我在fragment1上有一个getSharedPreferences,它将从先前的片段加载int。

public void backButtonWasPressed() {
    settings = getActivity().getSharedPreferences("MyPref", 0);
    .....
}


我调用fragment1.backButtonWasPressed()并给我强制关闭,并在“ settings = getActivity()。getSharedPreferences(“ MyPref”,0);”上返回错误消息nullpointerexception

我的Logcat:

08-28 16:52:21.828: E/AndroidRuntime(4412): FATAL EXCEPTION: main
08-28 16:52:21.828: E/AndroidRuntime(4412): java.lang.NullPointerException
08-28 16:52:21.828: E/AndroidRuntime(4412):     at pkh.apps.Fragment1.backButtonWasPressed(Fragment1.java:324)
08-28 16:52:21.828: E/AndroidRuntime(4412):     at pkh.apps.KajianUtama.onBackPressed(KajianUtama.java:71)
08-28 16:52:21.828: E/AndroidRuntime(4412):     at android.app.Activity.onKeyUp(Activity.java:2131)


Fragment1上的第324行是:settings = getActivity()。getSharedPreferences(“ MyPref”,0);

我的主要SherlockFragmentActivity:

public class KajianUtama extends SherlockFragmentActivity implements OnItemClickListener {
....
@Override
public void onBackPressed() {
    super.onBackPressed();
    FragmentManager fm = getSupportFragmentManager();
    fragment1 = (Fragment1) fm.findFragmentById(R.id.content_frame);
    fragment1.backButtonWasPressed();
}
.....


}

我的片段1:

public class Fragment1 extends SherlockFragment{
....
   public void backButtonWasPressed() {
     settings = getActivity().getSharedPreferences("MyPref", 0);
     c = settings.getInt("numRun",0);
     Log.d("back pressed", "c " + c);
   }
...
}


请给我一个解决此问题的解决方案。谢谢。

最佳答案

检查首选项的名称是否与保存时使用的名称相同,最佳做法是保存一个常量PREFERENCE_NAME="myPreferenceName",然后使用该常量而不是字符串。

编辑

以这种方式尝试

@Override
public void onBackPressed() {
  super.onBackPressed();
  FragmentManager fm = getSupportFragmentManager();
  fragment1 = (Fragment1) fm.findFragmentById(R.id.content_frame);
  fragment1.backButtonWasPressed(this);
}


接着

public void backButtonWasPressed(Context context) {
   settings = context.getSharedPreferences("MyPref", 0);
   c = settings.getInt("numRun",0);
   Log.d("back pressed", "c " + c);
}


将上下文传递给方法

10-08 18:33