2017-10-05 2 views
-3

Ich habe eine App gemacht, die den Benutzer Standort durch Ortsauswahl hinzufügen und fügen Sie sie in die SQLite-Datenbank.Ich zeige diese Standorte in Recyclerview. Um einen Artikel aus der Recycleransicht zu löschen, habe ich das bisher gemacht.Datensatz löschen von SQLite-Datenbank über Recyclerview in Android

1) Der Benutzer drückt lange auf ein Element in der Recycleransicht und dann erscheint ein Warndialog mit 2 Schaltflächen (Löschen und Abbrechen).

Was ich kann nicht-do:

1) Nun weiß ich nicht, wie ein Element aus recyclerview zu löschen und von SQLite-Datenbank, wenn der Benutzer auf die Schaltfläche Löschen tippt.

Ich habe es gesucht, aber nicht wie es implementiert werden kann. Ich poste den Code für die Klasse MainActivity.java, die Klasse PlaceDbhelper.java und die Klasse PlacelistAdapter.java.

MainActivity.java Klasse

public class MainActivity extends AppCompatActivity implements 
    ConnectionCallbacks, 
    OnConnectionFailedListener { 

// Constants 
public static final String TAG = MainActivity.class.getSimpleName(); 
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111; 
private static final int PLACE_PICKER_REQUEST = 1; 

// Member variables 
private PlaceListAdapter mAdapter; 
private RecyclerView mRecyclerView; 
private boolean mIsEnabled; 
private GoogleApiClient mClient; 
private Geofencing mGeofencing; 

//String arr; 


/** 
* Called when the activity is starting 
* 
* @param savedInstanceState The Bundle that contains the data supplied in onSaveInstanceState 
*/ 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Set up the recycler view 
    mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view); 
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); 
    mAdapter = new PlaceListAdapter(this, null); 
    mRecyclerView=(RecyclerView)findViewById(R.id.places_list_recycler_view); 
    mRecyclerView.setAdapter(mAdapter); 


    Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch); 
    mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled), false); 
    onOffSwitch.setChecked(mIsEnabled); 
    onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); 
      editor.putBoolean(getString(R.string.setting_enabled), isChecked); 
      mIsEnabled = isChecked; 
      editor.commit(); 
      if (isChecked) mGeofencing.registerAllGeofences(); 
      else mGeofencing.unRegisterAllGeofences(); 
     } 

    }); 


      mClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .addApi(Places.GEO_DATA_API) 
      .enableAutoManage(this, this) 
      .build(); 

    mGeofencing = new Geofencing(this, mClient); 
    mRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, 
      mRecyclerView, new ClickListener() { 



     public void onClick(View view, final int position) { 

      picture.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 

       } 
      });*/ 

     } 
     public void onItemClick(View view, int position) { 



     } 

     @Override 
     public void onLongClick(View view, int position) { 

      final AlertDialog alertDialog =new AlertDialog.Builder(MainActivity.this).create(); 
      alertDialog.setTitle("Are you want to delete this"); 
      alertDialog.setCancelable(false); 
      alertDialog.setMessage("By deleting this, item will permanently be deleted. Are you still want to delete this?"); 
      alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 



       } 
      }); 
      alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Delete", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 







       } 
      }); 
      alertDialog.show(); 
      Toast.makeText(MainActivity.this, "Long press on position :"+position, 
        Toast.LENGTH_LONG).show(); 
     } 
    })); 




     } 

/*** 
* Called when the Google API Client is successfully connected 
* 
* @param connectionHint Bundle of data provided to clients by Google Play services 
*/ 
@Override 
public void onConnected(@Nullable Bundle connectionHint) { 
    refreshPlacesData(); 
    Log.i(TAG, "API Client Connection Successful!"); 
} 

/*** 
* Called when the Google API Client is suspended 
* 
* @param cause cause The reason for the disconnection. Defined by constants CAUSE_*. 
*/ 
@Override 
public void onConnectionSuspended(int cause) { 
    Log.i(TAG, "API Client Connection Suspended!"); 
} 

/*** 
* Called when the Google API Client failed to connect to Google Play Services 
* 
* @param result A ConnectionResult that can be used for resolving the error 
*/ 
@Override 
public void onConnectionFailed(@NonNull ConnectionResult result) { 
    Log.e(TAG, "API Client Connection Failed!"); 
} 

public void refreshPlacesData() { 
    Uri uri = PlaceContract.PlaceEntry.CONTENT_URI; 
    Cursor data = getContentResolver().query(
      uri, 
      null, 
      null, 
      null, 
      null); 

    if (data == null || data.getCount() == 0) return; 
    List<String> guids = new ArrayList<String>(); 
    while (data.moveToNext()) { 
     guids.add(data.getString(data.getColumnIndex(PlaceContract.PlaceEntry.COLUMN_PLACE_ID))); 
    } 
    PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mClient, 
      guids.toArray(new String[guids.size()])); 
    placeResult.setResultCallback(new ResultCallback<PlaceBuffer>() { 
     @Override 
     public void onResult(@NonNull PlaceBuffer places) { 
      mAdapter.swapPlaces(places); 
      mGeofencing.updateGeofencesList(places); 
      if (mIsEnabled) mGeofencing.registerAllGeofences(); 
     } 
    }); 
} 


public void onAddPlaceButtonClicked(View view) { 
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 
     Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_LONG).show(); 
     return; 
    } 
    try { 

     PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); 
     Intent i = builder.build(this); 
     startActivityForResult(i, PLACE_PICKER_REQUEST); 
    } catch (GooglePlayServicesRepairableException e) { 
     Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage())); 
    } catch (GooglePlayServicesNotAvailableException e) { 
     Log.e(TAG, String.format("GooglePlayServices Not Available [%s]", e.getMessage())); 
    } catch (Exception e) { 
     Log.e(TAG, String.format("PlacePicker Exception: %s", e.getMessage())); 
    } 
} 


/*** 
* Called when the Place Picker Activity returns back with a selected place (or after canceling) 
* 
* @param requestCode The request code passed when calling startActivityForResult 
* @param resultCode The result code specified by the second activity 
* @param data  The Intent that carries the result data. 
*/ 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (requestCode == PLACE_PICKER_REQUEST && resultCode == RESULT_OK) { 
     Place place = PlacePicker.getPlace(this, data); 
     if (place == null) { 
      Log.i(TAG, "No place selected"); 
      return; 
     } 

     String placeID = place.getId(); 

     // Insert a new place into DB 
     ContentValues contentValues = new ContentValues(); 
     contentValues.put(PlaceContract.PlaceEntry.COLUMN_PLACE_ID, placeID); 
     getContentResolver().insert(PlaceContract.PlaceEntry.CONTENT_URI, contentValues); 

     // Get live data information 
     refreshPlacesData(); 
    } 
} 

@Override 
public void onResume() { 
    super.onResume(); 

    // Initialize location permissions checkbox 
    CheckBox locationPermissions = (CheckBox) findViewById(R.id.location_permission_checkbox); 
    if (ActivityCompat.checkSelfPermission(MainActivity.this, 
      android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     locationPermissions.setChecked(false); 
    } else { 
     locationPermissions.setChecked(true); 
     locationPermissions.setEnabled(false); 
    } 

    // Initialize ringer permissions checkbox 
    CheckBox ringerPermissions = (CheckBox) findViewById(R.id.ringer_permissions_checkbox); 
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    // Check if the API supports such permission change and check if permission is granted 
    if (android.os.Build.VERSION.SDK_INT >= 24 && !nm.isNotificationPolicyAccessGranted()) { 
     ringerPermissions.setChecked(false); 
    } else { 
     ringerPermissions.setChecked(true); 
     ringerPermissions.setEnabled(false); 
    } 
} 

public void onRingerPermissionsClicked(View view) { 
    Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS); 
    startActivity(intent); 
} 

public void onLocationPermissionClicked(View view) { 
    ActivityCompat.requestPermissions(MainActivity.this, 
      new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
      PERMISSIONS_REQUEST_FINE_LOCATION); 
} 




public static interface ClickListener{ 
    public void onClick(View view,int position); 
    public void onLongClick(View view,int position); 
} 


class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{ 

    private ClickListener clicklistener; 
    private GestureDetector gestureDetector; 

    public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){ 

     this.clicklistener=clicklistener; 
     gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){ 
      @Override 
      public boolean onSingleTapUp(MotionEvent e) { 
       return true; 
      } 

      @Override 
      public void onLongPress(MotionEvent e) { 
       View child=recycleView.findChildViewUnder(e.getX(),e.getY()); 
       if(child!=null && clicklistener!=null){ 
        clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child)); 
       } 
      } 
     }); 

    } 


    @Override 
    public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { 
     View child=rv.findChildViewUnder(e.getX(),e.getY()); 
     if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){ 
      clicklistener.onClick(child,rv.getChildAdapterPosition(child)); 
     } 

     return false; 
    } 

    @Override 
    public void onTouchEvent(RecyclerView rv, MotionEvent e) { 

    } 

    @Override 
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { 

    } 
} 

} 

PlaceDbhelper.java Klasse

public class PlaceDbHelper extends SQLiteOpenHelper { 

// The database name 
private static final String DATABASE_NAME = "location.db"; 
PlaceListAdapter obj1; 


// If you change the database schema, you must increment the database version 
private static final int DATABASE_VERSION = 1; 

// Constructor 
public PlaceDbHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
} 

@Override 
public void onCreate(SQLiteDatabase sqLiteDatabase) { 

    // Create a table to hold the places data 
    final String SQL_CREATE_PLACES_TABLE = "CREATE TABLE " + PlaceEntry.TABLE_NAME + " (" + 
      PlaceEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + 
      PlaceEntry.COLUMN_PLACE_ID + " TEXT NOT NULL, " + 
      "UNIQUE (" + PlaceEntry.COLUMN_PLACE_ID + ") ON CONFLICT REPLACE" + 
      "); "; 

    sqLiteDatabase.execSQL(SQL_CREATE_PLACES_TABLE); 
} 
String pe=PlaceEntry._ID.toString(); 
@Override 
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { 
    // For now simply drop the table and create a new one. 
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + PlaceEntry.TABLE_NAME); 
    onCreate(sqLiteDatabase); 
    } 

PlacelistAdapter.java Klasse

public class PlaceListAdapter extends 
RecyclerView.Adapter<PlaceListAdapter.PlaceViewHolder> { 

private Context mContext; 
private PlaceBuffer mPlaces; 
PlaceDbHelper obj1; 
RecyclerView recycleview; 

public PlaceListAdapter(Context context, PlaceBuffer places) { 
    this.mContext = context; 
    this.mPlaces = places; 
} 


@Override 
public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
    // Get the RecyclerView item layout 
    LayoutInflater inflater = LayoutInflater.from(mContext); 
    View view = inflater.inflate(R.layout.item_place_card, parent, false); 
    //final Activity activity; 
    return new PlaceViewHolder(view); 
} 


@Override 
public void onBindViewHolder(PlaceViewHolder holder, int position) { 
    String placeName = mPlaces.get(position).getName().toString(); 
    String placeAddress = mPlaces.get(position).getAddress().toString(); 
    holder.nameTextView.setText(placeName); 
    holder.addressTextView.setText(placeAddress); 
} 


public void swapPlaces(PlaceBuffer newPlaces) { 
    mPlaces = newPlaces; 
    if (mPlaces != null) { 
     // Force the RecyclerView to refresh 
     this.notifyDataSetChanged(); 
    } 
} 


@Override 
public int getItemCount() { 
    if (mPlaces == null) return 0; 
    return mPlaces.getCount(); 
} 


/** 
* PlaceViewHolder class for the recycler view item 
*/ 
class PlaceViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { 

    TextView nameTextView; 
    TextView addressTextView; 

    public PlaceViewHolder(final View itemView) { 
     super(itemView); 
     nameTextView = (TextView) itemView.findViewById(R.id.name_text_view); 
     addressTextView = (TextView) itemView.findViewById(R.id.address_text_view); 


    } 

    @Override 
    public void onClick(View v) { 

    } 
+0

Wo ist Ihr Code zum Hinzufügen der Orte zur Datenbank? – sumit

+0

Zum Entfernen von der Liste können Sie mPlace.remove (Position); im Alarmdialog –

+0

@AmjadKhan Sie meinen, wenn der Benutzer auf die Schaltfläche "Löschen" klicken wird, dann verschwindet dieser Artikel aus der Recycleransicht? –

Antwort

0

I-Lösung für Sie haben, müssen Sie Reihe von db löschen und dann entfernen Sie von Ihrer Arraylist und nachdem Sie es Adapter benachrichtigen. Wie unten.

Verwenden Sie diese Methode in Ihrer PlaceDbhelper.java Klasse

public void removePlace(String placeId){ 
     SQLiteDatabase db = this.getWritableDatabase(); 
     db.delete(PlaceEntry.TABLE_NAME, PlaceEntry.COLUMN_PLACE_ID + "=\"" + placeId+"\"", null) ; 
} 

jetzt diese Methode in Alarm aufrufen, wenn Klick DELETE

private void deletePlace(int position){ 
     PlaceDbhelper dbHelper = new PlaceDbhelper(MainActivity.this); 
     dbHelper.removePlace(placeArraylist.get(position).getPlaceId()); 
     placeArraylist.remove(position); 
     mAdapter.notifyDataSetChanged(); 
} 

Hope this Sie helfen, Wenn dies Ihr Problem make lösen es hat zugestimmt. Fragen Sie, ob Sie Hilfe brauchen.

+0

dass deleteproduct Methode eingebaut ist oder wie haben Sie es verwendet oder ich muss es irgendwo definieren. –

+0

* deletePlace * Methode sollte in Alarm verwendet werden und * removePlace * Methode wird in Ihrem Datenbankhelfer.Ich postete Ihre Lösung, jetzt müssen Sie diesen Code in Ihrem Projekt festlegen. –

+0

Ich habe Ihre Punkt, aber ich weiß nicht über deleteProduct-Methode, die Sie verwendet haben –

Verwandte Themen