0

I am using PreferenceManager in one of my fragment using codes like this.

String userId = PreferenceManager.getDefaultSharedPreferences(getContext()).getString("userId", "");

Its causing some time error called above. I have searched many questions in stackflow but not able to fix it. My complete error log is like below

FATAL EXCEPTION: main
Process: com.example.shayari, PID: 29366
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.support.v7.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:308)
at android.support.v7.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:303)
at com.example.shayari.material.QuotesListFragment.updateQuotesListServer(QuotesListFragment.java:252)
at com.example.shayari.material.QuotesListFragment.access$900(QuotesListFragment.java:45)
at com.example.shayari.material.QuotesListFragment$4.onResponse(QuotesListFragment.java:202)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6290)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Anyone have faced similar issue and if found any solution, let me know. Thanks a lot

1 Answer 1

1

getContext() is returning null. It will do that when the fragment is no longer attached to the activity.

You seem to be making a Retrofit call from a fragment and are attempting to update SharedPreferences as part of processing the response. However, apparently, you are not checking to see if the fragment is still attached to the activity. There are many reasons why the fragment may have been detached, including navigation (e.g., user presses BACK to exit the activity before the network I/O is complete) or configuration changes (e.g., the user rotates the screen, causing Android to swap to a new activity and new fragment, but Retrofit still wants to talk to the old fragment).

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

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.