public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks { private static final int PRODUCT_LOADER = 0; ProductCursorAdapter mCursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_catalog); ListView productsListView = (ListView) findViewById(R.id.list); View emptyView = findViewById(R.id.empty_view); productsListView.setEmptyView(emptyView); ProductCursorAdapter mCursorAdapter = new ProductCursorAdapter(this, null); productsListView.setAdapter(mCursorAdapter); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(CatalogActivity.this, AddProductActivity.class); startActivity(intent); } }); productsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView adapterView, View view, int position, long id) { Intent intent = new Intent(CatalogActivity.this, DetailEditActivity.class); Uri currentProductUri = ContentUris.withAppendedId(ProductContract.ProductEntry.CONTENT_URI, id); intent.setData(currentProductUri); startActivity(intent); } }); Log.e("working fine" , "product"); getSupportLoaderManager().initLoader(PRODUCT_LOADER, null, this); } And the onLoadFinished() method is : public void onLoadFinished(Loader loader, Cursor data) { mCursorAdapter.swapCursor(data); }
我一直收到如下错误: java.lang.NullPointerException:尝试调用虚方法' android.database.Cursor com.example.android.gloryinventory.ProductCursorAdapter.swapCursor(android.database.Cursor)'在空对象引用上
我的代码有问题吗? 提前谢谢。
答案 0 :(得分:1)
因为您在类的上下文中创建了ProductCursorAdapter mCursorAdapter
,但是在onCreate
中初始化了另一个局部变量而不是那个局部变量。这是有问题的一行:
ProductCursorAdapter mCursorAdapter = new ProductCursorAdapter(this, null);
应该是:
mCursorAdapter = new ProductCursorAdapter(this, null);
答案 1 :(得分:1)
在onCreate()
而不是:
ProductCursorAdapter mCursorAdapter = new ProductCursorAdapter(this, null);
执行:
mCursorAdapter = new ProductCursorAdapter(this, null);
您正在onCreate()
内创建一个局部变量,因此您班级中的字段仍然未初始化。