ユーザーが演劇のリハーサル中にメモを作成できるアプリに取り組んでいます。ユーザーは、作成したメモをリストビューで表示し、必要に応じて編集および削除できます。
たとえば、ユーザーが 3 つのメモを作成したとします。データベースでは、row_id は 1、2、3 になります。そのため、ユーザーがリストビューでメモを表示すると、1、2、3 の順序になります (値をインクリメントする前は、最初は 0、1、2)。 . したがって、ユーザーはデータベースから正しい行を表示および削除できます。
問題は、ユーザーがメモを削除することを決定したときに発生します。ユーザーが位置 2 のメモを削除するとします。したがって、データベースには row_id の 1 と 3 があります。しかし、リストビューでは、位置 1 と 2 になります。したがって、ユーザーがリストビューの位置 2 のメモをクリックすると、データベース内のrow_id 3の行を返す必要があります。ただし、存在しないrow_id 2を検索しようとするため、クラッシュします。
リストビューでのユーザーの選択に応じて、対応する row_id を取得する方法を知る必要があります。これを行う以下のコードは次のとおりです。
// When the user selects "Delete" in context menu
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case DELETE_ID:
deleteNote(info.id + 1);
return true;
}
return super.onContextItemSelected(item);
}
// This method actually deletes the selected note
private void deleteNote(long id) {
Log.d(TAG, "Deleting row: " + id);
mNDbAdapter.deleteNote(id);
mCursor = mNDbAdapter.fetchAllNotes();
startManagingCursor(mCursor);
fillData();
// TODO: Update play database if there are no notes left for a line.
}
// When the user clicks on an item, display the selected note
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
viewNote(id, "", "", true);
}
// This is where we display the note in a custom alert dialog. I've ommited
// the rest of the code in this method because the problem lies in this line:
// "mCursor = mNDbAdapter.fetchNote(newId);"
// I need to replace "newId" with the row_id in the database.
private void viewNote(long id, String defaultTitle, String defaultNote,
boolean fresh) {
final int lineNumber;
String title;
String note;
id++;
final long newId = id;
Log.d(TAG, "Returning row: " + newId);
mCursor = mNDbAdapter.fetchNote(newId);
lineNumber = (mCursor.getInt(mCursor.getColumnIndex("number")));
title = (mCursor.getString(mCursor.getColumnIndex("title")));
note = (mCursor.getString(mCursor.getColumnIndex("note")));
.
.
.
}
これ以上コードを表示したい場合はお知らせください。とても単純なことのように思えますが、解決策が見つかりません。
ありがとう!
編集
問題を修正しました。以下の質問に答えました。