【发布时间】:2015-03-31 16:44:13
【问题描述】:
当点击listview 的项目时,它会在另一个具有edittext 的活动中打开。编辑一个项目后,当我保存它时,项目不会在列表视图中更新,但它会在列表视图中插入一个新条目。
如何在不插入新项目的情况下更新现有项目?
这是我的代码
活动:TRList.class
ArrayList<HashMap<String, String>> items = new ArrayList<>();
List<TRListFormat> list = trDb.getAllReminders();
for (TRListFormat val : list) {
HashMap<String, String> map = new HashMap<>();
map.put("title",val.getTitle());
map.put("description", val.getDes());
map.put("date", val.getDate());
map.put("time", val.getTime());
items.add(map);
}
adapter = new SimpleAdapter(this, items, R.layout.tr_list_format,
new String[] { "title", "description", "date", "time" },
new int[] {R.id.tbr_title, R.id.tbr_des, R.id.tbr_date, R.id.tbr_time });
lv = (ListView)findViewById(R.id.tbr_list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(TRList.this, TRTimeReminder.class);
intent.putExtra("remId", (int)id);
startActivity(intent);
}
});
当listView 项目被点击时,它会打开另一个活动
TRTimeReminder.class我在menu中设置了保存按钮
case R.id.menu_tbr_done:
String title = edTitle.getText().toString();
String des = edDes.getText().toString();
String time = timeView.getText().toString();
String date = dateView.getText().toString();
Bundle extras = getIntent().getExtras();
if(extras != null) {
int value = extras.getInt("remId");
if (value > 0) {
trDb.updateReminder(new TRListFormat(value, title, des, date, time));
}
}
else{
trDb.addReminder(new TRListFormat(title, des, date, time));
}
Intent i = new Intent(getApplicationContext(), TRList.class);
startActivity(i);
edTitle.getText().clear();
edDes.getText().clear();
dateView.setText(currDate);
timeView.setText(currTime);
return true;
TRDBHelper.class
//Add new reminder
void addReminder(TRListFormat format){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_TITLE, format.getTitle());
values.put(COLUMN_DES, format.getDes());
values.put(COLUMN_DATE, format.getDate());
values.put(COLUMN_TIME, format.getTime());
db.insert(TABLE_NAME, null, values);
db.close();
}
//Update single reminder
public void updateReminder(TRListFormat format){
SQLiteDatabase db = this.getWritableDatabase();
int id = format.getId();
ContentValues values = new ContentValues();
values.put(COLUMN_ID, format.getId());
values.put(COLUMN_TITLE, format.getTitle());
values.put(COLUMN_DES, format.getDes());
values.put(COLUMN_DATE, format.getDate());
values.put(COLUMN_TIME, format.getTime());
db.update(TABLE_NAME, values, COLUMN_ID+ " = " +id, null);
db.close();
}
【问题讨论】:
-
请在您创建适配器的地方发布代码。
-
我不确定 SQLite,但我在不久前编写的应用程序中使用 MS SQL Server 观察到了这种行为。如果没有要更新的行,则对 Update 的调用会插入一行。
-
您确定调用的是您的
updateReminder方法,而不是addReminder? -
@Marcus 如果你看到我的保存按钮的代码,我设置
updateReminder只有当id>0时,否则它会插入一个新的提醒。请参阅我的代码中的 if..else..。我想我在那里做错了什么。 -
@Rohit5k2 谢谢,但我想这与适配器无关。它插入一个项目并检索,所以我的适配器没有错误。
标签: android database sqlite listview