【问题标题】:Android where to declare SharedPreferencesAndroid 在哪里声明 SharedPreferences
【发布时间】:2014-01-25 01:15:23
【问题描述】:

我试图在我的第二个活动中使用 edittexts 来更改我的第一个/主要活动的字符串。因此,要做到这一点,必须使用 SharedPreferences。

在我的第二个活动的顶部,我宣布了他们和一个编辑。它会导致 nullpointexception 错误并使代码崩溃。我不确定在哪里初始化它,因为我希望在主要/第一个活动中查看 sharedPreferences。

SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();

另外,将这段代码放入 sharedprefs 字典中是否合适?

if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
{
  editor.putString("intro", introstring);
}

【问题讨论】:

  • 你能发布第一个和第二个活动代码吗?在活动的 oncreate 方法中声明的共享首选项

标签: android sharedpreferences


【解决方案1】:

在我的第二个活动的顶部

您的意思是字段 - 是的,这将导致 NPE,原因在 Why getApplicationContext() in constructor of Activity throws null pointer exception? 中解释

所以你需要在 cmets 中建议

class YourSecondActivity extends Activity {

    SharedPreferences sp;
    Editor e;

    protected void onCreate() {
        sp = PreferenceManager.getDefaultSharedPreferences(this); // forget about
        // named preferences - get the default ones and finish with it
        e = sp.edit();
    }

    meth() {
        //...
        if(!introstring.isEmpty()) { // save the fields if NOT empty
            e.putString("intro", introstring);
            e.commit(); // you forgot to commit
        }
    }
}

【讨论】:

    【解决方案2】:

    我处理 SharedPrefrences 的方式是创建一个类,该类将扩展 Application 类并将 SharedPrefrences 放在那里,以便在应用程序的任何地方都可以访问。

    class MyApp extends Application{
          SharedPreferences sharedPreferences;
    
          public void onCreate() {
               sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
          }
    
          public static getSharedPrefrences(){
               return sharedPrefrences;
          }
    }
    

    您必须在活动标签中声明应用程序的名称标签

    <application
        android:allowBackup="true"
        android:name=".fundamentals.UploadApp"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        ....
        ....
    </application>
    

    然后,您可以从任何您想要的活动中访问它。

    class SomeActivity extends Activity{
          onCreate(){
              SharedPrefences prefs = MyApp.getSharedPrefrences();
          }
    }
    

    另外,您需要在将内容放入 SharedPrefrences 后提交更改

    if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
    {
      editor.putString("intro", introstring).commit();
    }
    

    【讨论】:

    • 这是我觉得更好的解决方案。我试图让我的应用程序范围的首选项在应用程序类中可用,关键是从 onCreate() 生命周期回调方法中实例化它。如果您从一个活动中执行此操作,那么您将需要从每个活动中实例化它。最好是一次创建并多次使用,而不是每次需要时都重新创建。