Hi I'm having trouble with sharedpreferences and saving the data of a int, I've tried everything but I can't figure it out.
Im using getExtra from two seperate activities to pull that data to the main activity and then adding those variables together to give me a total. Im trying to make it so that when leaving the main activity that all the variable stays the same and updates when the other two activites are changed.
this is the main activity with the sharedpreferences
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YearOneActivityButton();
YearTwoActivityButton();
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", MODE_PRIVATE);
scoreTotal = totalScorePref.getInt("TotalScoreY1", 0);
Intent totalGradeValueY1 = getIntent();
Intent totalGradeValueY2 = getIntent();
int year2Score = totalGradeValueY2.getIntExtra("totalYearValueY2", 0);
int year1Score = totalGradeValueY1.getIntExtra("totalYearValueY1", 0);
scoreTotal = year1Score + year2Score;
numberScore = (TextView)findViewById(R.id.number_score_txt);
numberScore.setText(String.valueOf(year1Score));
numberScore1 = (TextView)findViewById(R.id.number_score_1_txt);
numberScore1.setText(String.valueOf(year2Score));
totalGradeTxt = (TextView)findViewById(R.id.total_grade_txt);
totalGradeTxt.setText(String.valueOf(scoreTotal));
Log.d("SCORETOTAL", String.valueOf(scoreTotal));
}
#Override
public void onPause(){
int pTotalScore = scoreTotal;
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", 0);
SharedPreferences.Editor editor = totalScorePref.edit();
editor.putInt("TotalScoreY1", pTotalScore);
editor.commit();
super.onPause();
}
}
this is how im passing the data
public void SubmitMainActivity() {
ButtonSubmit = (Button) findViewById(R.id.button_submit);
ButtonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int totalGradeValueY1 = totalAllSpinnerValuesY1;
Intent year1ScoreIntent = new Intent(YearOneActivity.this, MainActivity.class);
year1ScoreIntent.putExtra("totalYearValueY1", totalGradeValueY1);
startActivity(year1ScoreIntent);
}
});
}
Hi please try like this
SharedPreferences topic = getSharedPreferences("topicfun", MODE_PRIVATE);
SharedPreferences.Editor topiccom = topic.edit();
topiccom.putInt("topicname",10);
topiccom.commit();
You can simply add below code after you calculate the totalGradeTxt:
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref",
MODE_PRIVATE);
SharedPreferences.Editor editor = totalScorePref
.edit()
.putInt("TotalScoreY1",pTotalScore)
.apply();
NOTE: I have used apply() instead of commit()
Related
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
Little problem in my learning.
Sorry for my frenchglish ^^
A variable changes every time, i press a button, it backs up and assigns it ++.
In the button input if the variable == in table REPONSE.Length, It restarts the activity and it REMOVE the backup.
My problem is that the backup does not remove itself while the activity restarts well.
Every time i support the activity it raises again without being able to start again at stage 0.
int REPONSE[]= new int[5]; //tableau des reponses
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Question = sharedPreferences.getInt("num", 0);
cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.apply();
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
}
//Sauvegarde de la variable
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("num", Question++);
editor.apply();
//Incrementation +1
Question++;
}
}); }
Thanks in advance:)
According to the documentation remove() removes a value once commit() is called. So you have to change editor.apply() to editor.commit()
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.commit(); //editor.apply() won't work
There are 3 points that I wold recommend you:
Point 1:
Try giving your Shared preference a name. Example:
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
If you are not giving a name to the shared preference android can fall into ambiguity and create a new Sharedpreference thus not affecting the old one.
Even you are creating a new SharedPreference inside the onClick method(this process is wrong), and there the android system is not being able to understand which Shared Preference to use thus not affecting the sharedpreference data that you want to change.
Point 2:
This not so important as the first one but to change the data of an already existing preference you need not to delete the preference instead just change the value, and it will be updated to your requirement:
sharedPreferences.edit().putInt("num", Question++).apply();
Point 3:
Create SharedPreference object once inside the class where it can
have global scope.
Initialize the SharedPreference only once in an activity inside
onCreate method.
Make your code something like this:
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
ConstraintLayout layout;
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
layout = findViewById(R.id.layout);
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
Question = sharedPreferences.getInt("num",0);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences.edit().putInt("num", Question++).apply();
}
});
}
}
I have an Activity in which I am trying to implement a kind of auto-login. In my login activity, I have this:
sharedPref = context.getSharedPreferences("data", Context.MODE_PRIVATE);
User.setUid(sharedPref.getInt("UID", 1));
Boolean al = sharedPref.getBoolean("AUTOLOGIN", false);
...
if (al) {
Log.i("AUTOLOGIN", "Go!");
Gui.createAlert(context, context.getString(R.string.loading));
Intent i = new Intent(context, CityActivity.class);
context.startActivity(i);
}
...
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
Ajax.AjaxListener callback = new Ajax.AjaxListener() {
int uid = Integer.parseInt(userInfo.optString("user_id", "1"));
String sid = user.optString("sid", "");
String k = json.optString("k", "");
Boolean al = autoLogin.isChecked();
SharedPreferences.Editor e = sharedPref.edit();
e.putInt("UID", uid).putBoolean("AUTOLOGIN", al).putString("SID", sid).apply();
Gui.createAlert(context, context.getString(R.string.loading));
Intent i = new Intent(context, CityActivity.class);
};
});
I've only been able to test this on the emulator, and I can't seem to get the SharedPreferences file contents to show in Android Device Monitor, but every time the app loads, it does the autologin routine. Even when I shut down the emulator completely and restart everything the autologin flag seems to persist. I'm pretty new to Java/Android programming, but coming from a PHP and JavaScript background, it's not hard to pick up. I'm just stumped as to why the AUTOLOGIN SharedPreference key always seems to return true when checked. Is there an example of implementing autologin with SharedPreferences?
I should note that I tried to use a database originally, but scrapped the idea because of difficulty of use and the minimal data required right now.
Try This Hope This Will Help You.
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login(View v){
SharedPreferences spf=getSharedPreferences("myprfs",Context.MODE_PRIVATE);
String name=spf.getString("uname", "no value");
String pass=spf.getString("pass", "no value");
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
if(et1.getText().toString().equalsIgnoreCase(name) && et2.getText().toString().equalsIgnoreCase(pass))
{
Intent i=new Intent();
i.setComponent(new ComponentName(getApplicationContext(), WelcomeActivity.class));
startActivity(i);
}
}
public void register(View v){
Intent i=new Intent();
i.setComponent(new ComponentName(getApplicationContext(), RegistrationActivity.class));
startActivity(i);
}
}
RegistrationActivity.java
public class RegistrationActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
}
public void register(View v){
EditText et1=(EditText)findViewById(R.id.editText1);
EditText et2=(EditText)findViewById(R.id.editText2);
EditText et3=(EditText)findViewById(R.id.editText3);
SharedPreferences spf=getSharedPreferences("myprfs", Context.MODE_PRIVATE);
SharedPreferences.Editor spe=spf.edit();
spe.putString("uname", et1.getText().toString());
spe.putString("pass", et2.getText().toString());
spe.putString("dob", et3.getText().toString());
spe.commit();
finish();
}
}
I'm trying use two SharedPreferences, the firt is Working, but the second isn't
here is my Java Code
public class JogoActivity extends AppCompatActivity implements View.OnClickListener {
//OTHERS VARIABLES
public TextView txtViewResult,txtCoins, txtTentativas;
private static final String PREF_NAME = "JogoActivityPreferences";
int resulFinalCache,coinsFinalCache;
int count1, count2 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
//methods...
//MY PROBLEMS START HERE
txtCoins = (TextView) findViewById(R.id.txtCoins);
txtViewResult = (TextView) findViewById(R.id.textViewResultado);
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count1 = sp1.getInt("count1", 0);
txtViewResult.setText(String.valueOf(formatter.format(count1).toString()));//THIS IS WORKING
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count2 = sp2.getInt("count2", 0);
txtCoins.setText(String.valueOf(formatter.format(count2).toString()));////THIS ISN'T
}
//Creating methods...
#Override
protected void onStop(){
super.onStop();
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
count2 = sp2.getInt("count2", 0);
editor = sp1.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
#Override
public void onDestroy() {
super.onDestroy();
SharedPreferences sp1= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
editor = sp2.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
}
every time I launch the app, I use, I close the app and open again, the TextView txtViewResult is working fine, but the txtCoins isn't
I Try use just getPreferences and not getSharedPreferences, but it isn't work too
I try create other Editor, but it isn't work too
Did i do something wrong?
Thank you very much!
No need to call getsharedpreferences twice.
Just call it one time and it should be working fine.
E.g your onstop would be
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
count2 = sp1.getInt("count2", 0);
editor.putInt("count2", coinsFinalCache);
editor.commit();
hmm. your solution is
SharedPreferences sp1_2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count1 = sp1_2.getInt("count1", 0);
SharedPreferences.Editor editor = sp1_2.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
count2 = sp1_2.getInt("count2", 0);
editor = sp1_2.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
//now both will work
infact bind the methods
Don't use the same name when getting them!
Instead of
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
Use two different names like so:
SharedPreferences sp1 = getSharedPreferences(PREF_NAME1, MODE_PRIVATE);
SharedPreferences sp2 = getSharedPreferences(PREF_NAME2, MODE_PRIVATE);
Also you don't need two different shared preferences. Just use one and put those 2 values with different keys.
Generally i can advise you to use simply
For saving:
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("name", 1).apply();
For reading:
PreferenceManager.getDefaultSharedPreferences(this).getInt("name", 0);
Enjoy!
I have a code... Its excellent save data and load data, but... When i reset application, my score loading, but when i click button for +5 score, my score reset and set 5. I am want that addition +5, but its dont work...
I understand that the problem of addition, because save and load working excellent, but addition doesnt work.
Sorry for my bad English :)
int mCounts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appli);
Settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
score = (TextView) findViewById(R.id.score);
score.setText(String.valueOf(mCounts));
}
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
}
public void onPause() {
super.onPause();
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Try this code in your button:
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Problem is here:
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
Remove int. it will work
I'm using Shared Preferences to save data from an AutoCompleteTextView.
When the user writes something in this AutoCompleteTextView, he can click a button in order to save what he just wrote (so that he doesn't have to write it every time).
Here's what my code looks like:
private AutoCompleteTextView autoComplete = null;
String nameFile = "Web service data";
String myData = "";
SharedPreferences pref;
Editor editor;
String channel = "";
String[] valuesArray = {channel};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, valuesArray);
autoComplete = (AutoCompleteTextView) findViewById(R.id.autocompletion);
autoComplete.setAdapter(adapter);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(sendForm2);
Button remove = (Button) findViewById(R.id.remove);
remove.setOnClickListener(sendForm2);
channel = pref.getString(nameFile, null);
}
OnClickListener sendForm2 = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
myData = autoComplete.getText().toString();
editor.putString(nameFile, myData);
editor.commit();
break;
case R.id.remove:
editor.remove(nameFile);
editor.commit();
break;
}
}
};
The problem is, the Shared Preferences doesn't save any data in channel at all. Even when I close the application and restart it.
Any clue or idea how to resolve this problem?
First thing I would try would be to add a
Log.d("OnCreate", "channel : "+ channel);
in the onCreate just after
channel = pref.getString(nameFile, null);
to see if you have something inside.
If you don't, this really means that sharedpref are not saved.
In this case I would try to bring back the :
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
just before the
switch (v.getId()) {
I remember reading that sometimes depending on what you are doing with your activities, the sharedpref editor you create can be "lost" and not be related to anything later in the code.
Use the following method to save and retrive String prefrence.
//save the prefrence by pasing key and data
public static void SavePrefrence(Context ctx, String Key, String value) {
ctx.getSharedPreferences("mypref", ctx.MODE_PRIVATE)
.edit().putString(Key, value).commit();
}
//get the prefrence by passing your key
public static String getPrefrence(Context ctx, String key) {
SharedPreferences pref = ctx.getSharedPreferences(
"mypref", ctx.MODE_PRIVATE);
String result = pref.getString(key, null);
return result;
}