3

I am trying to save an integer that will store how many times a user has tapped on an ImageView using the SharedPreferences interface. However, when I run the app it gives me null pointer exception on the line where I am declaring the sharedPreferences like this:

SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);

This is my first time of using this interface and is is a little confusing to me. I do not have any idea why this is happening. this is the log:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{koemdzhiev.com.eggyegg/koemdzhiev.com.eggyegg.MainActivity}: 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:2236)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
 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:132)
        at android.app.Activity.getLocalClassName(Activity.java:4987)
        at android.app.Activity.getPreferences(Activity.java:5021)
        at koemdzhiev.com.eggyegg.MainActivity.<init>(MainActivity.java:20)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1606)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
        at   

This is my code in the class that extends from the Application class:

public class EggyEggApplication extends Application {

@Override
public void onCreate() {
    SharedPreferences mSharedPreferences = this.getSharedPreferences(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
    SharedPreferences.Editor mEditor = mSharedPreferences.edit();
    if(mSharedPreferences.contains(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY))== false) {
        mEditor.putInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY), 0).apply();
    }
}

This is my code in main activity:

public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private int defaultValue;
private int i;
ImageView tapImage;
SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();

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


    tapImage = (ImageView)findViewById(R.id.tapImage);
    tapImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            i++;
            mEditor.putInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY),i);
            mEditor.commit();
        }
    });
    defaultValue = getResources().getInteger(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY);
    i = mSharedPreferences.getInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY),defaultValue);



    int defaultValue = getResources().getInteger(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY);
    long lastTapNumber = mSharedPreferences.getInt(getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY),defaultValue);
    i = (int) lastTapNumber;

}
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

4 Answers 4

12

the problem is this line in your MainActivity:

SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);

the exceptions said, you get a nullpointer,

this nullpointer happens because the context is null, this happens because the line above is executed before the activity is finished with creation,

so move this line into you onCreate Method should solve the problem

Sign up to request clarification or add additional context in comments.

4 Comments

I moved this line and the declaration of the Editor inside the onCreate method, but now I have the following exception: Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f060014 type #0x3 is not valid at android.content.res.Resources.getInteger(Resources.java:1027) at koemdzhiev.com.eggyegg.MainActivity.onCreate(MainActivity.java:39)
if line 39 is this: getResources().getInteger(R.string.koe...... then you need change it to getString instead of getInteger, you mix typed here
Thanks. I tried that but I had to parse the string into an integer like that: defaultValue = Integer.parseInt(getResources().getString(R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY)); But after doing so the app crashes at run time with: Caused by: java.lang.NumberFormatException: Invalid int: "numberOfClicks" :/
yes for sure it will crash, you try to transform the String: ** numberOfClicks** into int, but this is not a number, so maybe you use the wrong String resource, better use a real integer resource, R.integer.NAME....
3

In the Activity, move

SharedPreferences mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreferences.edit();

inside onCreate. Yo need a Context to access the SharedPreferences. Internally getPreferences(Context.MODE_PRIVATE), call getPackageName.

Edit

You should avoid to use localized strings as key for your SharedPreferences

1 Comment

you can't use R.string.koemdzhiev_eggyegg_PREFERENCE_FILE_KEY with getResource().getInteger(). R.string is for getResources().getString()
1

Well you said you save integer so they key word you are lookig for is

       "java.lang.String android.content.Context.getPackageName()"

Edit: My bad! There is probably something wrong in on create method

1 Comment

I still don't know where I should apply this change
0

Try -

public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private int defaultValue;
private int i;
ImageView tapImage;
SharedPreferences mSharedPreferences;

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

    mSharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
    this.editor = mSharedPreferences.edit();
    this.editor.commit();


    tapImage = (ImageView)findViewById(R.id.tapImage);
    tapImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            i++;
                setValueToSharedPref("TAP_NUMBER",i);
        }
    });


long lastTapNumber = mSharedPreferences.getInt("TAP_NUMBER",0);
i = (int) lastTapNumber;

}


    public void setValueToSharedPref(String key, boolean value) {
        this.editor.putBoolean(key, value);
        this.editor.commit();

    }


private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.