我仍然在思考ContentProviders,Loaders和SimpleCursorAdapters(我发现使用旧的startManagingCursor方法更容易)。本质上,我有一个 ListView 活动,当单击列表项时,将打开一个新活动,该活动的所有字段都填充了数据库中的数据。然后,用户可以删除记录,或更改字段并保存更改。我会提前为这篇文章的长度道歉,但我不确定什么可能/可能不相关。
我将首先为您提供旧代码(正在运行):
public class FuncLogbook extends DashMenuActivity implements OnItemClickListener {
private ListView list_LogbookResults;
private ListAdapter list_LogbookAdap;
private ArrayList<DBDetails> LogbookArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.dash_logbook);
list_LogbookResults = (ListView) findViewById(R.id.list_logbook);
list_LogbookResults.setOnItemClickListener(this);
LogbookArrayList = new ArrayList<DBDetails>();
list_LogbookAdap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
list_LogbookResults.setAdapter(list_LogbookAdap);
}
@SuppressWarnings("deprecation")
public List<String> populateList() {
List<String> BGLResultsList = new ArrayList<String>();
DBProvider mDBLogbook = new DBProvider();
AddDBHelper logbook = new AddDBHelper(this);
logbook.open();
Cursor cur = logbook.getEntries();
Cursor cur = mDBLogbook.query(DBProvider.CONTENT_URI, null, null, null, null);
startManagingCursor(cur);
while (cur.moveToNext()) {
String RowID = cur.getString(0);
String Time = cur.getString(1);
String Date = cur.getString(2);
String BGL = cur.getString(5);
DBDetails detailsClass = new DBDetails();
detailsClass.setuRow(RowID);
detailsClass.setuTime(Time);
detailsClass.setuDate(Date);
detailsClass.setuBGL(BGL);
LogbookArrayList.add(detailsClass);
BGLResultsList.add("BGL: " + BGL + "nRow ID: " + RowID
+"nDate: " + Date +"nTime: " + Time);
}
return BGLResultsList;
}
@Override
protected void onResume() {
super.onResume();
LogbookArrayList = new ArrayList<DBDetails>();
list_LogbookAdap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
list_LogbookResults.setAdapter(list_LogbookAdap);
}
@Override
protected void onStart() {
super.onStart();
LogbookArrayList = new ArrayList<DBDetails>();
list_LogbookAdap = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
list_LogbookResults.setAdapter(list_LogbookAdap);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent UpdateDBDetails = new Intent(this, UpdateDBDetails.class);
DBDetails clickedObject = LogbookArrayList.get(arg2);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickeduRowId", clickedObject.getuRow());
dataBundle.putString("clickeduTime", clickedObject.getuTime());
dataBundle.putString("clickeduDate", clickedObject.getuDate());
dataBundle.putString("clickeduBGL", clickedObject.getuBGL());
UpdateDBDetails.putExtras(dataBundle);
startActivity(UpdateDBDetails);
}
新代码:
public class FuncLogbook extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener {
private SimpleCursorAdapter adapter;
private ArrayList<DBDetails> LogbookArrayList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.dash_logbook);
this.getListView().setDividerHeight(2);
fillData();
ListView list = getListView();
list.setOnItemClickListener(this); }
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}
private void fillData() {
String[] from = new String[] { AddDBHelper.KEY_BGL, AddDBHelper.KEY_ROWID,
AddDBHelper.KEY_CATEG, AddDBHelper.KEY_TIME };
int[] to = new int[] {R.id.logBGL, R.id.logRowID, R.id.logCateg, R.id.logTime };
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.logbook_item, null, from, to, 0);
setListAdapter(adapter);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = { AddDBHelper.KEY_ROWID, AddDBHelper.KEY_BGL,
AddDBHelper.KEY_CATEG, AddDBHelper.KEY_TIME };
CursorLoader cl = new CursorLoader(this, DBProvider.CONTENT_URI,
projection, null, null, null);
return cl;
}
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent UpdateDBDetails = new Intent(this, UpdateDBDetails.class);
/*DBDetails clickedObject = LogbookArrayList.get(pos);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickeduRowId", clickedObject.getuRow());
dataBundle.putString("clickeduTime", clickedObject.getuTime());
dataBundle.putString("clickeduDate", clickedObject.getuDate());
dataBundle.putString("clickeduBGL", clickedObject.getuBGL());
UpdateDBDetails.putExtras(dataBundle);*/
startActivity(UpdateDBDetails);
}
运行它时,我在读取DBDetails clickedObject = LogbookArrayList.get(pos);
的行上收到一个 NullPointerException。 我知道拥有 ArrayList 是错误的,但我能找到的唯一教程要么展示如何将 ArrayList 与 onItemClick 一起使用,要么展示如何在 Toast 消息中使用选定的 id,但我似乎无法将信息放入捆绑包中以传递给活动。 任何帮助,不胜感激。
更新
根据Luksprog的回答,我修改为
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent UpdateDBDetails = new Intent(this, UpdateDBDetails.class);
Cursor c = (Cursor) adapter.getItem(pos);
Toast.makeText(getApplicationContext(), "Clicked Record Number " + id + " at " + pos,
Toast.LENGTH_SHORT).show();
Bundle dataBundle = new Bundle();
dataBundle.putString("clickeduRowId", c.getString(c.getColumnIndex(AddDBHelper.KEY_ROWID)));
dataBundle.putString("clickeduTime", c.getString(c.getColumnIndex(AddDBHelper.KEY_TIME)));
dataBundle.putString("clickeduDate", c.getString(c.getColumnIndex(AddDBHelper.KEY_DATE)));
dataBundle.putString("clickeduBGL", c.getString(c.getColumnIndex(AddDBHelper.KEY_BGL)));
UpdateDBDetails.putExtras(dataBundle);
startActivity(UpdateDBDetails);
}
如果我不向光标添加强制转换,则会引发错误,因此Cursor c = (Cursor) adapter.getItem(pos);
这仍然不起作用。日志猫显示:
10-21 23:24:02.167: E/CursorWindow(2663): Failed to read row 2, column -1 from a CursorWindow which has 8 rows, 4 columns.
10-21 23:24:02.178: E/AndroidRuntime(2663): FATAL EXCEPTION: main
10-21 23:24:02.178: E/AndroidRuntime(2663): java.lang.IllegalStateException: Couldn't read row 2, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.database.CursorWindow.nativeGetString(Native Method)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.database.CursorWindow.getString(CursorWindow.java:434)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.database.CursorWrapper.getString(CursorWrapper.java:114)
10-21 23:24:02.178: E/AndroidRuntime(2663): at com.rone.glucometer.FuncLogbook.onItemClick(FuncLogbook.java:227)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.widget.AdapterView.performItemClick(AdapterView.java:298)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2855)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.widget.AbsListView$1.run(AbsListView.java:3529)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.os.Handler.handleCallback(Handler.java:615)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.os.Handler.dispatchMessage(Handler.java:92)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.os.Looper.loop(Looper.java:137)
10-21 23:24:02.178: E/AndroidRuntime(2663): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-21 23:24:02.178: E/AndroidRuntime(2663): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 23:24:02.178: E/AndroidRuntime(2663): at java.lang.reflect.Method.invoke(Method.java:511)
10-21 23:24:02.178: E/AndroidRuntime(2663): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-21 23:24:02.178: E/AndroidRuntime(2663): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-21 23:24:02.178: E/AndroidRuntime(2663): at dalvik.system.NativeStart.main(Native Method)
更新我意识到上述日志猫错误是由于我没有列出 onCreateLoader 中的所有列;为了简单起见并减小大小,我在此示例中仅列出了 4 列,但我有接近 15 列。谢谢,您的代码运行良好 Luksprog
第二次尝试不起作用,因为您使用的ArrayList
现在未初始化,因为您使用基于Cursor
的适配器。相反,您应该从适配器获取Cursor
(使用getItem(position)
方法,您将获得正确行的Cursor
位置)并从中获取数据:
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent UpdateDBDetails = new Intent(this, UpdateDBDetails.class);
Cursor c = adapter.getItem(position);
Bundle dataBundle = new Bundle();
dataBundle.putString("clickeduRowId", c.getString(c.getColumnIndex(the_index_for_this_column_data))); // One of the fields from AddDBHelper.KEY_BGL, AddDBHelper.KEY_ROWID, AddDBHelper.KEY_CATEG, AddDBHelper.KEY_TIME
// the same for the other fields.
UpdateDBDetails.putExtras(dataBundle);
startActivity(UpdateDBDetails);
}
此外,为了安全起见,请在实例化适配器后调用LoaderManager
。