I am getting the default text and not the actual text saved when trying to access a shared preference. I have tested that it returns true when saving so I am pretty sure the problem is in reading from the preference file.
The preference class
public class SaveWarningMessage : Activity
{
private ISharedPreferences myPref;
private ISharedPreferencesEditor myPrefEditor;
private Context myContext;
public void MyAppPref(Context context)
{
this.myContext = context;
myPref = PreferenceManager.GetDefaultSharedPreferences(myContext);
myPrefEditor = myPref.Edit();
}
public void SaveString(string text)
{
myPrefEditor.PutString("warning text", text);
var returnValue = myPrefEditor.Commit();
}
public string GetString()
{
return myPref.GetString("warning text", "could not get pref");
}
}
}
The class saving the preference:
string warningText = Intent.GetStringExtra("warningText");
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
classInstans.SaveString(warningText);
The class reading from the preference:
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
string message = classInstans.GetString();
Personally I would not subclass it from Activity(?) and use the .actor to instance your ISharedPreferences, along with a few other changes you end up with this example.
Example:
public class SaveWarningMessage
{
public const string WARNINGTEXT = "warning text";
ISharedPreferences myPref;
public SaveWarningMessage(Context context)
{
myPref = PreferenceManager.GetDefaultSharedPreferences(context);
}
public void SaveString(string text)
{
var myPrefEditor = myPref.Edit();
myPrefEditor.PutString(WARNINGTEXT, text);
if (!myPrefEditor.Commit())
{
Log.Error("SomeTag", $"Saving {text} to Pref:{WARNINGTEXT} failed");
}
// Or replace the Commit & check of return the following
// if you do not care about checking the return value
// myPrefEditor.Apply();
}
public string GetString()
{
return myPref.GetString(WARNINGTEXT, "could not get pref");
}
}
Then you can you it like this:
string warningText = "SomeStringToSave";
SaveWarningMessage classInstans = new SaveWarningMessage(Application.Context);
classInstans.SaveString(warningText);
SaveWarningMessage classInstans2 = new SaveWarningMessage(Application.Context);
string message = classInstans2.GetString();
Log.Debug("SO", message);
Related
I'm trying to save a string to shared preferences and then start an activity and retrieve it but doesn't work. What am I doing wrong?
First I set the shared preference key then I start the activity:
SharedPreferences.Editor editor =
getSharedPreferences("PaymentStatus",MODE_PRIVATE).edit();
editor.putString("payment_status","success");
editor.apply();
Intent i = new Intent(getBaseContext(), ProfileActivity.class);
startActivity(i);
and on the ProfileActivity class I trying to retrieve the key:
SharedPreferences prefs = getSharedPreferences("PaymentStatus",
MODE_PRIVATE);
String payment_status = prefs.getString("payment_status", null);
if(payment_status == "success"){
Log.i("payment status", "success");
}
I can't see the payment status success in the logcat.
The issue with the code you have given is not with how you done it with shared preferences (you did that correctly btw)
Your issue is that you are comparing strings via == as this compares the string reference and not the string value. Use .equals() or .contains() instead.
if (payment_status.equals("success")) {
Log.i("payment status", "success");
}
This is my experience in used SharedPreferens.
Perhaps this approach will solve the problem:
public class UserData {
UserData(MainActivity mainActivity){this.mainActivity = mainActivity;}
private static UserData userData;
private final MainActivity mainActivity;
private SharedPreferences sPref;
private SharedPreferences.Editor editor;
final private String USER_ID = "user_id";
public static void create(MainActivity activity) {
if (userData == null) userData = new UserData(activity);
}
public static UserData getUserData() {
return userData;
}
void createUser() {
sPref = mainActivity.getSharedPreferences("UserData", Context.MODE_PRIVATE);
editor = sPref.edit();
// Если user id уже есть, выходим из метода
if(sPref.contains(USER_ID)) return;
editor.putString(USER_ID, createUserId());
editor.apply();
Toast.makeText(mainActivity,"UserId created", Toast.LENGTH_SHORT).show();
}
// id формируется на основе текущей даты и времени
private String createUserId() {
Date currentDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmmss", Locale.getDefault());
return dateFormat.format(currentDate);
}
public String getUserId() {
return sPref.getString(USER_ID, "");
}
}
I am trying to use SharedPreferences to register account for my apps but it is always return different value from what I have saved at saveSipAccount in the first time when i try to get SharedPreferences at getSipAccount . It is only working when i restart my apps.
I am newbie for android and SIP so please help me, thank you so much!
This is my code
private static String PREFERENCE_NAME = "voip_demo_pref";
private static String SIP_DOMAIN_KEY = "sip_domain";
private static String SIP_PROXY_KEY = "proxy";
private static String SIP_USER_KEY = "user";
private static String SIP_PASSWORD_KEY = "password";
public void saveSipAccount(Context context, String domain, String proxy, String user, String password) {
SipAccount account = new SipAccount(domain, proxy, user, password);
saveSipAccount(context, account);
}
public void saveSipAccount(Context context, SipAccount account) {
SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor e = pref.edit();
e.putString(SIP_DOMAIN_KEY, account.getDomain());
e.putString(SIP_PROXY_KEY, account.getProxy());
e.putString(SIP_USER_KEY, account.getUser());
e.putString(SIP_PASSWORD_KEY, encryptString(account.getPassword()));
e.apply();
}
public SipAccount getSipAccount(Context context) {
SipAccount account = new SipAccount();
SharedPreferences pref = context.getSharedPreferences(PREFERENCE_NAME, context.MODE_PRIVATE);
account.setDomain(pref.getString(SIP_DOMAIN_KEY, ""));
account.setProxy(pref.getString(SIP_PROXY_KEY, ""));
account.setUser(pref.getString(SIP_USER_KEY, ""));
String password = pref.getString(SIP_PASSWORD_KEY, "");
if (!TextUtils.isEmpty(password)) {
password = decryptString(password);
}
account.setPassword(password);
return account;
}
and this is the code when I call saveSipAccount
String domain = String.valueOf(sipDomainView.getText());
String proxy = String.valueOf(sipProxyView.getText());
String user = String.valueOf(sipUserView.getText());
String password = String.valueOf(sipPasswordView.getText());
sipManager.saveSipAccount(MyApplication.getInstance().getApplicationContext(), domain, proxy, user, password);
Log.d(TAG, "saved");
try {
service.changeAccount();
}
and this is getSipAccount
public boolean changeAccount() {
sipManager = SipManager.newInstance();
SipAccount profile = sipManager.getSipAccount(MyApplication.getInstance().getApplicationContext());
AccountConfig config = sipManager.getAccountConfig(app, profile.getDomain(), profile.getProxy()
, profile.getUser(), profile.getPassword());
try {
MyApp.ep.libRegisterThread(Thread.currentThread().getName());
} catch (Exception e) {
Log.e(TAG, "libRegisterThread error.", e);
}
changeAccountStatus("processing");
try {
account.modify(config);
} catch (Exception e) {
Log.e(TAG, "MyAccount.modify error.", e);
changeAccountStatus("Fail registration");
return false;
}
return true;
}
You can try this
e.commit()
and creat a String variable like this:
String str1 = pref.getString(SIP_DOMAIN_KEY, null)
and log str1 to check. Hope this help you
Try creating a special class for sharedPreferences. For example:
public class MySharedPreferences {
public static final String MyPREFERENCES = "MyPrefs";
public static final String KEY1 = "key1";
public static final String KEY2 = "key2";
// other keys
private static MySharedPreferences mInstance;
private static Context mCtx;
private MySharedPreferences(Context context) {
mCtx = context;
}
public static synchronized MySharedPreferences getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySharedPreferences(context);
}
return mInstance;
}
//this method will save the sip account
public boolean saveSipAccount(String domain, String proxy, String user, String password) {
SipAccount account = new SipAccount(domain, proxy, user, password);
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(YOUR_KEY, account.getDomain());
//other putString
return editor.commit();
}
public SipAccount getSipAccount() {
SipAccount account = new SipAccount();
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String domain = sharedPreferences.getString(YOUR_KEY, ""));
account.setDomain(domain));
//other code
if (!TextUtils.isEmpty(password)) {
password = decryptString(password);
}
account.setPassword(password);
return account;
}
For obtain a SipAccount
SipAccount acount = MySharedPreferences.getInstance(context).getSipAccount();
Delete and reinstall your app.
My apps worked when I used Tray instead of SharedPreference!
Thank you guy so much for your answer ad your kindness :) !
I have an app that shows notification in a listview. I want these notifications to be saved so that if I open the app and see notification I can see these notifications again when I close the app and then open it. I tried this
but nothing was saved.
Another major question is how can I run this app in background? So if notification is received the app lists that notification in the listview without being opened?
My Code
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
if (pack.contains("fake")){
try {
// remotePackageContext = getApplicationContext().createPackageContext(pack, 0);
// Drawable icon = remotePackageContext.getResources().getDrawable(id);
// if(icon !=null) {
// ((ImageView) findViewById(R.id.imageView)).setBackground(icon);
// }
byte[] byteArray = intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if (byteArray != null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
if(text.contains("") && !text.contains(" messages")) {
model.setName(title + ": " + text);
model.setImage(bmp);
if (modelList != null) {
modelList.add(model);
adapter.notifyDataSetChanged();
} else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
Make a class Cache which has the capabilities to serialize and deserialize data.
public class Cache {
private static Cache CACHE;
public static Cache get() {
if (!SharedPreferencesHelper.isCacheAvailable()) {
CACHE = new Cache();
SharedPreferencesHelper.saveCache(CACHE);
} else {
CACHE = SharedPreferencesHelper.getCache();
}
return CACHE;
}
ArrayList<Taxonomy> cachedTaxonomies;
public Cache() {
cachedTaxonomies = new ArrayList<Taxonomy>();
}
public ArrayList<Taxonomy> getCachedTaxonomies() {
return cachedTaxonomies;
}
public static String serialize(Cache cache) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
return gson.toJson(cache);
}
public static Cache deserialize(String json) {
Type type = new TypeToken<Cache>() {
}.getType();
return new Gson().fromJson(json, type);
}
public void update() {
SharedPreferencesHelper.saveCache(this);
}
}
Here Taxonomy is a model.
Below is the class which helps you save in SharedPrefs
public class SharedPreferencesHelper {
private static final String PREFS_CACHE = "prefs_cache";
public static SharedPreferences getSharedPreferences() {
return SpreeApplication.getSharedPreferences();
}
// Cache -------------------------------------
public static boolean isCacheAvailable() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return false;
} else {
return true;
}
}
public static Cache getCache() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return null;
} else {
return Cache.deserialize(json);
}
}
public static void saveCache(Cache cache) {
saveString(PREFS_CACHE, Cache.serialize(cache));
}
// -----------------------------------------------------
private static void saveString(String prefKey, String value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putString(prefKey, value);
prefEditor.commit();
}
private static void saveBoolean(String prefKey, boolean value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putBoolean(prefKey, value);
prefEditor.commit();
}
}
To save write this :
List<Taxonomy> taxonomies = new ArrayList<Taxonomy>();
Cache cache = Cache.get();
cache.getCachedTaxonomies().clear();
cache.getCachedTaxonomies().addAll(taxonomies);
SharedPreferencesHelper.saveCache(cache);
this is my spreeapplication class which is a custom application class
Remember you have to mention in manifest if you create a custom application class
public class SpreeApplication extends Application{
private final static String DEFAULT_PREFERENCES = "spree";
private static SharedPreferences sharedPreferences;
private static Context applicationContext;
#Override
public void onCreate() {
super.onCreate();
applicationContext = this;
sharedPreferences = getSharedPreferences(DEFAULT_PREFERENCES, Context.MODE_PRIVATE);
}
public static SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
public static SharedPreferences.Editor getSharedPreferencesEditor() {
return sharedPreferences.edit();
}
public static Context getContext() {
return applicationContext;
}
}
I am new to android. I am using a SessionHandler class where i save the username from LoginActivity in shared preferences. I want to access this username from shared preferences in a class of broadcast receiver
Here is the code for SessionHandler class.
public SharedPreferences getLoginPreferences() {
// This sample app persists the registration ID in shared preferences,
// but
// how you store the regID in your app is up to you.
return context.getSharedPreferences(
LoginActivity.class.getSimpleName(), Context.MODE_PRIVATE);
}
public void storeLoginSession(String str_Name) {
final SharedPreferences prefs = getLoginPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("name", str_Name);
editor.commit();
}
I want to access this name name here in startService().
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
startService();
}
}
private void startService() {
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
strDate = sdf.format(c.getTime());
}
How can I get this value? I tried using context but not working. Can anyone please help me.
Best way to use SharedPreference is to wrap inside your custom Preference class like :
public class YourPreference {
private static YourPreference yourPreference;
private SharedPreferences sharedPreferences;
public static YourPreference getInstance(Context context) {
if (yourPreference == null) {
yourPreference = new YourPreference(context);
}
return yourPreference;
}
private YourPreference(Context context) {
sharedPreferences = context.getSharedPreferences("YourCustomNamedPreference",Context.MODE_PRIVATE);
}
public void storeLoginSession(String str_Name) {
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
editor.putString("name", str_Name);
prefsEditor.commit();
}
}
Then you can get YourPrefrence instance from any class where contet is available using
YourPreference yourPrefrence = YourPreference.getInstance(context);
yourPreference.storeLoginSession(YOUR_STRING);
You can create global functions for sharedPreferences:
public static void setSharedPrefString(Context context, String key, String value) {
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preference.edit();
editor.putString(key, value);
editor.commit();
}
public static String getSharedPrefString(Context context, String key) {
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(context);
if (preference != null) {
return preference.getString(key, "");
}
return "";
}
call "getSharedPrefString" from onReceive of BroadcastReceiver.
Let me know if you find it useful.
Create a class called AppPreference.class
public class AppPreference {
private SharedPreferences mSharedPreferences;
public static final String KEY_LOGIN= "KEY_LOGIN";
public AppPreference(Context context) {
super();
mSharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE);
}
public void setLoginStatus(String value) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(KEY_POSTCODE_LOGIN, value);
editor.commit();
}
public String getLoginStatus() {
return mSharedPreferences.getString(KEY_POSTCODE_LOGIN,"");
}
}
You can save in value by calling
AppPreference appPreference = new AppPreference(context);
appPreference .setLoginStatus("value you want to save");
getvalue call
AppPreference appPreference = new AppPreference(context);
appPreference .getLoginStatus();
Hi please use this sample code
public class PreferenceHandler
{
public static boolean storeNameToPrefernce(Context context,
String key, String getDetailsString) {
// TODO Auto-generated method stub
SharedPreferences mySharedPreferences;
try{
mySharedPreferences=context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
SharedPreferences.Editor editor=mySharedPreferences.edit();
editor.putString(key,getDetailsString);
editor.commit();
}
catch(Exception e){
System.out.println(e);
return false;
}
return true;
}
public static String getNameFromPreference(Context context,String key)
{
String value;
SharedPreferences mySharedPreferences;
try{
mySharedPreferences = context.getSharedPreferences(MyConstants.PREFERENCE_NAME,0);
value = mySharedPreferences.getString(key, "NONE");
}catch(Exception e){
return "NONE";
}
return value;
}
}
Getting string from Preference class:
In SampleActvity class.
String name =PreferenceHandler.getNameFromPreference(sampleActivity.this,key);
I do it in this simply way:
main class:
public class SWP extends Activity implements LocationListener
{ ....
public static final String MY_PREFERENCES = "SWP_Preferences";
public static SharedPreferences preferencesSwp;
public static SharedPreferences.Editor preferencesEditorSwp;
...
#Override
protected void onCreate(Bundle savedInstanceState)
{ ....
preferencesSwp = getSharedPreferences(MY_PREFERENCES, Activity.MODE_PRIVATE);
preferencesEditorSwp = preferencesSwp.edit();
....
}
....
}
in any other, read
value1 = SWP.preferencesSwp.getString("PREF_value1", "init_text");
and write
SWP.preferencesEditorSwp.putString("PREF_value1", value1 );
SWP.preferencesEditorSwp.commit();
I would like to store class object in android sharedpreference. I did some basic search on that and I got some answers like make it serializable object and store it but my need is so simple. I would like to store some user info like name, address, age and boolean value is active. I made one user class for that.
public class User {
private String name;
private String address;
private int age;
private boolean isActive;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
}
Thanks.
Download gson-1.7.1.jar from this link: GsonLibJar
Add this library to your android project and configure build path.
Add the following class to your package.
package com.abhan.objectinpreference;
import java.lang.reflect.Type;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class ComplexPreferences {
private static ComplexPreferences complexPreferences;
private final Context context;
private final SharedPreferences preferences;
private final SharedPreferences.Editor editor;
private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>(){}
.getType();
private ComplexPreferences(Context context, String namePreferences, int mode) {
this.context = context;
if (namePreferences == null || namePreferences.equals("")) {
namePreferences = "abhan";
}
preferences = context.getSharedPreferences(namePreferences, mode);
editor = preferences.edit();
}
public static ComplexPreferences getComplexPreferences(Context context,
String namePreferences, int mode) {
if (complexPreferences == null) {
complexPreferences = new ComplexPreferences(context,
namePreferences, mode);
}
return complexPreferences;
}
public void putObject(String key, Object object) {
if (object == null) {
throw new IllegalArgumentException("Object is null");
}
if (key.equals("") || key == null) {
throw new IllegalArgumentException("Key is empty or null");
}
editor.putString(key, GSON.toJson(object));
}
public void commit() {
editor.commit();
}
public <T> T getObject(String key, Class<T> a) {
String gson = preferences.getString(key, null);
if (gson == null) {
return null;
}
else {
try {
return GSON.fromJson(gson, a);
}
catch (Exception e) {
throw new IllegalArgumentException("Object stored with key "
+ key + " is instance of other class");
}
}
} }
Create one more class by extending Application class like this
package com.abhan.objectinpreference;
import android.app.Application;
public class ObjectPreference extends Application {
private static final String TAG = "ObjectPreference";
private ComplexPreferences complexPrefenreces = null;
#Override
public void onCreate() {
super.onCreate();
complexPrefenreces = ComplexPreferences.getComplexPreferences(getBaseContext(), "abhan", MODE_PRIVATE);
android.util.Log.i(TAG, "Preference Created.");
}
public ComplexPreferences getComplexPreference() {
if(complexPrefenreces != null) {
return complexPrefenreces;
}
return null;
} }
Add that application class in your manifest's application tag like this.
<application android:name=".ObjectPreference"
android:allowBackup="false"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
....your activities and the rest goes here
</application>
In Your Main Activity where you wanted to store value in Shared Preference do something like this.
package com.abhan.objectinpreference;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private final String TAG = "MainActivity";
private ObjectPreference objectPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objectPreference = (ObjectPreference) this.getApplication();
User user = new User();
user.setName("abhan");
user.setAddress("Mumbai");
user.setAge(25);
user.setActive(true);
User user1 = new User();
user1.setName("Harry");
user.setAddress("London");
user1.setAge(21);
user1.setActive(false);
ComplexPreferences complexPrefenreces = objectPreference.getComplexPreference();
if(complexPrefenreces != null) {
complexPrefenreces.putObject("user", user);
complexPrefenreces.putObject("user1", user1);
complexPrefenreces.commit();
} else {
android.util.Log.e(TAG, "Preference is null");
}
}
}
In another activity where you wanted to get the value from Preference do something like this.
package com.abhan.objectinpreference;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
private final String TAG = "SecondActivity";
private ObjectPreference objectPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
objectPreference = (ObjectPreference) this.getApplication();
ComplexPreferences complexPreferences = objectPreference.getComplexPreference();
android.util.Log.i(TAG, "User");
User user = complexPreferences.getObject("user", User.class);
android.util.Log.i(TAG, "Name " + user.getName());
android.util.Log.i(TAG, "Address " + user.getAddress());
android.util.Log.i(TAG, "Age " + user.getAge());
android.util.Log.i(TAG, "isActive " + user.isActive());
android.util.Log.i(TAG, "User1");
User user1 = complexPreferences.getObject("user", User.class);
android.util.Log.i(TAG, "Name " + user1.getName());
android.util.Log.i(TAG, "Address " + user1.getAddress());
android.util.Log.i(TAG, "Age " + user1.getAge());
android.util.Log.i(TAG, "isActive " + user1.isActive());
} }
Hope this can help you. In this answer I used your class for the reference 'User' so you can better understand. However we can not relay on this method if you opted to store very large objects in preference as we all know that we have limited memory size for each app in data directory so that if you are sure you have only limited data to store in shared preference you can use this alternative.
Any suggestions on this implement are most welcome.
the other way is to save each property by itself..Preferences accept only primitive types, so you can't put a complex Object in it
You can use the global class
public class GlobalState extends Application
{
private String testMe;
public String getTestMe() {
return testMe;
}
public void setTestMe(String testMe) {
this.testMe = testMe;
}
}
and then Locate your application tag in nadroid menifest, and add this into it :
android:name="com.package.classname"
and you can set and get the data from any of your activity by using the following code.
GlobalState gs = (GlobalState) getApplication();
gs.setTestMe("Some String");</code>
// Get values
GlobalState gs = (GlobalState) getApplication();
String s = gs.getTestMe();
You could just add some normal SharedPreferences "name", "address", "age" & "isActive" and simply load them when instantiating the class
Simple solution of how to store login value in by SharedPreferences.
You can extend the MainActivity class or other class where you will store the "value of something you want to keep". Put this into writer and reader classes:
public static final String GAME_PREFERENCES_LOGIN = "Login";
Here InputClass is input and OutputClass is output class, respectively.
// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";
// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();
// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
Now you can use it somewhere else, like other class. The following is OutputClass.
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");
// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);