0

This is the onCreate method of the MainActivity, which comes right after the LoginActivity.

public class MainActivity extends AppCompatActivity {

GridView medicineGrid;
ArrayList<Medicine> medicineArrayList;
GridAdapter adapter;
SQLiteHelper sqLiteHelper;    

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    medicineGrid = (GridView) findViewById(R.id.gv_med_list);
    try {
        sqLiteHelper = new SQLiteHelper(MainActivity.this);
    }catch (NullPointerException e){
        e.printStackTrace();
    }        
    medicineArrayList = new ArrayList<Medicine>();

    medicineArrayList = sqLiteHelper.getAllMedicine();
    adapter = new GridAdapter(MainActivity.this, medicineArrayList);
    medicineGrid.setAdapter(adapter);
}

And when the MainActivity is getting executed the application is getting crashed with the NullPointer Exception as below:

FATAL EXCEPTION: main Process: com.example.amitava.medikart, PID: 4662 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.amitava.medikart/com.example.amitava.medikart.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6077) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference at com.example.amitava.medikart.SQLiteHelper.onCreate(SQLiteHelper.java:57) at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251) at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187) at com.example.amitava.medikart.SQLiteHelper.getAllMedicine(SQLiteHelper.java:170) at com.example.amitava.medikart.MainActivity.onCreate(MainActivity.java:40) at android.app.Activity.performCreate(Activity.java:6662) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6077)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)  Application terminated.

This is the SQLiteOpenHelper class what I've written, please check if I've done something wrong here -

public class SQLiteHelper extends SQLiteOpenHelper{

//Database details
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "MedicineDatabase.db";

//Table details within the database
public static final String TABLE_NAME = "MEDICINE";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_MEDICINE_NAME = "NAME";
public static final String COLUMN_CATEGORY = "CATEGORY";
public static final String COLUMN_DESCRIPTION = "DESCRIPTION";
public static final String COLUMN_IMAGE_BITMAP = "IMAGE";
public static final String COLUMN_STRENGTH = "STRENGTH";
public static final String COLUMN_PRICE = "PRICE";

public Context context;

public SQLiteHelper(Context context){
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    //Create New Table
    sqLiteDatabase.execSQL("Create Table " + TABLE_NAME + "(" + COLUMN_ID + " Integer Primary Key Autoincrement, " +
            COLUMN_MEDICINE_NAME + " Varchar, " + COLUMN_CATEGORY + " Varchar, " + COLUMN_DESCRIPTION + " Varchar, " +
            COLUMN_STRENGTH + " Varchar, " + COLUMN_PRICE + " Varchar, " + COLUMN_IMAGE_BITMAP + " Blob);");
    //Insert static data into the table which would work as a API for the dummy project
    //First row
    Bitmap bitmap1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.atorvastatin);
    byte[] picture1 = getBytes(bitmap1);
    addEntry("Atorvastatin", "Cardiac", "Atorvastatin is used along with a proper diet to help" +
            " lower \"bad\" cholesterol and fats (such as LDL, triglycerides) and raise \"good\" cholesterol (HDL) in the blood." +
            " It belongs to a group of drugs known as \"statins.\" It works by reducing the amount of cholesterol made by the liver. " +
            "Lowering \"bad\" cholesterol and triglycerides and raising \"good\" cholesterol decreases the risk of heart disease and helps" +
            " prevent strokes and heart attacks.", "10 mg", "610", picture1);
    //Second Row
    Bitmap bitmap2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.amlodipine_besylate_atenolol);
    byte[] picture2 = getBytes(bitmap2);
    addEntry("Amlodipine Besylate Atenolol", "Cardiac", "Amlodipine ATenolol Tablet is used for Hypertension, " +
            "Elevated blood pressure, Blood pressure, Chest pain, Coronary artery disease, High blood pressure and other conditions. Amlodipine" +
            " ATenolol Tablet works by inhibiting the influx of calcium ions into vascular smooth muscle and cardiac muscles; blocking receptors" +
            " resulting in slowing of heart rate and reducing oxygen demand", "50 mg", "350", picture2);
    //Third Row...}

Please help me understand why am I getting NullPointerException for caling getResources() method

  • 1
    look at the `context` variable in your subclass... – luk2302 Mar 18 '18 at 16:05
  • @luk2302 Thanks for your comment, but I'm passing the MainActivity Context as a parameter to the construnctor of the subclass – Sayantan Chowdhury Mar 18 '18 at 16:19
  • I know, I did not say "look at what you pass", I said "look at the variable" / field. Do you ever assign anything to it? You should really start using a proper IDE like IntelliJ which will tell you that your code will crash and hint to why. – luk2302 Mar 18 '18 at 16:20
  • @luk2302 Thank you so much for your help.. That issue is fixed. Though now I'm getting IllegalStateException as getDatabase was called recursively... I'll check it myself for now – Sayantan Chowdhury Mar 18 '18 at 16:35

0 Answers0