How to Set Values in Shared Preferences using Java in Android? - java

here is the Method:
public class SessionManager {
public static void setStatus(Context context, int value, String key) {
// TODO Auto-generated method stub
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = pref.edit();
editor.putInt(key,value);
editor.commit();
}
public static int getStatus(Context c,String key){
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
int a = pref.getInt(key,0);
return a;
}
}
i am trying to set value "1" in shared Preferences on PostExecuteMethod() of Async Task:
protected void onPostExecute(Void result){
super.onPostExecute(result);
progressDialog.dismiss();
Log.i("Setting Status Variables Value in Customer:",""+AndroidUtil.getStatusForServices());
SessionManager.setStatus(context,1,"status");
Log.i("Setting Status Variables Value in Customer after:",""+AndroidUtil.getStatusForServices());
}
But it still it saves 0 in Variable Here is the Logcat:
01-04 03:31:32.430: I/Setting Status Variables Value in Customer:(20879): 0
01-04 03:31:32.440: I/Setting Status Variables Value in Customer after:(20879): 0

You can easily do this in the following way.
First you will need declare the SharedPreferences inside the Activity in this manner:
public class MainActivity extends Activity
{
SharedPreferences sp;
int val=2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=this.getSharedPreferences("service_validation", MODE_WORLD_READABLE);
val=sp.getInt("VALIDATION", val);
.
.// you can put here anything code
.
}
.
.// you can put here anything method
.
.
}
Now when you would like to save the value in background asynch task. Please put this code inside onPostExecute(..) method in this manner:
SharedPreferences.Editor editor=sp.edit();
editor.putInt("VALIDATION", 1);
editor.commit();
It is better to use this code on doInBackground(..) method.
After saving the value, refresh or re-run the Activity. It will show the effect .
Enjoy the code!!
If my answer will help you then please support my answer.

Related

How to retrieve boolean values from a different activity?

I have one activity that sets various variables to either true or false, to be used as settings for other activities. I need to be able to call the state of these variables in my other activities but I can't figure out how. I know for strings I can use
getApplicationContext().getResources().getString(R.string.stringName);
but the same thing won't work for Boolean. Someone suggested using
activityName.variableName
but that won't work either. Any suggestions?
Instead of static variable or application variable use SharedPreference to achieve this which also persist on application close.
SettingsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("YOUR_KEY1", true);
editor.putBoolean("YOUR_KEY2", false);
editor.putBoolean("YOUR_KEY3", true);
editor.commit();
....
}
Then in other activity or fragment use getBoolean() to retrieve those data.
OthersActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
....
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//here false is the default value if key is missing
boolean value1 = sharedPreferences.getBoolean("YOUR_KEY1", false);
boolean value2 = sharedPreferences.getBoolean("YOUR_KEY2", false);
boolean value3 = sharedPreferences.getBoolean("YOUR_KEY3", false);
....
}
you can make global variables using many ways most common two
1- use of Application class
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
sure don't forgt to declare in manifest file
<application
android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
How to use?
// set
((MyApplication) this.getApplication()).setSomeVariable("foo");
// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();
2- by using Extra as a variable to be passed from activity to others with help of Intent
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
to read it in second activity use
String sessionId = getIntent().getStringExtra("EXTRA_SESSION_ID");
for setting screens suggest to use SharedPreference you can learn how to use from here

Error in onPause and onResume method restoring the user last state

Am tring to restore the the last page of user before webview app close o paused. But am getting error in onPause and onResume method, i don't know how to fixe the error cannot resolve symbol context | cannot resolve method put
#Override
protected void onPause() {
// cannot resolve symbol context
// cannot resolve method put
super.onPause();
SharedPreferences prefs = context.getApplicationContext().getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
SharedPreferences.Editor edit = prefs.edit();
edit.put("lastUrl", exfilevbrowser.getUrl());
edit.commit();
}
#Override
protected void onResume() {
super.onResume();
// cannot resolve symbol context
if(exfilevbrowser != null) {
SharedPreferences prefs = context.getApplicationContext().getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
String s = prefs.getString("lastUrl","");
if(!s.equals("")) {
appLoadUrl(s, false);
}
}
}
If you are inside an activity, directly use getSharedPreferences() instead of context.getApplicationContext().getSharedPreferences()
If you are inside fragment, use getContext().getSharedPreferences()
Then use edit.putString() instead of edit.put()

SharedPreferences not working. Always show the same value

This is my MainActivity.java's onCreate method:
protected void onCreate(Bundle savedInstanceState) {
loadSavedPreferences();
savePreferences("storedAddress", userAddress.getText().toString());
}
These 2 are the methods inside the class
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String address = sharedPreferences.getString("storedAddress", "YourAddress");
userAddress.setText(address);
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
Here's the flow. First time user uses the app has to enter their address in the EditText field. I want the same address to be stored there when the user returns.
The problem with the code above: It always shows "YourAddress" in the EditText field. There's no login required for this application. Just a simple form.
Use your savePreferences() method in any action the user can do after typing his address,a button click or whatever.
The way it is now, it's saving only when the activity gets created and after you load the preferences with the default value YourAddress. That's why you always get the same value.

Get attributes from SharedPreferences in android

This is my MainActivity.java where I instanciate static SharedPreferences and it's editor:
public static SharedPreferences settings;
public static SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager.getDefaultSharedPreferences(this);
editor = settings.edit();
Then I make an AsyncTask call to another java class where I try to store a token in onPostExecute method to this SharedPreferences.
#Override
protected void onPostExecute(String result) {
MainActivity.editor.putString("auth_token", result);
MainActivity.editor.commit();
Log.d("token", MainActivity.settings.getString("auth_token", "Nothing"));
}
This Log.d() method outprints the token value in the console, which is "OK". But then I start an acitivity Next.java where I try to get this token on a screen using this:
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
String auth_token_string = MainActivity.settings.getString("auth_token", "Nothing");
text = (TextView) findViewById(R.id.logintxt);
text.setText(auth_token_string);
And the result on the screen is the default String "Nothing".
What am I doing wrong here? ...and is this the right way to use SharedPreferences? I got this idea here in this topic.
EDIT:
Code from AuthorizeActivity.java where I call the asyncTask:
public void getToken(String code){
AsyncTask<String, Void, String> tsk = new Api().execute(code);
Intent i = new Intent(this.getBaseContext(), Next.class);
dialog.dismiss();
startActivity(i);
}
Your settings variable is static, it's initialised in onCreate method of MainActivity when you access settings in Next.java it's not initialised yet.
You have access to SharedPreferences in Next.java (it's shared).
EDIT :
add a update method in MainActivity :
public void update() {
Intent i = new Intent(this.getBaseContext(), Next.class);
startActivity(i);
}
and your postExecute should look like this :
#Override
protected void onPostExecute(String result) {
MainActivity.editor.putString("auth_token", result);
MainActivity.editor.commit();
Log.d("token", MainActivity.settings.getString("auth_token", "Nothing"));
((MainActivity) context).update();
}
Do not use the settings from MainActivity, create a new SharedPrefs instance and call getString method.
Edit: I've created an example of how this should be handled on GitHub
Firstly, I would advise that you don't make your members static; they don't need to be static.
On your Next.class (Perhaps you should rename this, it's not clear what it does), you just need to get a handle on the shared preferences again with your new context:
PreferenceManager.getDefaultSharedPreferences(this);
Please note, there's a difference between getDefaultSharedPreferences and getSharedPreferences - use whichever you think it most appropriate.

SharedPreferences not keeping value

With SharedPreferences, i would like to save a value (that will be later the date of last update) and load it. It works well until i shut down my phone or force close my application. It resets the value.
Here's the code :
public class feedPlayer extends Activity
{
public final static String PARAM_USERDETAILS="userdetails";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadvars();
savevars();
}
public void savevars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
Editor edit = parametres.edit();
edit.clear();
//Global.Maj = "maj"
TextView maj=(TextView) findViewById(R.id.datemaj);
edit.putString("gimli", Global.MAJ);
edit.commit();
maj.setText(Global.MAJ);
}
public void loadvars()
{
SharedPreferences parametres = this.getSharedPreferences(PARAM_USERDETAILS, MODE_PRIVATE);
TextView maj=(TextView) findViewById(R.id.datemaj);
String Smaj = parametres.getString("gimli", Global.MAJ);
maj.setText(Smaj);
}
}
Use onCreate() method to load your data and onDestroy() method to save data:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadvars();
}
#Override
protected void onDestroy() {
super.onDestroy();
savevars();
}
You can use too: onResume() with onPause() method but this two method are reserved for process (start process in onResume() method, stop process in onPause() method)
You are calling the savevars() method each time your activity is created. That means for sure every time your application starts.
In this method you are writing always the same value in the preferences:
edit.putString("gimli", Global.MAJ);
edit.commit();

Categories

Resources