I Simply want to store String name ="Android"
using SharedPreferences from one of the Activity of my Application and latter I want to retrieve this String in BroadcastReceiver Class of same Application.
I tried everything. please help me.
I Simply want to store String name ="Android"
using SharedPreferences from one of the Activity of my Application and latter I want to retrieve this String in BroadcastReceiver Class of same Application.
I tried everything. please help me.
Follow the below code. Make one class called PreferenceData . In that class there are two methods . One is for store the string into shared preference and another is for get the string for shared preference.
public class PreferenceData
{
static final String PREF_STORE = "store_temp";
public static SharedPreferences getSharedPreferences(Context ctx)
{
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setTempString(Context ctx, String str)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_STORE, str);
editor.commit();
}
public static String getTempString(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_STORE, "");
}
}
How to Access it ?
PreferenceData.getTempString(Pass Context); // Get Shared Preference String
PreferenceData.setTempString(Pass Context,"Android") // Set String to Shared Preference
SharedPreferencesで値を設定するには...
private final String PREF = "PREF";
private final String PREF_STRING = "PREF_STRING";
final SharedPreferences preferences = activity.getSharedPreferences(PREF, Activity.MODE_PRIVATE);
preferences.edit().putString(PREF_STRING, "Android").commit();
SharedPreferencesから値を取得するため。
preferences.getString(PREF_STRING, "Default value");
コードの後半で文字列を変更する必要がない場合は、文字列をハードコードされた「Strigs」静的変数に入れて、それを読み取るだけにすることができます。文字列を宣言して読み取る方がはるかに簡単です。文字列「Android」を読んで変更する必要がある場合は、次の例を使用してください:http ://saigeethamn.blogspot.ch/2009/10/shared-preferences-android-developer.html
It would be easier to figure out if you could post the code you tired.
By the way,
public abstract void onReceive (Context context, Intent intent)
this method will give you context instance. you can use that to get preferences.
context.getPreferences(MODE_PRIVATE);
hope this helps.
try this code
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("android", "your string"); // value to store
editor.commit();
now in your Reciever class add the following
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
String android= mPrefs.getString("android", null);