2017-05-01 60 views
-6

我已在活動共享偏好:如何解決SharedPreference中的NullPointerException?

SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE); 
      SharedPreferences.Editor editor = sp.edit(); 
      editor.putInt("your_int_key", 14); 
      editor.commit(); 

,並在片段

GET喜好
if (getActivity().getSharedPreferences("your_prefs", Activity.MODE_PRIVATE) != null) { 
       SharedPreferences sp = getActivity().getSharedPreferences("your_prefs", Activity.MODE_PRIVATE); 
       myIntValue = sp.getInt("your_int_key", -1); 
      } 
      textTv[i] = (TextView) v.findViewById(nizTekstaID[i]); 
      textTv[i].setVisibility(View.VISIBLE); 
      textTv[i].setText(result.get(i)); 
      textTv[i].setTextSize(myIntValue); 

,但我得到的NullPointerException,這裏是logcat的:

05-01 04:46:01.298 10968-10968/com.example.bolt.automagazin E/AndroidRuntime: FATAL EXCEPTION: main 
                      Process: com.example.bolt.automagazin, PID: 10968 
                      java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.support.v4.app.FragmentActivity.getSharedPreferences(java.lang.String, int)' on a null object reference 
                       at com.example.bolt.automagazin.FragmentGdeSeUcitavajuVestiScroll1$asyncTekstovi.onPostExecute(FragmentGdeSeUcitavajuVestiScroll1.java:988) 
                       at com.example.bolt.automagazin.FragmentGdeSeUcitavajuVestiScroll1$asyncTekstovi.onPostExecute(FragmentGdeSeUcitavajuVestiScroll1.java:829) 
                       at android.os.AsyncTask.finish(AsyncTask.java:651) 
                       at android.os.AsyncTask.-wrap1(AsyncTask.java) 
                       at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) 
                       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) 
在這一行

if (getActivity().getSharedPreferences("your_prefs", Activity.MODE_PRIVATE) 
!= null) { 
+0

那麼哪一條是FragmentGdeSeUcitavajuVestiScroll1.java的第988行? –

+1

活動爲空。不是SharedPreferences –

+0

你可以(也應該)在Asynctask之外獲得你的偏好 –

回答

0

最可能的原因是因爲片段尚未附加到活動。您需要在片段的onActivityCreated()方法中調用getActivity()

void onActivityCreated (Bundle savedInstanceState){ //call getActivity() here } 
相關問題