Thursday, March 22, 2012

SharedPreferences Between two Activity

Create One class with name AppPreferences

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class AppPreferences {
 private static final String APP_SHARED_PREFS = "com.chirag.saga.password"; 
 private SharedPreferences appSharedPrefs;
 private Editor prefsEditor;

 public AppPreferences(Context context) {
  this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS,
    Activity.MODE_PRIVATE);
  this.prefsEditor = appSharedPrefs.edit();
 }

 public String getPassword() {
  return appSharedPrefs.getString("password", "0000");
 }

 public void savePassword(String text) {
  prefsEditor.putString("password", text);
  prefsEditor.commit();
 }
}

Then in your Activity...

protected AppPreferences appPrefs;
appPrefs = new AppPreferences(getApplicationContext());

and
String someString = appPrefs.getPassword();
or
appPrefs.savePassword(someString);

No comments: