ListView
SQLiteテーブルからの値の束を表示するがあります。最初に、を使用して、SQLクエリからのカーソルに基づいて入力しましたSimpleCursorAdapter
。に送信する前にリスト内のデータを操作/追加する必要があったため、代わりListView
にを使用するように切り替えました。SimpleAdapter
ListView
SimpleCursorAdapter
行をタップした後に返されたIDを使用するListView
ことは、データベーステーブルからの正しいIDですが、IDを使用することは、位置と同じであるため、SimpleAdapter
によって生成されたばかりのように見えます。ListView
私のテーブルは次のようになります。
_id | col1 | col2 | col3
のカーソルを生成するメソッドはSimpleCursorAdapter
次のようになります。
public Cursor fetchDataAsCursor()
{
return db.query("table_name", new String[] { "_id", "col1", "col2"}, null, null, null, null, null);
}
ListView
使用法を入力するメソッドはSimpleCursorAdapter
次のようになります。
private void simpleFillData()
{
Cursor cursor = dbAdapter.fetchDataAsCursor();
startManagingCursor(cursor);
String[] from = new String[] {"col1", "col2"};
int[] to = new int[] {R.id.col1, R.id.col2};
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.list_row, cursor, from, to);
setListAdapter(notes);
}
次のメソッドでは、返されるIDに問題がないため、これは正常に機能します。
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, DetailActivity.class);
i.putExtra("_id", id);
startActivityForResult(i, ACTIVITY_EDIT);
}
次に、に切り替えSimpleAdapter
ます。
を生成するためのコードList
:
public ArrayList<HashMap<String, Object>> getList()
{
ArrayList <HashMap<String, Object>> list = new ArrayList();
c = fetchDataAsCursor();
c.moveToFirst();
for(int i = 0; i < c.getCount(); i++)
{
HashMap<String, Object> h = new HashMap<String, Object>();
h.put("_id", c.getLong(0));
h.put("col1", c.getString(1));
h.put("col2", c.getString(2));
//This is the extra column
h.put("extra", calculateSomeStuff(c.getString(1), c.getString(2));
list.add(h);
c.moveToNext();
}
return list;
}
そして、ListView
:を満たすメソッドの場合
private void fillData()
{
ArrayList<HashMap<String, Object>> list = dbAdapter.getList();
String[] from = new String[] {"col1", "col2", "extra"};
int[] to = new int[] {R.id.col1, R.id.col2, R.id.extra};
SimpleAdapter notes = new SimpleAdapter(this, list, R.layout.list_row, from, to);
setListAdapter(notes);
}
この最後の方法では、リスト内の値のListView
取得に失敗します。_id
私はそれが使用するときと同じようにこれを自動的に行うだろうと推測したでしょうSimpleCursorAdapter
の行のIDを操作して、データベーステーブルListView
のキーと同じ値になるようにする方法はありますか?_id
(すべてのコード例は大幅に簡略化されています)
編集:
私はそれを考え出した。SimpleAdapter
オーバーライドする独自のサブクラスを作成する必要がありましたpublic long getItemId(int position)
public class MyListAdapter extends SimpleAdapter
{
private final String ID = "_id";
public PunchListAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
{
super(context, data, resource, from, to);
}
@Override
public long getItemId(int position)
{
Object o = getItem(position);
long id = position;
if(o instanceof Map)
{
Map m = (Map)o;
if(m.containsKey(ID))
{
o = m.get(ID);
if(o instanceof Long)
id = (Long)o;
}
}
return id;
}
}