Save value of Int (Shared Preference) - java

I'm new to java. I've made a counter which goes up as user holds on a button. I want the app to start with int value of where it left. I know SharedPreference is the way to go but I've no idea how to use it. I'm not sure where to put which part of SharedPreference. Thank you.
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
}

Add the following function to your activity
public int getValue(String key) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int value = sharedPref.getInt(key, 0);
return value;
}
public void saveValue(String key, int value) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
Some code added in your onCreate() method
final String key = "somekey";
count = getValue(key); //get value from sharedPreference
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
text.setText(String.valueOf(count)); // set it first
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
saveValue(key,count);
text.setText(String.valueOf(count));
return false;
}
});

You can do it like this,save count in SharedPreference when destroy the activity and read value from SharedPreference when you create it:
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
SharedPreferences sh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
sh = getSharedPreferences("sh_name", MODE_PRIVATE);
count = sh.getInt("count", 1);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
sh.edit().putInt("count", count).apply();
}
}

Try turning
int count = 1;
into
static int count = 1;
I'm also somewhat a Java noobie so this may or may not work.

Related

sharedpreferences is not saving the text value

**
I am trying to save the text variable using Sharedpreferences. I saved the variable by this code. But when I click the button the saved variable will go back to 0. I want to start counting from the saved value. please help me
**int counter = 0;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
counterView=findViewById(R.id.counterid);
Btn=findViewById(R.id.button1);
Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}
}
Considering the informations you've provided I think you needed to give the counter the value stored in SharedPreferences, to continue the count from that, when the button was pressed again.
Try this:
int counter = 0;
Button adBtn;
TextView counterView;
public static final String SHARED_PREF="shared";
public static final String TEXT="text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counterView=findViewById(R.id.counterid);
adBtn=findViewById(R.id.button1);
adBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences counterSp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String correctCounterValue = counterSp.getString(TEXT,"");
counter = Integer.valueOf(correctCounterValue);
counter++;
counterView.setText(Integer.toString(counter));
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(TEXT,counterView.getText().toString());
editor.commit();
}
});
SharedPreferences sp = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
String tValue = sp.getString(TEXT,"");
counterView.setText(tValue);
}

App crashes when using Shared Preferences

Im making a simple app, which counts the clicks of a button and saves the integer with a Shared Preferences. I tried it with the following code, but the app crashes all the time, if I try to open "Singleplayer"
public class Singleplayer extends AppCompatActivity {
private int sp1;
private int record;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singleplayer);
final Button button1 = (Button) findViewById(R.id.buttonspieler1);
final TextView lbl1 = (TextView)findViewById(R.id.lblspieler1);
final TextView lbl2 = (TextView)findViewById(R.id.lblrekord);
SharedPreferences data_record = getSharedPreferences("savegame", 0);
record = data_record.getInt("myKey1", 0);
lbl2.setText(String.valueOf(record));
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
}
});
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
}
you are using sharedPrefrence in your onStop() so you will face many issue here, i suggest to use it at the end of click method
button1.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
if(sp1< record) {
sp1++;
lbl1.setText(String.valueOf(sp1));
}
else if(sp1>= record)
{
sp1++;
record++;
lbl1.setText(String.valueOf(sp1));
lbl2.setText(String.valueOf(record));
}
SharedPreferences data_record = getSharedPreferences("savegame", 0);
SharedPreferences.Editor editor = data_record.edit();
editor.putString("myKey1", String.valueOf(record));
editor.commit();
}
});
so why the app crash, because the sharedPref dosen't carry any value it's null
please check this

Error : Cannot Assign a Value to Final Variable

I'm new to android development and I'm trying to learn SharedPreferences.
How do I manipulate the value of X using buttons and then save it to SharedPreferences again using a button.
I have to declare SharedPreferences after OnCreate, but if I declare X after
OnCreate I have to set it Final so I can use it in my onClickListener, because it's inner class, but if I do then I'd get a complier error that reads:
"Error:(42, 17) error: cannot assign a value to final variable x"
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final Editor editor = pref.edit();
int x = pref.getInt("Value", 0);
final TextView txt = (TextView) findViewById(R.id.textView);
final Button ButtonAdd = (Button) findViewById(R.id.buttonPlus);
final Button ButtonMinus = (Button) findViewById(R.id.buttonMinus);
final Button ButtonCommit = (Button) findViewById(R.id.buttonCommit);
final EditText EditText = (EditText) findViewById(R.id.editText);
txt.setText(Integer.toString(x));
ButtonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x = x + 1;
EditText.setText(Integer.toString(x));
}
});
ButtonMinus.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(x != 0){
x=x-1;}
EditText.setText(Integer.toString(x));
}
});
ButtonCommit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
txt.setText(Integer.toString(x));
editor.putInt("Value", x);
}
});
}
}
public class MainActivity extends AppCompatActivity {
private int x; //declare here
Now in your onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final Editor editor = pref.edit();
x = pref.getInt("Value", 0); //assign values to global variable
//rest of the code
}
See this for different Types of variables and Their usage
declare x as a member field of your Actvity and it will be accessible in your inner class

android - saving int with sharedPreferences

In my new app a counter increases when the button is clicked. I want to save the highscore with sharedPreferences, so the score is saved and shown the next time the app is started. The problem is that I don't really get it working, even with other answered questions.
package com.example.test;
public class MainActivity extends ActionBarActivity {
public int score = 0;
public int highscore = 0;
TextView tvscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvhighscore= (TextView) findViewById(R.id.highscore);
tvscore = (TextView) findViewById(R.id.score);
Button count = (Button) findViewById(R.id.button1);
tvhighscore.setText(String.valueOf(highscore));
SharedPreferences prefs = this.getSharedPreferences("score", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("score", 0);
editor.commit();
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int highscore = prefs.getInt("score", 0);
}
}
First of all you need to use the same key for the shared preferences when writing and querying. Then also in onclick you need to store the score in the prefs and not query it again. Here's the updated code:
public class MainActivity extends ActionBarActivity {
public int score = 0;
public int highscore;
TextView tvscore, tvhighscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvhighscore= (TextView) findViewById(R.id.highscore);
tvscore = (TextView) findViewById(R.id.score);
Button count = (Button) findViewById(R.id.button1);
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
highscore = prefs.getInt("high_score", 0);
tvhighscore.setText(String.valueOf(highscore));
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
if (score > highscore) {
highscore = score;
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
prefs.edit().putInt("high_score", highscore).apply();
tvhighscore.setText(String.valueOf(highscore));
}
}
}
You have some errors in your code
First error is that you are using different names for SP
SharedPreferences are accessed via an unique key. in your code you have two of them: myPrefsKey and myPrefsKey. Be sure of using always the same or the value will not be found.
The second is that you are using two times the same int name
Both in code and in onclick method you are casting an int with the same name highscore. This is not allowed
The third is in logics:
What you are doing is:
Saving value on activity start.
Reading value on button click
While you should do the following:
Read the value in onCreate method using the getInt code you are using inside the button click and setting the textview's text with it.
Save the value on button click after incrementing it.
This way you will have the code working.
Below an example:
package com.example.test;
public class MainActivity extends ActionBarActivity {
public int score = 0;
public int highscore = 0;
TextView tvscore;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvhighscore= (TextView) findViewById(R.id.highscore);
tvscore = (TextView) findViewById(R.id.score);
Button count = (Button) findViewById(R.id.button1);
//here you retrieve the value of the highscore
prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int highscore = prefs.getInt("score", 0);
tvhighscore.setText(String.valueOf(highscore));
}
public void onClick (View view) {
score++;
//here you save the value of the score in your pref
tvscore.setText(String.valueOf(score));
Editor editor = prefs.edit();
editor.putInt("score", score);
editor.commit();
}
}
Dunno if this is exactly what you were looking for, but this should help you understanding the logics :)
Good luck!
I recommend that you create a class to manage your sp.
I leave you an example below.
public class SharedPrefsManager {
private static final String USER_CODE = "userCode";
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor prefEditor;
private static void setPreferences(Context context) {
if (context == null) {
context = Application.getContext();
}
sharedPreferences = context.getSharedPreferences("APP_NAME", 0);
}
public static int getCodigoUsuario(Context context) {
setPreferences(context);
return sharedPreferences.getString(USER_CODE, 0);
}
public static void setCodigoUsuario(int userCode, Context context) {
setPreferences(context);
prefEditor = sharedPreferences.edit();
prefEditor.putInt(USER_CODE, userCode);
prefEditor.commit();
}
}
SAVE: SharedPrefsManager.setCodigoUsuario(13, context);
GET SharedPrefsManager.getCodigoUsuario(context);

Save ints in SharedPreferences

I'm new to programming and I need to save more than 1 ints in SharedPreferences. I'm making a counter and I want to just save values of all ints in my code. How would I do that? If possible, can you modify my code with Shared Preferences.
Thanks
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int i=0;
int j=0;
int k=0;
TextView x= (TextView) findViewById(R.id.textView);
TextView y = (TextView) findViewById(R.id.textView2);
TextView z = (TextView) findViewById(R.id.textView3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a = (Button) findViewById(R.id.b1);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i++;
x.setText(String.valueOf(i));
}
});
Button b = (Button) findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
j++;
y.setText(String.valueOf(j));
}
});
Button c = (Button) findViewById(R.id.b3);
c.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
k++;
z.setText(String.valueOf(k));
}
});
}
}
This should do the trick.
private static void setInt(Context context, String name, int i) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(name, i);
editor.apply();
}
private static int getInt(Context context, String name, int default) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getInt(name, default);
}
#DroidGalaxy In SharedPreferences you can save at a time one value. In order to use shared preferences , you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.
Here instance pointing means it can retrieve last value that can save in this.
For example-
if you can store in your int varaiable = 10, then in next time you get value int varaiable = 10 .
but in next time -
If you change int varaiable = 10 TO int varaiable = 20 then it can return int varaiable = 20.

Categories

Resources