Saving the data of a variable until the user closes the application? - android

I'm thinking how best to save the age of a user from 2 Date of Birth variables: YEAR and DAY_OF_YEAR. As age is a dynamic variable, I want the age variable creation to only be called once as I don't want to have to call a function every time I want to refer to age in the same user session.
Then when the user closes the app and reopens, I want age to be initialised again incase their age has changed.
So how can I save age for the user session and then initialise it again once the app reopens?

Use "Static" Variable
private static int myValue;
public static int getMyValue() {
return myValue;
}
public static void setMyValue(int myValue) {
MyActivity.myValue = myValue;
}
Static Values will only be held only as long as the app is Open
anytime you need to set new value you call setMyValue()

First of all, calculate the age in the application class and store it in shared preference, and use it wherever you want from shared preferences.
Also check in application class if calculated age and age in shared preference is same or not, if it is same no need to update preference else update shared preferences.
Suppose the name of your age calculation method is calculateAge(),
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
int age = calculateAge();
if (a != getAge()) {
saveAge(this, a);
}
}
int calculateAge() {
return age;
}
public static void saveAge(Context context, String lang, int age) {
SharedPreferences sharedPref = context.getSharedPreferences(quesID, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("age", age);
editor.apply();
}
public static int getAge(Context context) {
SharedPreferences sharedPref =
context.getSharedPreferences(context.getString(R.string.filename),
Context.MODE_PRIVATE);
return sharedPref.getInt("age", 0);
}
}
and to use age anywhere in app use App.getAge();

Related

Access SharedPreference inside a class that extends BroadcastReceiver

I'm trying to call my method(saveSharedpreferences.setCountReceived) from a class (SMSSendingWeb) that extends BroadcastReceiver, to a custom SaveSharedPreferences class.
My problem is it can't save into the SharedPreferences nothing happens.
I'm confused where is the problem of my code.
My argument in this method has error when
saveSharedpreferences.setCountReceived(SMSSendingWeb.this, countReceived);
I changed it to context has also error
saveSharedpreferences.setCountReceived(context, countReceived);
Here's my code: Please look into setCountReceived()
public class SaveSharedPreferences {
static final String PREF_USER_NAME= "username";
static final String PREF_COUNT_RECEIVED= "received";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
//==========================================================
public static void setCountReceived(Context ctx, Integer countReceived)
{
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putInt(PREF_COUNT_RECEIVED, countReceived);
editor.commit();
}
}
Android code:
public class SMSSendingWeb extends BroadcastReceiver {
RestService restService;
public static Integer countReceived = 0;
SaveSharedPreferences saveSharedpreferences;
#Override
public void onReceive(Context context, Intent intent) { //for Receiving
restService = new RestService();
saveSharedpreferences = new SaveSharedPreferences();
Bundle b = intent.getExtras();
Object[] pduObj= (Object[]) b.get("pdus");
String mobileno = null;
String message = null;
String data = null;
for(int i=0;i<pduObj.length;i++){
SmsMessage smsMessage=SmsMessage.createFromPdu((byte[]) pduObj[i]);
//get the sender number
mobileno=smsMessage.getOriginatingAddress();
//get the sender message
message=smsMessage.getMessageBody();
data="From : "+mobileno+"\n Message : "+message;
}
SMSInbox sms = new SMSInbox();
sms.MobileNo = mobileno;
sms.Message = message;
restService.getService().addSMS(sms, new Callback<String>() {
#Override
public void success(String s, Response response) {
//Toast.makeText(, "Successfully added", Toast.LENGTH_LONG).show();
countReceived += 1;
saveSharedpreferences.setCountReceived(SMSSendingWeb.this, countReceived);
Log.d("API inside restService", "count: " + countReceived);
}
#Override
public void failure(RetrofitError error) {
//Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
countReceived += 1;
Log.d("API outside restService", "count: " + countReceived);
saveSharedpreferences.setCountReceived(context, countReceived);
}
You are trying to access the Preferences and not Shared Preference there is a subtle difference between the two. As from this answer
Preferences is an Android lightweight mechanism to store and retrieve
pairs of primitive data types (also called Maps, and Associative
Arrays).
In each entry of the form the key is a string and the value must be a
primitive data type.
WHEN WE NEED THEM:
PREFERENCES are typically used to keep state information and shared
data among several activities of an application.
Shared Preferences is the storage, in android, that you can use to
store some basic things related to functionality, users' customization
or its profile.
Suppose you want to save user's name in your app for future purposes.
You cant save such a little thing in database, So you better keep it
saved in your Preferences. Preferences is just like a file , from
which you can retrieve value anytime in application's lifetime in a
KEY-VALUE pair manner.
Take another example, If you use whatsapp, we have a wallpaper option
there. How the application knows which image serves as wall-paper for
you whenever you open your whatsapp. This information is stored in
preferences. Whenever you clear data for any app, preferences are
deleted
You are using Preferences and trying to write a value in Shared Preference so I just changed your code to using the Shared Preference.
For saving preferences
public static void setCountReceived(Context ctx, Integer countReceived)
{
SharedPreferences.Editor editor = getSharedPreferences(YOUR_PREF_NAME,MODE_PRIVATE).edit();
editor.putInt(PREF_COUNT_RECEIVED, countReceived);
editor.commit();
}
For retrieving preferences,
static SharedPreferences getSharedPreferences(Context ctx) {
return context.getSharedPreferences(YOUR_PREF_NAME,MODE_PRIVATE);
}

android saving a value from a textview

I made a simple counting app where there is Text-view that contains the counted number, and I want to save the counted number so that when I close the app the counted number should be there.
You should use SharedPreferences. Save the count to preference every time it is updated. Read and load the saved value in TextView when app starts next time.
The best solution for your problem is to use SharedPreference.
create another class called SaveCounterValue and copy the following code to that class
public class SaveCounterValue {
static final String PREF_COUNTER= "counter";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setCounter(Context ctx, int counter)
{
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putInt(PREF_COUNTER, counter);
editor.commit();
}
public static Long getCounter(Context ctx)
{
return getSharedPreferences(ctx).getInt(PREF_COUNTER, 0);
}
}
Then in your activity after conter++ you copy the below code
SaveCounterValue.setConuter(context, counter);

How to use Android SharedPreferences

I am working on an Android project where a user can store some data but is able to delete and change/alter/update the values, I have been searching for a while now for a tutorial, but are not able to find any, so I was wondering, Is it possible to use SharedPreferences for that?
While you can always read the docs and know more about SharedPreferences, for a quick start here are few static methods from one of my project which you can use.
public static boolean getBooleanPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean(key, false);
}
public static void setBooleanPrefs(Context ctx, String key, Boolean value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putBoolean(key, value).commit();
}
public static String getStringPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getString(key, "");
}
public static void setStringPrefs(Context ctx, String key, String value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putString(key, value).commit();
}
public static int getIntPrefs(Context ctx, String key) {
return PreferenceManager.getDefaultSharedPreferences(ctx).getInt(key, 0);
}
public static void setIntPrefs(Context ctx, String key, int value) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().putInt(key, value).commit();
}
public static void clearPrefs(Context ctx) {
PreferenceManager.getDefaultSharedPreferences(ctx).edit().clear().commit();
}
So far if data is limited to some values, yes you can use SharedPreferences for that. You can easily update/alter/clear values in SharedPreferences.For usage of Shared preferences, refer these
Android Shared preferences example
http://developer.android.com/guide/topics/data/data-storage.html#pref
http://www.tutorialspoint.com/android/android_shared_preferences.htm
But if your data is not limited and have some repititive type of values to be stored.For eg. data of app users, their info and all that, then you should go for local database using SQLite. For SQLite,you should go through this tutorial
For pros and cons of SQLite and SharedPreferences, you should go through this answer
shared preference is good way to store values.
need to declare shared preference and stored value to it like.
SharedPreferences prefrs = PreferenceManager
.getDefaultSharedPreferences(getApplication());
Editor editor = prefrs.edit();
editor.putString("key",abc);
editor.commit();
you can easily get that value like below...
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String name = prefs.getString("key", "default");
you can delete that stored value and can use for stored new value like below
SharedPreferences prefrs = PreferenceManager
.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editor = prefrs.edit();
editor.clear();
editor.commit();
finish();

SharedPreferences commit and rollback

Is the following the intended/reasonable way to commit and rollback SharedPreferences, and to use it in general?
public class Settings {
private static final String PREFS_NAME = "Settings";
private static SharedPreferences preferences = null;
private static SharedPreferences.Editor editor = null;
public static void init(Context context) {
// Activity or Service what ever starts first provides the Context
if (preferences == null)
// getSharedPreference because getPreferences is a method of Activity only (not Service or Context)
preferences = context.getSharedPreferences(PREFS_NAME, 0);
editor = preferences.edit();
}
public static String getEmail() {
return preferences.getString("email", null);
}
public static void setEmail(String email) {
editor.putString("email", email);
}
public static String getPassword() {
return preferences.getString("password", null);
}
public static void setPassword(String password) {
editor.putString("password", password);
}
public static void save() {
editor.commit();
}
public static void rollback() {
editor = preferences.edit();
}
}
This is more detail as enforced by stackoverflow editor. I really don't know what else should be said about this.
Experts' feedback is much appreciated. And if may snipped is reasonable it could well as better explanation then all other threads I have found here.
There is only one change in the following method from my understanding. Because if u forget to initialize preference ,u will get null pointer exception.
public static void rollback(Context context) {
if (preferences == null)
// getSharedPreference because getPreferences is a method of Activity only (not Service or Context)
preferences = context.getSharedPreferences(PREFS_NAME, 0);
editor = preferences.edit();
}
Best way to have things persisted is "USE OF PREFERENCE ACTIVITY". See examples and read online docs about them. Use EditTextPreference for automatically persisting values.
First thing is that no body ever uses shared preference to save user id and password . Because shared preference is key-value pair. For key Email you can have only one respective value. Here what you want is :- for key Email multiple values and for key password also multiple value.
There exist one solution if u want to do something like this. Use email id (xyz#xyz.com) as key . And password as the value of key(xyz#xyz.com).

android default values for shared preferences

I am trying to understand the SharedPreferences of Android. I am a beginner
and don't know a lot about it.
I have this class I implemented for my app Preferences
public class Preferences {
public static final String MY_PREF = "MyPreferences";
private SharedPreferences sharedPreferences;
private Editor editor;
public Preferences(Context context) {
this.sharedPreferences = context.getSharedPreferences(MY_PREF, 0);
this.editor = this.sharedPreferences.edit();
}
public void set(String key, String value) {
this.editor.putString(key, value);
this.editor.commit();
}
public String get(String key) {
return this.sharedPreferences.getString(key, null);
}
public void clear(String key) {
this.editor.remove(key);
this.editor.commit();
}
public void clear() {
this.editor.clear();
this.editor.commit();
}
}
The thing is that I would like to set default preferences. They would be set when the app is installed and could be modified after by the application and stay persistent.
I heard about a preferences.xml but I don't understand the process.
Could someone help me?
Thanks for you time
Simple, if you want a separate default value for each variable, you need to do it for each one, but on your method:
public String get(String key) {
return this.sharedPreferences.getString(key,"this is your default value");
}
If the variable was never accessed by the user or was never created, the system will set the default value as value and if you or the user changed this value, the default value is ignored. See http://developer.android.com/guide/topics/data/data-storage.html#pref
Directly from the Android Documentation:
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings. This data will persist
across user sessions (even if your application is killed).
Could you use the default value parameter of the getX() method?
For example, to get a String called 'username', you could use this:
String username = prefs.getString("username_key", "DefaultUsername");
You can simply define your default values in your Preferences class.
You can store default values in string resource:
<string name="key_name">default_value</string>
and then get it as it follows:
int ResId = context.getResources().getIdentifier(key_name, "string", context.getPackageName()));
prefs.getString(key_name,context.getResources().getString(ResId);

Categories

Resources