Android SharedPreferences does not save after app reopening - android

I'm trying to use SharedPreferences with a very simple app
it is just a TextView with number 0 and one button to increment this number, but after reopening the app and press the button it resets to 0
Here is the code:
public class MainActivity extends AppCompatActivity {
public TextView t1;
public Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
t1=(TextView)findViewById(R.id.textView);
SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
int n=mypref.getInt("n",0);
String s=""+n;
t1.setText(s);
SharedPreferences.Editor editor=mypref.edit();
editor.putInt("n",0);
editor.apply();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
add();
}
});
}
The add method:
private void add() {
SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
SharedPreferences.Editor editor=mypref.edit();
int n=mypref.getInt("n",0);
n++;
String s=""+n;
t1.setText(s);
editor.putInt("n",n);
editor.apply();
}

You have this code every time your activity is created (same goes when you open the app):
SharedPreferences mypref=getSharedPreferences("file",MODE_PRIVATE);
int n=mypref.getInt("n",0);
String s=""+n;
t1.setText(s);
// here you reset the counter to 0
SharedPreferences.Editor editor=mypref.edit();
editor.putInt("n",0);
editor.apply();
// the problem ends here
So, to fix the problem simply remove the code between comments

Related

Save Changed Text Of a TextView

I have an Button in my first activity which changes it background onclick and save with SharedPreferences , but I want to set one more code that when I check the button it set the text of a TextView in my second activity to "Button-Checked" and when I uncheck it set the text of the TextView to "Button-Unchecked" and then SAVE the text (with SharedPreferences or anything else).
In my first activity:
public class MainActivity extends Activity {
private boolean likechek;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button like = (Button) findViewById(R.id.like);
like.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putBoolean("like_", !likechek).commit();
LikeAnalayzer();
}
});
}
private void LikeAnalayzer() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
likechek = sp.getBoolean("like_", false);
UpdateLikeButton();
}
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
}else{
like.setBackgroundResource(R.drawable.star);
}
}
}
and Second (its empty):
public class Fav extends Activity {
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fav);
tv = (TextView) findViewById(R.id.tv);
tv.setText("");
}
}
Thanks for your answer , I really need it.
If I understand you right, you want to set the text to the textView if the button is checked, so you could do it like the change of the background like this for example:
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
TextView myTextView = (TextView)findViewById(R.id.textView);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
myTextView.setText("Button-Checked");
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Checked").commit();
}else{
like.setBackgroundResource(R.drawable.star);
myTextView.setText("Button-Unchecked");
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Unchecked").commit();
}
}
and if you want to set the text of the textView in the second activity just skip the part in the first one that is myTextView.setText("Button-Checked"); like this:
private void UpdateLikeButton() {
Button like = (Button) findViewById(R.id.like);
if(likechek){
like.setBackgroundResource(R.drawable.starf);
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Checked").commit();
}else{
like.setBackgroundResource(R.drawable.star);
//and save in the shared preferences the state:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Dog.this);
sp.edit().putString("button_state", "Button-Unchecked").commit();
}
}
and do it in the second one like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fav);
tv = (TextView) findViewById(R.id.tv);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String buttonState = sp.getString("button_state", "");
tv.setText(buttonState);
}
Hopefully this helps you :)

sharedpreferences - getInt when button is clicked

scenario during a simple ball game i click exit and return to the menu and then exit out of the app,once i launch the app again I can click 'Continue" from the main menu and return to the game where i had left off or click New game and start again.
My problem is get sharedprefs are on onCreate, so even if i click 'New game' it continues from where i had left off.
I tried various onclick, findviewbyid methods and none of them worked, for example.
public class GActivity extends ActionBarActivity {
private int RWIDTH = 70;
// + a whole bunch of other unrelated stuff that i cut-out to make viewing easier.
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button CntButton = (Button) findViewById(R.id.ConGame);
CntButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
RWIDTH = settings.getInt("RWIDTH", RWIDTH);
}
});
}
protected void onStop(){
super.onStop();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("RWIDTH", RWIDTH);
editor.commit();
}

Two shared preferences in the same app

My app has got two activities. In both activities there's an EditText and a Button. You write a number inside and then, after pressing the button, the number is displayed via TextView. But the number in the activity A is different from the number in the activity B, and I want the two numbers to be saved.
In order to do that, I'm using getSharedPreferences, specifying a string name for each one:
Activity A:
EditText mark1;
public static final String Mark1 = "mark1Key";
TextView marksem1;
public static final String MarkSem1 = "marksem1Key";
Button calcsem1;
double mark1calc=0;
public static final String MyPREFERENCES = "MyPrefsA" ;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.etsam_gfa_layout);
initControls();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
mark1 = (EditText) findViewById(R.id.mark1);
if (sharedpreferences.contains(Mark1))
{
mark1.setText(sharedpreferences.getString(Mark1, ""));
}
marksem1 = (TextView) findViewById(R.id.total1calc);
if (sharedpreferences.contains(MarkSem1))
{
marksem1.setText(sharedpreferences.getString(MarkSem1, ""));
}
public static Double safeParse(String input) {
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
return 0d;
}
}
private void initControls() {
mark1=(EditText)findViewById(R.id.mark1);
marksem1=(TextView)findViewById(R.id.total1calc);
calcsem1=(Button)findViewById(R.id.total1);
calcsem1.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) {calcsem1();}
private void calcsem1() {
mark1calc=safeParse(mark1.getText().toString());
totalsem1=(6*mark1calc);
marksem1.setText(Double.toString(totalsem1));
marksem1.setText(String.format("%.2f", totalsem1));
}});
public void run1(View view){
Editor editor = sharedpreferences.edit();
String mark1string = mark1.getText().toString();
String marksem1string = marksem1.getText().toString();
editor.putString(Mark1, mark1string);
editor.putString(MarkSem1, marksem1string);
editor.commit();
}
}
And the same thing with the activity B, but using public static final String MyPREFERENCES = "MyPrefsB";
The result is that Activity A does de work fine, but activity B, when I exit the app and enter again, has the EditText empty (it has not save anything).
Any ideas about this? Thank you so much!

SharedPreferences Android - Saving and editing one string only using two activities

I have a single string which the user will edit and will be displayed back to him when he uses the app. He can edit the string at any time. I am familiar with SQLite databases, but because for this purpose I am using only one string/one record, I felt SharedPreferences would be better. However, after following two different tutorials, I am unable to get it so save the data. In both cases I have needed to amend the tutorial code because I will be using two activities, one to view the code, the other to edit it. I was unable to find a tutorial for using sharedpreferences for two activities. Below is the code.
Class to view the code:
public class MissionOverviewActivity extends Activity {
TextView textSavedMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_view);
textSavedMem1 = (TextView)findViewById(R.id.textSavedMem1);
LoadPreferences();
textSavedMem1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
return;
}});
};
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
textSavedMem1.setText(strSavedMem1);
}
}
Class to edit the code and return to the view page
public class MissionDetailActivity extends Activity {
EditText editText1;
Button buttonSaveMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_edit);
editText1 = (EditText)findViewById(R.id.editText1);
buttonSaveMem1 = (Button)findViewById(R.id.buttonSaveMem1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
viewStatement();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
protected void viewStatement() {
Intent i = new Intent(this, MissionOverviewActivity.class);
startActivity(i);
}
}
If any body could answer this question, or point me in the direction of a sharedpreferences tutorial that uses two classes (for edit and displaying), It would be greatly appreciated!
Thanks
getPreferences(int) is private for Activity, you want to share the same SharedPreference between activities you should use this way:
SharedPreferences prefs = this.getSharedPreferences(
"yourfilename", Context.MODE_PRIVATE);
and use the same method when you want to reload it. here the doc for getPrerences(int)

save the state when back button is pressed

I am developing an android app. If I press a back button the state of my application should be saved .What should i use to save the state ..am confused with all of these onPause(),onResume(), or onRestoresavedInstance() ??? which of these should i use to save the state of my application?? For eg when i press exit button my entire app should exit i have used finish() ?
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
s1=(Button)findViewById(R.id.sn1);
s1.setOnClickListener(this);
LoadPreferences();
s1.setEnabled(false);
}
public void SavePreferences()
{
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", s1.isEnabled());
}
public void LoadPreferences()
{
System.out.println("LoadPrefe");
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
s1.setEnabled(state);
}
#Override
public void onBackPressed()
{
System.out.println("backbutton");
SavePreferences();
super.onBackPressed();
}
What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}
you can use this way
public void onBackPressed() {
// Save settings here
};
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
save your application state in this method.

Categories

Resources