2016-08-11 8 views
0

jsonobjectの文字列値を共有設定に渡してコミットしています。しかし、これをフェッチしている間、デフォルト値を返します。JSONObject文字列がsharedpreferencesに格納されていません

public void new_putMultipleProfileData(String got_multiple_json_data){ 

    Editor editor=app_prefs.edit(); 
    editor.putString(NEW_TESTING_PIC_ID, got_multiple_json_data); 
    editor.commit(); 
} 

取得の場合:置くため

public String new_getMultipleProfileData(){ 
    return app_prefs.getString(NEW_TESTING_PIC_ID,"0"); 
} 

完全な好みのヘルパークラス:あなたは全体の同じ優先マネージャを使用したい場合は

public class PreferenceHelper { 


private final String PREF_NAME = "Testing_xyz"; 
private SharedPreferences app_prefs; 

//For Testing 
public static final String NEW_TESTING_PIC_ID = "testing"; 

private Context context; 

public PreferenceHelper(Context context) { 
    app_prefs = context.getSharedPreferences(PREF_NAME, 
      Context.MODE_PRIVATE); 
    this.context = context; 
} 


public void new_putMultipleProfileData(String got_multiple_json_data){ 
    AppLog.Log("new_data_80503","got_multiple_json_data "+got_multiple_json_data); 
    Editor editor=app_prefs.edit(); 
    editor.putString(NEW_TESTING_PIC_ID, "hello"); 
    editor.commit(); 
} 

public String new_getMultipleProfileData(){ 
    AppLog.Log("new_data_80503","new_getMultipleProfileData "+app_prefs.getString(NEW_TESTING_PIC_ID,"0")); 
    return app_prefs.getString(NEW_TESTING_PIC_ID,"0"); 
} 

}

+0

ApplicationContextを使用できますか? – Pr38y

+0

@ Pr38y private SharedPreferences app_prefs; –

+0

@ Pr38y public PreferenceHelperClass(コンテキストコンテキスト){ app_prefs = context.getSharedPreferences(PREF_NAME、 Context.MODE_PRIVATE); this.context = context; } –

答えて

0

a ppを入力し、defaultSharedPreferenceを使用します。 getSharedPreferencesそのコンテキストのみの戻り設定ファイルは、異なるコンテキストでは異なります。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

または

あなたの代わりにどのようにapp_prefsを初期化しているcontext

+0

しかし、異なるデータをプリファレンスに入れても、getDefaultSharedPreferencesを使ってうまく動作しています。両者の違いは何ですか? –

+0

getSharedPreferencesは、そのコンテキストのみのプリファレンスファイルを返します。コンテキストごとに異なります。 getDefaultSharedPreferencesは、コンテキストに関係なく、アプリケーション全体で1つのファイルを返します。現在のコードでは、アクティビティA用とアクティビティB用の2つのPREF_NAME xmlファイルを作成しています。アクティビティAのファイルにデータを保存しています。アクティビティBのファイルからアクセスする – Pr38y

関連する問題