sharedpreferences is not saving the text value - java

**
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);
}

Related

How can I get my sharedpreferences to work correctly?

I'm having trouble getting my sharedpreferences to work. I'm trying to load in data from a textbox in another activity into a textview. I don't get any errors, but it keeps returning the default value of "nameKey".
Here is where the data is being entered and saved
public class ActivitySettings extends AppCompatActivity {
SharedPreferences sharedPreferences;
final String MyPREFERENCES = "MyPrefs";
final String Name = "nameKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final EditText enterName1 = (EditText) findViewById(R.id.enterName1);
final EditText enterName2 = (EditText) findViewById(R.id.enterName2);
Button btnOK = (Button) findViewById(R.id.btnOK);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
btnOK.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String n = enterName1.getText().toString();
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Name, n);
editor.commit();
}
});
and here's a different activity where i'm trying to read in the data and set it to a textview
public class ActivityDuel extends AppCompatActivity {
public String getPrefs(String n, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString(n, "nameKey");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duel);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView txtD1 = (TextView) findViewById(R.id.txtD1);
txtD1.setText(getPrefs("name", this));
}
}
Call like this
txtD1.setText(getPrefs("nameKey", this));
And your getPrefs() function should like below
public String getPrefs(String n, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString(n, "");
}
I think it's better to create a class for handle your SharedPreferences and add your key as static string to it and use methods for insert and read. here an example:
SettingProvider.class
public class SettingProvider {
private static final String SETTING_PROVIDER_NAME = "setting";
public static final String NAME = "name"
private SharedPreferences sharedPreferences;
private static SettingProvider ourInstance;
private SharedPreferences sharedPreferences;
private SettingProvider(Context context) {
if (context == null)
throw new RuntimeException("context must be valid!");
this.sharedPreferences = context.getSharedPreferences(SETTING_PROVIDER_NAME, 0);
}
public static SettingProvider getInstance(Context context) {
if (ourInstance == null) {
ourInstance = new SettingProvider(context);
}
return ourInstance;
}
public void setName(String name) {
return this.sharedPreferences.edit().setString(NAME, name).apply();
}
public String getName() {
return this.sharedPreferences.getString(NAME, "");
}
}
now for use in activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duel);
SettingProvider.getInstance(this).setName("the name");
String name = SettingProvider.getInstance(this).getName();
}
I think the issue is that you are saving a shared preferences key of 'Name', so from the field final String Name = "nameKey"; the preferences key is 'nameKey'
Then when you try and get the string out you are using "name" as the lookup key value and as it doesn't exist it gets set to the default of 'nameKey' so I think you need to change this txtD1.setText(getPrefs("name", this)); to txtD1.setText(getPrefs(Name, this));

Need more detail about saving the arraylist

Related: Save ArrayList to SharedPreferences
I have an edit text to enter a value, a button to add it to an ArrayList and save, a button to retrieve and display the value, and a button to reset the ArrayList. But the button to collect constantly displays 2.
public class test extends AppCompatActivity {
ArrayList arrayList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button button = findViewById(R.id.create);
Button button1 = findViewById(R.id.recup);
Button button2 = findViewById(R.id.reset);
final EditText editText = findViewById(R.id.editText);
final TextView textView = findViewById(R.id.textView);
//Initialize ArrayList
loadData();
//Button for add variable in arraylist and save
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre = editText.getText().toString();
arrayList.add(nombre);
saveData();
}
});
//Button for look arrayList.get(0)
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(String.valueOf(arrayList.get(0)));
}
});
//Button for reset
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("task list");
editor.commit();
}
});
}
//save data
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString("task list", json);
editor.apply();
}
//load data
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList>() {
}.getType();
arrayList = gson.fromJson(json, type);
}
}

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 value of Int (Shared Preference)

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.

Categories

Resources