Save ints in SharedPreferences - java

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.

Related

How to create EditText & Button so that EditText should take new input whenever button is pressed storing prev value?

What i did exactly is that user provides input in the EditText and it gets stored in the arrray and later when the button is pressed it clears the field
and now i incremented "number" but when i click button it always takes the previous value of "number". How can i send my incremented value of "number" in OnCreate?
so that whenever i click the button it should take incremented value of "number".
Thanks in Advance!
I tried using for loop it goes endlessly i.e it crashes.pls, help.
public class thirdactivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
final int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0);
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*created an Array to store the value
*/
int DLPoints[] = new int[number];
/**
*taking inptut from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
int userDLPV = Integer.parseInt(editText1.getText().toString());
DLPoints[number] = userDLPV;
editText1.setText("");
number++
}
}
public class thirdactivity extends AppCompatActivity {
ArrayList<Integer> userInput = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thirdactivity);
Intent intent1 = getIntent();
int no = intent1.getIntExtra(MainActivity.EXTRA_NUMBER4, 0) + 1;
Button Next = (Button)findViewById(R.id.button2);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(no);
}
});
}
public void validate(int number){
/**
*taking input from user and store in userDLPV
*/
EditText editText1 = (EditText) findViewById(R.id.points);
editText1.setText("" + number);
userInput.add(number);
}
}

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.

android how to program a stopwatch with SharedPreference

I'm programming a stopwatch in android sdk but I want to keep going even when I press back. I understand the activity lifecycle to some extent and I should overrive the onPause and onResume methods but have no idea how to go with that since SharePreference editor can't take in a Chronometer object
package com.example.taekwondobuddy.util;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.LinearLayout;
public class Time extends Activity {
Chronometer mChronometer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
mChronometer = new Chronometer(this);
layout.addView(mChronometer);
Button startButton = new Button(this);
startButton.setText("Start");
startButton.setOnClickListener(mStartListener);
layout.addView(startButton);
Button stopButton = new Button(this);
stopButton.setText("Stop");
stopButton.setOnClickListener(mStopListener);
layout.addView(stopButton);
Button resetButton = new Button(this);
resetButton.setText("Reset");
resetButton.setOnClickListener(mResetListener);
layout.addView(resetButton);
setContentView(layout);
}
View.OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.start();
}
};
View.OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
}
any tips or advice? Help is appreciated!
// try this
public class Time extends Activity {
Chronometer mChronometer;
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
sharedPreferences = getSharedPreferences(getString(R.string.app_name), MODE_PRIVATE);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
mChronometer = new Chronometer(this);
layout.addView(mChronometer);
Button startButton = new Button(this);
startButton.setText("Start");
startButton.setOnClickListener(mStartListener);
layout.addView(startButton);
Button stopButton = new Button(this);
stopButton.setText("Stop");
stopButton.setOnClickListener(mStopListener);
layout.addView(stopButton);
Button resetButton = new Button(this);
resetButton.setText("Reset");
resetButton.setOnClickListener(mResetListener);
layout.addView(resetButton);
setContentView(layout);
}
private void showElapsedTime() {
long elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase();
Toast.makeText(MyActivity.this, "Elapsed milliseconds: " + elapsedMillis,
Toast.LENGTH_SHORT).show();
}
View.OnClickListener mStartListener = new View.OnClickListener() {
public void onClick(View v) {
int stoppedMilliseconds = 0;
String chronoText = mChronometer.getText().toString();
String array[] = chronoText.split(":");
if (array.length == 2) {
stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000
+ Integer.parseInt(array[1]) * 1000;
} else if (array.length == 3) {
stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 * 1000
+ Integer.parseInt(array[1]) * 60 * 1000
+ Integer.parseInt(array[2]) * 1000;
}
mChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
mChronometer.start();
}
};
View.OnClickListener mStopListener = new View.OnClickListener() {
public void onClick(View v) {
mChronometer.stop();
}
};
View.OnClickListener mResetListener = new View.OnClickListener() {
public void onClick(View v) {
mChronometer.setBase(SystemClock.elapsedRealtime());
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
prepareSharedData();
}
#Override
protected void onResume() {
super.onResume();
mChronometer.setText(sharedPreferences.getString("time", "00:00"));
}
#Override
protected void onPause() {
super.onPause();
prepareSharedData();
}
public void prepareSharedData(){
String chronoText = mChronometer.getText().toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("time", chronoText);
editor.commit();
}
}
If you want to continue your countdown where you left it off than you need shared preferences other wise if you want to keep going stop watch even when user press back button you don't need Shared-Preference, shared-preference used to store primitive and string data types, You can use AsyncTask or Service to perform this operation,Still if you are using Chronometer you can not store Chronometer itself in shared preferences instead its values returned by elapsedRealtime() or from other methods of Chronometer
In AsyncTask or Service you can keep polling elapsedRealtime() , AsyncTask keep alive untill its doInBackground method finishes,even if you press back button AsyncTask keep alive

Categories

Resources