'java.lang.NullPointerException: Attempt to invoke interface method 'void android.database.Cursor.close()' on a null object reference

https://github.com/kamaleshdas1997/MyPets

LOGCAT:-

    Process: com.example.mypets, PID: 21583
    java.lang.NullPointerException: Attempt to invoke interface method 'void android.database.Cursor.close()' on a null object reference
        at com.example.mypets.CatlogActivity.displayDatabaseInfo(CatlogActivity.java:133)
        at com.example.mypets.CatlogActivity.onStart(CatlogActivity.java:48)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1470)
        at android.app.Activity.performStart(Activity.java:7170)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3061)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2020-12-13 09:54:55.751 496-496/? E/SELinux: avc:  denied  { find } for service=opdiagnose pid=21583 uid=10312 scontext=u:r:untrusted_app:s0:c56,c257,c512,c768 tcontext=u:object_r:opdiagnose_service:s0 tclass=service_manager permissive=0
2020-12-13 09:54:55.751 496-496/? E/SELinux: avc:  denied  { find } for service=opdiagnose pid=21583 uid=10312 scontext=u:r:untrusted_app:s0:c56,c257,c512,c768 tcontext=u:object_r:opdiagnose_service:s0 tclass=service_manager permissive=0

CatlogActivity:

package com.example.mypets;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.example.mypets.data.PetContract.PetEntry;
import com.example.mypets.data.PetDBHelper;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

public class CatlogActivity extends AppCompatActivity {




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_catlog_activity);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(CatlogActivity.this , EditorActivty.class);
                startActivity(i);
            }
        });

    }


    @Override
    protected void onStart() {
        super.onStart();
        displayDatabaseInfo();

    }



    /**
     * Temporary helper method to display information in the onscreen TextView about the state of
     * the pets database.
     */
    private void displayDatabaseInfo() {


        // To access our database, we instantiate our subclass of SQLiteOpenHelper
        // and pass the context, which is the current activity.

        // Create and/or open a database to read from it
//        SQLiteDatabase db = mDbHelper.getReadableDatabase();


        TextView displayView = (TextView) findViewById(R.id.text_view_pet);



        //Projection
        String[] projection ={
                PetEntry._ID,
                PetEntry.COLUMN_PET_NAME,
                PetEntry.COLUMN_PET_BREED,
                PetEntry.COLUMN_PET_GENDER,
                PetEntry.COLUMN_PET_WEIGHT
        };

        // Perform this raw SQL query "SELECT * FROM pets"
//        // to get a Cursor that contains all rows from the pets table.
        Cursor cursor = getContentResolver().query(
                PetEntry.CONTENT_URI,
                projection,
                null,
                null,
                null
        );

        try {
            // Create a header in the Text View that looks like this:
            //
            // The pets table contains <number of rows in Cursor> pets.
            // _id - name - breed - gender - weight
            //
            // In the while loop below, iterate through the rows of the cursor and display
            // the information from each column in this order.
            displayView.setText("The pets table contains " + cursor.getCount() + " pets.\n\n");
            displayView.append(PetEntry._ID + " - " +
                    PetEntry.COLUMN_PET_NAME + " - " +
                    PetEntry.COLUMN_PET_BREED + " - " +
                    PetEntry.COLUMN_PET_GENDER + " - " +
                    PetEntry.COLUMN_PET_WEIGHT + "\n");

            // Figure out the index of each column
            int idColumnIndex = cursor.getColumnIndex(PetEntry._ID);
            int nameColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_NAME);
            int breedColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_BREED);
            int genderColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_GENDER);
            int weightColumnIndex = cursor.getColumnIndex(PetEntry.COLUMN_PET_WEIGHT);

            // Iterate through all the returned rows in the cursor
            while (cursor.moveToNext()) {
                // Use that index to extract the String or Int value of the word
                // at the current row the cursor is on.
                int currentID = cursor.getInt(idColumnIndex);
                String currentName = cursor.getString(nameColumnIndex);
                String currentBreed = cursor.getString(breedColumnIndex);
                int currentGender = cursor.getInt(genderColumnIndex);
                int currentWeight = cursor.getInt(weightColumnIndex);
                // Display the values from each column of the current row in the cursor in the TextView
                displayView.append(("\n" + currentID + " - " +
                        currentName + " - " +
                        currentBreed + " - " +
                        currentGender + " - " +
                        currentWeight));
            }
        }
            finally {
            // Always close the cursor when you're done reading from it. This releases all its
            // resources and makes it invalid.
            cursor.close();
        }
    }

    private void insertPet() {
        ContentValues contentValues = new ContentValues();
        contentValues.put(PetEntry.COLUMN_PET_NAME, "name");
        contentValues.put(PetEntry.COLUMN_PET_BREED, "breed");
        contentValues.put(PetEntry.COLUMN_PET_GENDER, PetEntry.GENDER_MALE);
        contentValues.put(PetEntry.COLUMN_PET_WEIGHT, 7);

        Uri newURI = getContentResolver().insert(PetEntry.CONTENT_URI, contentValues);

        Log.v("CatalogActivity" , "New Role ID" + newURI);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_catalog, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.action_delete_all_entries:
                insertPet();
                return true;


            case R.id.action_insert_dummy_data:
                insertPet();
                displayDatabaseInfo();

                return true;
        }

        return super.onOptionsItemSelected(item);
    }




}



Solution 1:[1]

After Building your program from the Guthub link, it's obvious your query to the Database doesn't match any element.

Commented out everywhere you make invoke a method on the cursor object and added the line of code below

if(cursor==null)
        Toast.makeText(getApplicationContext(),"null cursor",0).show();

And it's obvious it's null

Solution 2:[2]

  1. List item

@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Get readable database SQLiteDatabase database = mDbHelper.getReadableDatabase();

    // This cursor will hold the result of the query
    Cursor cursor;

    // Figure out if the URI matcher can match the URI to a specific code
    int match = sUriMatcher.match(uri);
    switch (match)
    {
        case PETS:
            // For the PETS code, query the pets table directly with the given
            // projection, selection, selection arguments, and sort order. The cursor
            // could contain multiple rows of the pets table.
            cursor=database.query(PetEntry.TABLE_NAME,projection,
                    selection,selectionArgs,null,null,sortOrder);

            break;
        case PET_ID:
            // For the PET_ID code, extract out the ID from the URI.
            // For an example URI such as "content://com.example.android.pets/pets/3",
            // the selection will be "_id=?" and the selection argument will be a
            // String array containing the actual ID of 3 in this case.
            //
            // For every "?" in the selection, we need to have an element in the selection
            // arguments that will fill in the "?". Since we have 1 question mark in the
            // selection, we have 1 String in the selection arguments' String array.
            selection = PetEntry._ID + "=?";
            selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };

            // This will perform a query on the pets table where the _id equals 3 to return a
            // Cursor containing that row of the table.
            cursor = database.query(PetEntry.TABLE_NAME, projection, selection, selectionArgs,
                    null, null, sortOrder);
            break;

        default:
            throw new IllegalArgumentException("Cannot query unknown URI " + uri);
    }

    return cursor;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2