1

A.java : このクラスには、共有優先権が格納されます。以下のスニペットを使用しています。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(A.this);
Editor edit = prefs.edit();
edit.putString("Key1", key);
edit.putString("Key2", secret);
edit.commit();

BroadCastReceiver.java :電話を再起動したときに Key1、Key2 の値を取得したい。このために、以下のスニペットを使用しています。

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String a = prefs.getString("Key1", null);
    String b = prefs.getString("Key2", null);
}

クエリ:

この問題は文脈によるものかどうか

出力:

null値を取得しています。他のアクティビティでこの形式を試してみましたが、broadcastReceiver ではnull値が得られました。

私が正しい方法よりも間違った方法を選択している場合は?

4

2 に答える 2

1

2 つの異なる Context オブジェクトを使用しているようです。PreferenceManager.getDefaultSharedPreferences()呼び出しは、指定されたコンテキストのデフォルトの SharedPreferences を返します。

両方にアプリケーション Context を使用すると、問題が解決するはずです。getApplicationContext() を使用してアクティビティで取得し、context.getApplicationContext() を使用して BroadcastReceiver で取得します。

この記事では、コンテキストの違いの概要を説明しています。


更新: Triodeのコメントとして、Context.getSharedPreferences()を使用することをお勧めします。これは常に単一のインスタンスを返します。

于 2013-10-23T12:39:18.033 に答える
0
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences("Name of your preference",Context.MODE_PRIVATE);

共有設定のオブジェクトを取得するには、

例えば、

SharedPreferences sharedPreferences = context.getSharedPreferences(
           "Demo",
            Context.MODE_PRIVATE);
        edit.putString("Key1", key);
        edit.putString("Key2", secret);
        edit.commit();


SharedPreferences sharedPreferences = context.getSharedPreferences(
           "Demo",
            Context.MODE_PRIVATE);
    String a = prefs.getString("Key1", null);
    String b = prefs.getString("Key2", null);
于 2013-10-23T12:51:13.497 に答える