Search code examples
androidnullpointerexceptionsimplecursoradapter

java.lang.NullPointerException when invoking onLoadFinished()


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);
    }

I keep receiving the error as following : java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor com.example.android.gloryinventory.ProductCursorAdapter.swapCursor(android.database.Cursor)' on a null object reference

Is there's something wrong with my code? Thanks in advance.


Solution

  • Because you are creating ProductCursorAdapter mCursorAdapter within the context of the class but initializing another local variable instead of that one in your onCreate. Here is the problematic line:

    ProductCursorAdapter mCursorAdapter = new ProductCursorAdapter(this, null);

    which should be:

    mCursorAdapter = new ProductCursorAdapter(this, null);