We want to create properties that are shared between the two activities using the Shared Preferences class on Android. How can I transfer these attributes from one activity to another? Static variables may be possible, but I don't think it's the right way for me.
android
You must use the int to hand over to another activity, or read the required properties from the new activity.
Create a helper class that can handle calls to shared properties, and create an instance of that class in the activity to save or read the properties.
public class AppPreferences {
public static final String KEY_PREFS_SMS_BODY = "sms_body";
private static final String APP_SHARED_PREFS = AppPreferences.class.getSimpleName(); // Name of the file -.xml
private SharedPreferences _sharedPrefs;
private Editor _prefsEditor;
public AppPreferences(Context context) {
this._sharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this._prefsEditor = _sharedPrefs.edit();
}
public String getSmsBody() {
return _sharedPrefs.getString(KEY_PREFS_SMS_BODY, "");
}
public void saveSmsBody(String text) {
_prefsEditor.putString(KEY_PREFS_SMS_BODY, text);
_prefsEditor.commit();
}
}
Next, please fill out the activities as below...
public class MyActivity extends Activity {
private AppPreferences _appPrefs;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_appPrefs = new AppPreferences(getApplicationContext());
// ...
}
}
You can read or save the value using the method below.
String someString = _appPrefs.getSmsBody();
_appPrefs.saveSmsBody(someString);
© 2024 OneMinuteCode. All rights reserved.