我在我的应用程序中设置了一个内容提供程序并使用 LoaderManager 加载数据但是我在将游标交换到游标适配器时遇到了麻烦,我测试了游标是否正在返回数据并且它正在返回!跟踪问题,似乎 ad.swapCursor(cursor);
是问题所在。
你认为我做错了什么?它可能是内容提供商吗?
public class Main extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {
public SimpleCursorAdapter ad;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getLoaderManager().initLoader(0, null, Main.this) != null);
ad = new SimpleCursorAdapter(this, android.R.id.list, null, null, null, 0);
}
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
Toast.makeText(this, "Started!", Toast.LENGTH_SHORT).show();
CursorLoader cursorLoader = new CursorLoader(getBaseContext(),
AviatorContentProvider.LISTS_URI, null, null, null, null);
if(cursorLoader != null){
Toast.makeText(this, "This thing is heavy!", Toast.LENGTH_SHORT).show();
}
return cursorLoader;
}
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
// TODO Auto-generated method stub
ad.swapCursor(cursor);
}
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}}
谢谢
最佳答案
您永远不会初始化您的 SimpleCursorAdapter
“广告”。尝试在适配器上调用 swapCursor
时,您可能会遇到空指针异常。
在 onCreate
中初始化您的适配器并传入一个空游标(因为尚未加载任何数据)。
String[] from = new String[] { COLUMN_NAME_FROM_YOUR_CURSOR };
int[] to = new int[] { android.R.id.text1 };
ad = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to,0);
注意我在哪里有“COLUMN_NAME_FROM_YOUR_CURSOR”。您需要将其中一列的字符串值放在那里(来自常量或硬编码值)
确保检查 logcat 以查看收到的错误。它会准确地告诉您错误是什么以及导致错误的代码行。
关于java - 使用 SimpleAdapterCursor swapCursor() 交换游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607919/