我有一个应用程序,当用户单击列表视图中的某个项目时,有关该项目的信息将显示在另一页中,用户可以单击“编辑”或“删除”按钮将其从列表中删除。
问题是删除的代码不起作用。详细信息页面只是关闭并返回到列表页面,而没有删除或修改任何内容。
列表页面
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent in=new Intent(showAll.this,editCar.class);
in.putExtra("car_id",position);
startActivity(in);
}
});
详细页面
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_car);
Button btnDelete=(Button) findViewById(R.id.button4);
Button btnEdit=(Button)findViewById(R.id.edut);
final EditText comName=(EditText)findViewById(R.id.edit_comp);
final EditText model=(EditText)findViewById(R.id.edit_model);
final CheckBox status=(CheckBox)findViewById(R.id.checkbox);
final int i=getIntent().getIntExtra("car_id",0);
Realm.init(getApplicationContext());
final Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
final RealmResults<Car> cars =realm.where(Car.class).findAll();
realm.commitTransaction();
final Car car3=cars.get(i);
realm.close();
comName.setText(car3.getName());
model.setText(car3.getModel());
status.setChecked(car3.isStatus());
final Context context=this;
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(editCar.this).setTitle("warning").setMessage("are you sure you want to delete this car ?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Realm.init(getApplicationContext());
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
car3.deleteFromRealm();
realm.commitTransaction();
realm.close();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() { //if user choose no do nothing
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context,"no",Toast.LENGTH_SHORT).show();
}
}).show(); //show dialog
答案 0 :(得分:1)
点击删除按钮即可添加此功能。这对我有用。 :)
Notifications
是我的模型课。
Realm realm = Realm.getDefaultInstance();
final Notifications deletedItem = yourArrayList.get(indexPosition);
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
RealmResults<Notifications> **rows** = realm.where(Notifications.class).equalTo("columnKeyName", columnKeyValue).findAll();
**rows**.deleteAllFromRealm();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
final int deletedIndex = indexPosition;
// remove the item from recycler view and notify adapter
yourArrayList.remove(deletedIndex);
adapter.notifyDataSetChanged();
希望这对您也有帮助。 :)