Shared Preference not saving value [closed] - android

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am just learning to build some applications in Android. Out of curiosity, I have a small and weird problem using Shared Preferences. If someone can help me addressing this issue , I would be most thankful to them. Anyways,here goes the problem. I have 2 Activities. 1. Activity 1 : Consists of just one button that will get you to the next activity. 2. Activity 2 : Consists of a listview with checkbox (simple_list_item_checked or simple_list_multi_choice_item).
My question is: I open my application, hit the button on my first activity screen, this moves me to the second activity. I check an item in the listview. I hit the back button on my phone, go to the first activity, again press the button on my activity 1 screen, this takes me to the list again. Now I just leave my list item checked(I don't change anything that is already checked previously). Now again, I hit back button on my phone, get back to activity one. Now again when I press the button on my activity one screen. It takes me back to the listview but SURPRISINGLY nothing is checked. To note a point here, I had also set and retrieved my shared preference.
MY QUESTION IN A SINGLE LINE IS : If I don't change a value in the check list while I'm in that Activity and then go back to the Main Activity, and get back to the same check list activity, my shared preference does not load what has been saved earlier. Is this the normal behavior of Shared Preference or is it a problem in the coding.
I would just like to know how preference values are saved and retrieved and how long does a preference save a value ? I mean the lifecycle of the saved value in preference.
MY SECOND QUESTION : Also, I would like to know one more thing in activity life cycle. When I am in the second activity as explained in the above example. Now I press the home button , now I go to the background tasks and clear all the tasks(Apps) that are running . Now, my question is which state of activity life cycle is followed or what will be the final activity lifecycle before i clear all my apps from the background ? Please someone help me out on this. Thanks to all those creative developers out there in advance. Hope someone can solve my issue.
public class Secondact extends ListActivity {
ListView list;
SharedPreferences pref;
int pos,itemposition,positionvalue;
boolean boolval,checkvalue;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.secondact);
Toast.makeText(getApplicationContext(), "ONCREATE", 50).show();
list=getListView();
String[] family_array=this.getResources().getStringArray(R.array.family);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,family_array);
list.setAdapter(adapter);
list.setChoiceMode(1);
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
Toast.makeText(getApplicationContext(), "DATA LOADED ITEM NO:"+pos, 50).show();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
pos=position;
list.setItemChecked(pos, true);
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
// Toast.makeText(getApplicationContext(), "PAUSE", 50).show();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
//Toast.makeText(getApplicationContext(), "RESUME", 50).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor=pref.edit();
editor.putInt("itempos", pos);
editor.putBoolean("boolvalue", list.isItemChecked(pos));
editor.commit();
Toast.makeText(getApplicationContext(), "DESTROY", 50).show();
Toast.makeText(getApplicationContext(), "DATA SAVED ITEM NO:"+pos, 50).show();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
pos=pref.getInt("itempos", pos);
boolval=pref.getBoolean("boolvalue", true);
list.setItemChecked(pos, boolval);
//Toast.makeText(getApplicationContext(), "RESTART", 50).show();
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
savedInstanceState.putInt("itempositionno", positionvalue);
savedInstanceState.putBoolean("checkvalue", true);
Toast.makeText(getApplicationContext(), "ONSAVEINSTANCE", 50).show();
list.setItemChecked(pos, checkvalue);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
pos=savedInstanceState.getInt("itempositionno", pos);
checkvalue=savedInstanceState.getBoolean("checkvalue", true);
list.setItemChecked(pos, checkvalue);
Toast.makeText(getApplicationContext(), "ONRESTOREINSTANCE", 50).show();
super.onRestoreInstanceState(savedInstanceState);
}
}

I would just like to know how preference values are saved and
retrieved and how long does a preference save a value ? I mean the
lifecycle of the saved value in preference.
A single line reply to your single line question -
It is saved throughout the life-cycle of the application unless you yourself clear it.
To obtain shared preferences:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
In order to edit(clear) -
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
In order to save -
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();
Read - how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values.
Which state of activity life cycle is followed or what will be the
final activity life-cycle before I clear all my apps from the
background ?
Depends on your requirement. No need to follow final activity life-cycle to do this. For example - When the user logs out from the application, preferences related to the user are of no use and can be cleared independent of the life-cycle just after the log out button press.

Alright, for those who are suffering from the same problem of the shared preference not maintaining the value on activity switch. This piece of logic does the trick:
Set your default value of your row in the listview like this
sp.getInt("CheckedValue",
pass the position of the ealier checked row as the default one
viz.Listitem.getCheckedItemPosition());
This will save the checked value throughout your application's life cycle and/or activity life cycle.
NOTE:
Make sure to clear your sharedpreference before commit() so as to avoid the hectic memory usage of your app.

Related

Android - saving a position of a page when pausing

I got a ViewPager which saves the current page position (as the order in it's adapter). When the app goes to the backgroung, the ViewPager seem to lose the position it was last in and when switching to the app again, it starts at fragment with the position 0.
How can I save the current position and set the correct fragment? Hopefully it's something that needs to be done in a single place only and not in every fragment.
OK so it eventually was just something standard. I just overrided OnPause and OnResume. I saved the state with a SharedPreferences in the OnPause method and restored it in the OnResume method.
#Override
public void onPause()
{
super.onPause();
final SharedPreferences.Editor ed = getSharedPreferences("name",
android.content.Context.MODE_PRIVATE).edit();
ed.putInt(INDEX_KEY_STRING, viewPager.getCurrentItem());
ed.commit();
}
#Override
public void onResume()
{
super.onResume();
final SharedPreferences sp = getSharedPreferences("name",
android.content.Context.MODE_PRIVATE);
viewPager.setCurrentItem(sp.getInt(INDEX_KEY_STRING, 0));
}

How to storesome data after activity is destroyed

I am creating a calculator application, when my activity is sent to background and then brought to front.The result in it becomes zero. How can i save the data nd retrive it next time hen activity is recreated.
For that specific case, you want to use the Activity lifecycle methods onSaveInstanceState and onRestoreInstanceState. Override both those methods, and then save the necessary data in onSaveInstanceState. In the onCreate or the onRestoreInstanceState check for the existence of the saved data and then restore it to the right place.
Note: you can use preferences or a database as well, but those are generally to be used for data that should last more than a single background/restore cycle. The onSaveInstanceState/onRestoreInstanceState methods are specifically for the case where an Activity gets sent to the background and then restored later.
Use SharedPreferences like :
SharedPreferences preferences = null;
SharedPreferences.Editor editor = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
}
in onDestory() write :
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
editor = preferences.edit();
editor.putInt(YOUR_KEY, YOUR_VALUE);
editor.commit();
}
and in onStart() write :
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
int result = preferences.getInt(YOUR_KEY, YOUR_VALUE);
}
Hope this will help you

Android Java - saving EditText's text when user presses "back"

I need to fill form and by pressing "Back" button save it , let's say, to preferences.
Or even show it to Log.
The problem is when I use onBackPressed() - Activity goes to onPause() and myEditText.getText().toString() returns result from XML and not the result that was actually in myEditText field. Same thing goes for onDestroy().
Of course, if I hang someButton.onClickListener() it saves my data well from myEditText because Activity doesn't go onPause() and doesn't take result from XML, but I need to save it exactly by pressing back button.
The code is basic:
EditText etCompetitionName;
Competition competition;
etCompetitionName=(EditText) findViewById(R.id.etCompetitionName);
Intent intent=getIntent();//I get number of object to work with
pos=intent.getIntExtra("pos", -1); // this is this number
competition=getObject(pos);// well, this is loading this object
olDetCompetitionName=competition.getName();//getting name from loaded object
etCompetitionName.setText(olDetCompetitionName);//set this text to EditText field
...
then :
protected void onDestroy() {
super.onDestroy();
//try to save
competition.setName(etCompetitionName.getText().toString());
saveObject(competition);
}
So, it saves old value, the one I set in the beggining. If I don't set it - it will be taken from layout xml. It is issue of onPause() I need to avoid it.
Your question is quite confusing but if you override onBackPressed() you can get the data.
#Override
public void onBackPressed()
{
String text = myEditText.getText().toString();
// save text
super.onBackPressed();
}
I know you said you did this but show how you are doing it if this doesn't work. This will put whatever the user has typed in the text variable then you can save it in SharedPreferences or wherever you want.
You can also do the same thing in onPause() if you want it to save if, say, something else comes in the foreground.
SecondActivity.Java -> I saved two edittext value in SharedPReference and called the MainActivity intent
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editor = sharedPreferences.edit();
editor.putString("1", a.getText().toString());
editor.putString("2", b.getText().toString());
editor.commit();
Intent i = new Intent(SecondActivity.this,MainActivity.class);
SecondActivity.this.startActivity(i);
}
MainActivity.Java -> I have a button listener to show a Toast with values from the sharedpreference.
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String a = pref.getString("1", "") ;
String b = pref.getString("2", "");
Toast.makeText(getApplicationContext(),a+" "+b, Toast.LENGTH_LONG).show();
}
});

How can i stop to be refreshed my values in android activity

I am working in android. I am designing a file upload functionality.
This is my layout:
If I fill my entries like as title,price,category and then I press browse button for browse option then I go to BrowseActivity using startActivity(). But when I come back to this activity then all entries which were filled by me disappear. please suggest me what should I do for this so my entered entries save. If I do browse first then fill entries then it works properly.
What should I do for the case in which user first fill entries and then click on the browse button?
Use the SharedPreferences options to save all the Strings in onPause(). You can get them back in onResume() and fill out your text boxes. This is also nice since you can save the values that were entered and restore them each time the user leaves the app for any other reason.
EDIT:
Quick example:
Save your strings like so:
#Override
public void onPause(){
super.onPause();
// Save the user preferences during runtime for later use.
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("title", "Value of title");
editor.commit();
}
Then you get get the value back like this.
#Override
public void onResume(){
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
String title = settings.getString("title");
}
Here is what you need to do.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("title", title.getText.toString());
//Do the same for the other 2 boxes.
super.onSaveInstanceState(savedInstanceState);
}
and in onRestoreInstanceState() pull the items out.
Like..
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
String Title = savedInstanceState.getString("title");
//Do the same for other String items you put into the bundle using the savedInstanceState() above. And then use EditText.setText(title); to set the text
}
The bundle is used exactly for this purpose. You Can get more info here
Check out android's shared preferences, they should give you an easy way to store data.
Android Shared Preferences
http://developer.android.com/guide/topics/data/data-storage.html
http://developer.android.com/reference/android/content/SharedPreferences.html
Another way is to create an object which holds the data you need, and don't new it in the onResume method...

SharedPreferences are shown only after restarting the activity

Hello Together I startet to write my first Android app and I tried to use the SharedPreferences to have the possibility to store some strings.
I can Type in different names and in the onStop() I put them into the SharedPreferences and after that i make a commit. Has someone a solution that Preferences are shown on the next Activity immediatly? Because at the moment I have to switch back to the Activity where I Typed in the names and if I immediatly switch back to the Activity where the names shall be shown they appear.
protected void onStop() {
SharedPreferences.Editor edit = set.edit();
for(int x=0;x<counterM;x++){
edit.putString("playerM"+x, playersMale.get(x));
}
for(int x=0;x<counterF;x++){
edit.putString("playerF"+x, playersFemale.get(x));
}
edit.putInt("counter", counterF + counterM);
edit.commit();
super.onStop();
}
and here is the onCreate() where I load the name...
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
set = this.getSharedPreferences("MY_COUNT",0);
this.setContentView(R.layout.decisionscreen);
Random r = new Random();
int i = set.getInt("counter",1000);
int x = r.nextInt(i);
name = set.getString("playerM"+x, "no Players found");
TextView t = (TextView)findViewById(R.id.nameView);
t.setText(name+" "+i);
dareButton();
truthButton();
}
I hope someone can figure out what my problem is.
Try to put the shared preferences editor stuff in the onPause override. It will be called as soon as you switch the activity.

Categories

Resources