我正在使用UI上的长按从我的本地数据库中删除一行,删除后,该行将从用户界面的列表中自动删除。
public class AllData extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
DotCursorAdapter mAdapter;
private ListView lv;
Context context = this;
private final int LOADER_ID = 860;
public static DatabaseHandler dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lv = (ListView) findViewById(R.id.lists);
dbHelper = new DatabaseHandler(this);
mAdapter = new DotCursorAdapter(this, null, 1);
getSupportLoaderManager().initLoader(LOADER_ID, null, this);
lv.setAdapter(mAdapter);
lv.setTextFilterEnabled(true);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new DumbLoader(this);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mAdapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mAdapter.swapCursor(null);
}
/**
* DumbLoader sub class
*/
public static class DumbLoader extends CursorLoader {
public DumbLoader(Context context) {
super(context);
}
@Override
public Cursor loadInBackground() {
Cursor c = dbHelper.FetchAllData();
return c;
}
}
public final class DotCursorAdapter extends CursorAdapter {
public DotCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.visitation_activity, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
/**
* Data from the local database
*/
final String id = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
final String date = cursor.getString(cursor.getColumnIndexOrThrow("created_at"));
view.setTag(Long.valueOf(id));
view.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
((AllData) mContext).deleteData(((Long) view.getTag()).longValue());
return true;
}
});
}
}
/**
* Delete data and update list view
*/
public void deleteData(long id) {
final long alarmId = id;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please confirm")
.setTitle("Delete set?")
.setCancelable(true)
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dbHelper.deleteData(alarmId);
//Refresh the list of the alarms in the adaptor
dbHelper.FetchAllData();
//Notify the adapter the data has changed
mAdapter.notifyDataSetChanged();
}
}).show();
}}
使用上面的代码,我可以从本地数据库中删除数据,但它不会从用户界面中删除已删除的行,除非我刷新页面。
有没有办法在删除后自动从列表视图中删除已删除的行。提前谢谢。
答案 0 :(得分:2)
使用此getSupportLoaderManager().restartLoader(0, null, AllData.this);
代替mAdapter.notifyDataSetChanged();
来刷新列表项
答案 1 :(得分:0)
或者您可以使用intent并保持源活动和目标活动相同.....并在删除行后使用此行
Intent i = new Intent(sourceActivity.this,targetActivity.this);
startActivity(i);
sourceActivity.finish();