0

I'm creating an android app using android studio and have recently tried to implement shared Preferences as I need to access data from one activity in another without starting it.(It is a database helper activity). However, when I try to debug the app, this shows up:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rcadit.foodgenie/com.example.rcadit.foodgenie.resultActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

Activity 2 (part where I want to access the data)

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String courseData = prefs.getString("courseData", "no id"); //no id: default value
    String prepData = prefs.getString("prepData", "no id");
    String hungerData = prefs.getString("hungerData", "no id");
    String cuisineData = prefs.getString("cuisineData", "no id");

Activity 1 (part where I am assigning the data)

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Spinner spinner = (Spinner) parent;
        // On selecting a spinner item
        String value = parent.getItemAtPosition(position).toString();
        if (value.equals("Low") ) {
            hungerValue = "1";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("hungerData", hungerValue); //InputString: from the EditText
            editor.commit();
        }
        if (value.equals("Medium") ) {
            hungerValue = "2";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("hungerData", hungerValue); //InputString: from the EditText
            editor.commit();
        }
        if (value.equals("High") ) {
            hungerValue = "3";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("hungerData", hungerValue); //InputString: from the EditText
            editor.commit();
        }
        if (value.equals("Under 10 mins") ) {
            prepValue = "< 10";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("prepData", prepValue); //InputString: from the EditText
            editor.commit();
        }
        if (value.equals("No Preparation") ) {
            prepValue = " = 0";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("prepData", prepValue); //InputString: from the EditText
            editor.commit();
        }
        if (value.equals("Under 20 mins") ) {
            prepValue = "< 20";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("prepData", prepValue); //InputString: from the EditText
            editor.commit();
        }
        if (value.equals("Under 30 mins") ) {
            prepValue = "< 30";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("prepData", prepValue); //InputString: from the EditText
            editor.commit();
        }
        if (value.equals("Over 30 mins") ) {
            prepValue = "> 30";
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("prepData", prepValue); //InputString: from the EditText
            editor.commit();
        }
        if(spinner.getId() == R.id.cuisine_spinner)
        {
            cuisineValue = value;
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("cuisineData", cuisineValue); //InputString: from the EditText
            editor.commit();
        }

        if(spinner.getId() == R.id.course_spinner)
        {
            courseValue = value;
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("courseData", courseValue); //InputString: from the EditText
            editor.commit();
        }

        Log.d(TAG, "onItemSelected: " + value + " " + courseValue+ " "+ cuisineValue + " "+ prepValue + " "+ hungerValue);

    }

Full LogCat

08/02 17:00:08: Launching app
Cold swapped changes.
$ adb shell am start -n "com.example.rcadit.foodgenie/com.example.rcadit.foodgenie.SplashScreen" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to com.example.rcadit.foodgenie
Connected to the target VM, address: 'localhost:8610', transport: 'socket'
I/art: Not late-enabling -Xcheck:jni (already on)
W/ActivityThread: Application com.example.rcadit.foodgenie is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1387)
W/System: ClassLoader referenced unknown path: /data/app/com.example.rcadit.foodgenie-1/lib/x86
W/System: ClassLoader referenced unknown path: /data/app/com.example.rcadit.foodgenie-1/lib/x86
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

                  [ 08-02 09:00:13.226  3744: 3744 D/         ]
                  HostConnection::get() New Host Connection established 0xaa9a5480, tid 3744


                  [ 08-02 09:00:13.300  3744: 3765 D/         ]
                  HostConnection::get() New Host Connection established 0xaa9a6020, tid 3765
I/OpenGLRenderer: Initialized EGL, version 1.4
D/android.widget.GridLayout: horizontal constraints: x2-x0>=792, x2-x1<=308, x1-x0<=325 are inconsistent; permanently removing: x2-x1<=308. 
D/MyActivity: onItemSelected: Please Select null null null null
D/MyActivity: onItemSelected: Please Select null Please Select null null
D/MyActivity: onItemSelected: Please Select null Please Select null null
D/MyActivity: onItemSelected: Please Select Please Select Please Select null null
I/Choreographer: Skipped 30 frames!  The application may be doing too much work on its main thread.
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa9b7e30
D/MyActivity: onItemSelected: Low Please Select Please Select null 1
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4016e50
D/OpenGLRenderer: endAllStagingAnimators on 0xa282d300 (ListPopupWindow$DropDownListView) with handle 0xa262fad0
D/MyActivity: onItemSelected: American Please Select American null 1
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4016e50
D/OpenGLRenderer: endAllStagingAnimators on 0xa2830080 (ListPopupWindow$DropDownListView) with handle 0xa261f040
D/MyActivity: onItemSelected: Under 30 mins Please Select American < 30 1
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4016e50
D/OpenGLRenderer: endAllStagingAnimators on 0xa269aa00 (ListPopupWindow$DropDownListView) with handle 0xa261f4b0
D/MyActivity: onItemSelected: Drinks Drinks American < 30 1
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa9b7e30
W/art: Verification of void com.example.rcadit.foodgenie.resultActivity.onCreate(android.os.Bundle) took 436.369ms
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.rcadit.foodgenie, PID: 3744
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rcadit.foodgenie/com.example.rcadit.foodgenie.resultActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                      at android.app.ActivityThread.-wrap11(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:148)
                      at android.app.ActivityThread.main(ActivityThread.java:5417)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
                      at android.content.ContextWrapper.getPackageName(ContextWrapper.java:133)
                      at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:375)
                      at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:370)
                      at com.example.rcadit.foodgenie.DatabaseAccess.<init>(DatabaseAccess.java:21)
                      at com.example.rcadit.foodgenie.DatabaseAccess.getInstance(DatabaseAccess.java:49)
                      at com.example.rcadit.foodgenie.resultActivity.onCreate(resultActivity.java:19)
                      at android.app.Activity.performCreate(Activity.java:6237)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                      at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:148) 
                      at android.app.ActivityThread.main(ActivityThread.java:5417) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Disconnected from the target VM, address: 'localhost:8610', transport: 'socket'

I have no idea where my mistake is and am new to android programming. :(

samgak
  • 23,944
  • 4
  • 60
  • 82
Adit R
  • 45
  • 6
  • What is there at `resultActivity.java:19` – Ravi Aug 02 '16 at 09:27
  • possible duplicate of [Getting java.lang.nullPointerException using SharedPreferences](http://stackoverflow.com/questions/3099955/getting-java-lang-nullpointerexception-using-sharedpreferences?rq=1) – V-rund Puro-hit Aug 02 '16 at 09:31
  • where is this when logcat prints Please Select null null null? is this the value 'String value'? if yes, parent.getItemAtPosition(position).toString(); will crash. Also try do not do this.... value.equals("Low"), if your value is null, this line also will crash. Do the other way, "Low".equals(value) will at least prevent it to crash. – kggoh Aug 02 '16 at 09:32
  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Yazan Aug 02 '16 at 12:07
  • Google is your friend. – Sufian Aug 02 '16 at 15:53
  • thanks for the suggestion @kggoh – Adit R Aug 04 '16 at 06:39

0 Answers0