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.
Related
I have a page in my application where the user can enter a product name and it's calorie count, which it then removes from a daily calorie count which comes from another class. This works perfectly I wanted to make it so that it doesn't reset to the original value each time the page is opened (unless its a fresh install / manual reset via a button).
I came across SharedPreferences and tried to implement this, but it always comes up with the default value in my onResume method and I am not too sure why and need some assistance to figure out what I am doing wrong and how to fix it, as I will need to use this in several other classes also.
My Class:
public class CalorieTracker extends AppCompatActivity {
protected String age, calorieCount;
protected EditText itemName, kCal;
protected TextView remainingCalories;
protected Button submitBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_tracker);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
calorieCount = extras.getString("calories");
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount = Integer.parseInt(remainingCalories.getText().toString());
int enteredAmount = Integer.parseInt(kCal.getText().toString());
calorieCount = String.valueOf(currentCount - enteredAmount);
remainingCalories.setText(calorieCount);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sessionCalories",remainingCalories.getText().toString());
editor.commit();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
}
http://prntscr.com/me99dp
Image of what it looks like when I boot the application, even though the initial calorieCount value should be 2100 which I get from the previous page using the Bundle extras.
If I change the
line remainingCalories.setText(mPrefs.getString("sessionCalories","")); in my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3")); then it shows 3 initially.
Make sure that your data is updated in shared preference correctly. In Activity life cycle after onviewCreated only onResume called .
so if your current activity will go to foreground or rotate then only onResume will call again.
so solution ,in button click after set the value and get value from sharedpreference and display like this
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// first time save data
setvalueFromSharedpreference()
}
});
public setvalueFromSharedpreference()
{
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
when I boot the application, even though the initial calorieCount
value should be 2100 which I get from the previous page using the
Bundle extras.
If I change the line
remainingCalories.setText(mPrefs.getString("sessionCalories","")); in
my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3"));
then it shows 3 initially.
Reason editText remainingCalories always have default (sharedpreference value) is because onResume method is called after onCreate in activity's lifecycle. Thats why, Bundle extras value is being overwritten by sharedpreference value.
You can achieve this in onCreate method by checking if Intent extras has value. If yes, then set that value otherwise set the sharedPrefrence's value as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
calorieCount = mPrefs.getString("sessionCalories","");
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
if(!calorieCount.isEmpty)
remainingCalories.setText(calorieCount);
else
{
calorieCount = extras.getString("calories");
}
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
}
And remove the sharedPreference setting from onResume.
Hope it helps cheers:)
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.
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
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();
}
});
I have a problem when creating a hangman game.
I'm pretty new to android, only been doing it for a week, but now i'm in a real jam.
I keep loosing an int variable's value at the same place everytime. It is the variable antallGjett (Means number fo guesses). I have pictures in an imageview there and the first is set to zero. First time it is okey, the image changes. But then next time, nothing happens. It never changes to image "hang2" on the second miss, but on the third miss it goes forward. BUT, the counter still have the value 6 at image nr 5. heres the method:
public void klikkKnapp(char[] c, Button bokstav, char[] l, char[] gjettetOrd) {
boolean bol= sjekkBokstav(c, bokstav, l, gjettetOrd);
if(bol== false) {
if(antallGjett>= 6)
antallGjett= 0;
++antallGjett; //number of guesses
String pakke= getApplicationContext().getPackageName();
image= getResources().getIdentifier(pakke+":drawable/hang"+ antallGjett+"", null, null); //
hangMan= (ImageView)findViewById(R.id.hengtmann);
if(hangMan.getId()== image) {
++antallGjett;
image= getResources().getIdentifier(pakke+":drawable/hang"+ antallGjett, null, null);
}
hangMan.setImageBitmap(BitmapFactory.decodeResource(getResources(), image));
}
if(antallGjett== 6)
showDialog(false);
else if(Arrays.equals(ord, gjettetOrd))
showDialog(true);
}
I have implementet onPause() and onResume() , but it doesent help.
Example of my onPause() method:
protected void onPause() {
super.onPause();
Context context = this.getBaseContext();
SharedPreferences sharedPref = context.getSharedPreferences("PREF_KEY", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("antallGJETT", antallGjett); // value to store
// Commit to storage
editor.commit();
}
And here onResume:
#Override
protected void onResume() {
super.onResume();
Context context = this.getBaseContext();
SharedPreferences sharedPref= context.getSharedPreferences("PREF_KEY", MODE_PRIVATE);
an
tallGjett= sharedPref.getInt("antallGJETT", antallGjett);
}
I have read and read and tried and tried, but i see no solution.. :(