I have a simple scenario but can't seem to wrap my head around it.
I want to save a incremented value as a int to SharedPreferences every time a user tap on a item, let me show what I have:
int counter = 0;
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
SharedPreferences shareOpenClose = getSharedPreferences("Counter", Context.MODE_PRIVATE);
SharedPreferences.Editor editorOpenClose = shareOpenClose.edit();
editorOpenClose.putInt("count", counter);
editorOpenClose.apply();
SharedPreferences getCount = getSharedPreferences("Counter", Context.MODE_PRIVATE);
int getCountAmmount = getCount.getInt("count", 0);
if (getCountAmmount>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
So, when I close the activity and open it again the counter will be reset to zero and the first save to SharedPreferences back to 0. If I keep the activity open and test this it work and I get the toast as expected.
Can someone please point out what I'm doing wrong?
Because you never set the counter back when the activity loads. try this:
int counter = 0;
onCreate(...){
SharedPreferences countPref = getSharedPreferences("Counter", Context.MODE_PRIVATE);
counter = countPref.getInt("count", 0);
}
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
SharedPreferences countPref = getSharedPreferences("Counter", Context.MODE_PRIVATE);
SharedPreferences.Editor editorOpenClose = countPref.edit();
editorOpenClose.putInt("count", counter);
editorOpenClose.apply();
if (counter>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
Make the following changes in your code
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences shareOpenClose = getSharedPreferences("Counter", Context.MODE_PRIVATE);
final SharedPreferences.Editor editorOpenClose = shareOpenClose.edit();
final int[] counter = {0};
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter[0]++;
editorOpenClose.putInt("count", counter[0]);
editorOpenClose.apply();
SharedPreferences getCount = getSharedPreferences("Counter", Context.MODE_PRIVATE);
int getCountAmmount = getCount.getInt("count", 0);
if (getCountAmmount>3){
Toast.makeText(c, "success!", Toast.LENGTH_SHORT).show();
}
}
});
}
I hope this will help you, Happy Coding
Related
I want to save the number value so that when close the app it continues to be saved and when open it the progress is maintained. I don't know why SharedPreferences don't work.
I have tried in many ways but either the app forces it to close or it just doesn't work
number = numero
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView contador;
int numero = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("valor", numero);
int data = mPrefs.getInt("valor", numero);
contador = findViewById(R.id.contador);
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor data = data.edit();
data.putInt("tag", numero).commit();
}
};
You should use the same sharedPreferences for retrieving the values.
also, get the values by the same key you saved them. below is an example you can follow.
SharedPreferences mPrefs = getSharedPreferences("valor",
Context.MODE_PRIVATE);
try{
int data = mPrefs.getInt("tag", numero);
}
catch(NullPointerException e){
e.printStackTrace()
}
public void onClick(View v) {
numero++;
contador.setText(String.valueOf(numero));
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt("tag", numero).commit();
}
};
I'm building an app to check prime numbers and display them. the user need to be able to save the number and load it upon restart of the app.
I have problem when retrieving the saved int from Sharedprefrences. the codes saves the int and loads it on the "loaddata" function. But when I start checking if the saved in is a primenumber, the code jumps 2 primenumbers. Eg if I save "11", the next primenumber should be "13" but it jumps to "19".
Would be great if someone could point into the right direction since i'm a bit of newbie.
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
private Button applyPrimeButton;
private Button saveButton;
private Button loadButton;
public static final String SHARED_PREFS = "sharedPrefs";
int max = 500;
int j = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
editText = (EditText) findViewById(R.id.edittext);
applyPrimeButton = (Button) findViewById(R.id.apply_prime_button);
saveButton = (Button) findViewById(R.id.save_button);
loadButton = (Button) findViewById(R.id.load_button);
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = j; i <= max; i++) {
if (isPrimeNumber(i)) {
textView.setText(i+"");
j = i+1;
break;
}
}
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
loadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadData();
}
});
}
public boolean isPrimeNumber(int nummer) {
for (int i = 2; i <= nummer / 2; i++) {
if (nummer % i == 0) {
return false;
}
}
return true;
}
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int nummer = Integer.parseInt(textView.getText().toString());
editor.putInt("prime_save", nummer);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
textView.setText(String.valueOf(nummer));
}
}
Several issues:
You are not updating j to the correct value when loading data, and instead relying on what you are displaying in the textview.
To find prime number, it is enough to check until the square root of the original number and not half of it.
Try this:
applyPrimeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(j<max ){
if (isPrimeNumber(j)) {
textView.setText(j+"");
j++;
}
}
}
});
public void saveData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("prime_save", j);
editor.commit();
Toast.makeText(this, "Data saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sp = getSharedPreferences(SHARED_PREFS, Activity.MODE_PRIVATE);
int nummer = sp.getInt("prime_save",0);
j = nummer;
textView.setText(String.valueOf(nummer));
}
Am trying save boolean FAVOURITE data in sharedPreferences. when phone is rotated or closed .It is not working it is taking default value. I don't know whats wrong with this code. i am unable to figure out whats the problem is can someone show me the problem with the code
//Context context =this;
String FAVOURITE = "selected";
boolean favourite = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null){
favourite = savedInstanceState.getBoolean(FAVOURITE,false);
Toast.makeText(this,""+favourite,Toast.LENGTH_SHORT).show();
}
final Bundle queryBundle = new Bundle();
movieObject=(CardsClass)getIntent().getSerializableExtra("movieObject");
setTitle(movieObject.getmTitle());
setContentView(R.layout.activity_details);
final ImageView fav = (ImageView)findViewById(R.id.fav);
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (favourite == false) {
favourite = true;
fav.setImageResource(R.drawable.fav_on);
Toast.makeText(DetailsActivity.this, favourite + " is added to favourites", Toast.LENGTH_SHORT).show();
queryBundle.putBoolean(FAVOURITE,favourite);
}
else if(favourite){
favourite=false;
fav.setImageResource(R.drawable.fav_off);
queryBundle.putBoolean(FAVOURITE,favourite);
Toast.makeText(DetailsActivity.this, movieObject.getmTitle() + " is removed from favourites", Toast.LENGTH_SHORT).show();
}
}
});
Actually, you're doing the wrong thing. You should do something like:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(FAVOURITE, favorite); // then you can check the favorite value in onCreate as well.
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
this.favorite = savedInstanceState.getBoolean(FAVOURITE);
// do something here when restore.
super.onRestoreInstanceState(savedInstanceState);
}
To write or read in the SharedPreferences
Write:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean(FAVORITE, favorite);
editor.commit();
Read:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Boolean favorite = sharedPref.getBoolean(FAVORITE, true);
How to return seekBar value from Activity B to Activity A ?
seekBar=(SeekBar)findViewById(R.id.seekBarPercentage);
save.setOnClickListener(new View.OnClickListener() //return to previous activity {
#Override
public void onClick(View v) {
Intent returnIntent=new Intent();
Project=project.getSelectedItem().toString(); //spinner value
Description=description.getText().toString(); //editText value
// seekBar value ?
returnIntent.putExtra("Project",Project);
returnIntent.putExtra("Description",Description);
setResult(Activity.RESULT_OK,returnIntent);
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
progress = progresValue;
// Toast.makeText(getApplicationContext(), "Changing seekbar's progress", Toast.LENGTH_SHORT).show();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Toast.makeText(getApplicationContext(), "Started tracking seekbar", Toast.LENGTH_SHORT).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
progressText.setText("Covered: " + progress + "/" + seekBar.getMax());
// Toast.makeText(getApplicationContext(), "Stopped tracking seekbar", Toast.LENGTH_SHORT).show();
}
});
}
Additionally to #Anindya Dutta's Answer if you want to persist the data use SharedPreferences
Get SharedPreferences
SharedPreferences prefs = getDefaultSharedPreferences(context);
Read preferences:
String key = "test1_string_pref";
String default = "returned_if_not_defined";
String test1 = prefs.getString(key, default);
To edit and save preferences
SharedPreferences.Edtior editor = prefs.edit(); //Get SharedPref Editor
editor.putString(key, "My String");
editor.commit();
Shorter way to write
prefs.edit().putString(key, "Value").commit();
Additional info for SharedPreferences: JavaDoc and Android Developers Article
Keep the int progress outside the OnSeekBarChangeListener.
Retrieve current progress as progress = seekBar.getProgress().
Similar to returnIntent.putExtra("Description",Description);, put the progress in the Intent as an extra.
I have a tutorial in my app showing up when a user runs it for the first time
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (firstRun == true) {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
firstRun = false;
}
}
}, 200);
I have delayed it because without a delay i just get a black screen (the interface doesn't have the time to load)
But doing so i get the Tutorial.class opened many times, what am i doing wrong?
EDIT:
Here is some more code, i won't paste all of it since it would be only too long to read and it wouldn't be relevant to the problem
I save my preferences like this
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.putBoolean("FirstRun", firstRun);
editor.putString("Label1", label1S);
editor.putString("Label2", label2S);
editor.commit();
}
protected void onPause(){
super.onPause();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Counter1", counter);
editor.putInt("Counter2", counter2);
editor.commit();
}
Here is how i restore them inside the onCreate();
// Restore previous settings and data
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int counterRestored = settings.getInt("Counter1", 0);
int counter2Restored = settings.getInt("Counter2", 0);
boolean firstRunRestored = settings.getBoolean("FirstRun", true);
String label1Restored = settings.getString("Label1", "Counter 1");
String label2Restored = settings.getString("Label2", "Counter 2");
counter = counterRestored;
counter2 = counter2Restored;
firstRun = firstRunRestored;
label1S = label1Restored;
label2S = label2Restored;
renameLabel();
calculateTotal();
This is my second activity Tutorial.class
public class Tutorial extends MainActivity{
ImageButton btnSkip, btnSkip2, btnNext, btnNext2;
RelativeLayout tutorial, tutPage1, tutPage2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorial);
btnSkip = (ImageButton) findViewById(R.id.btn_skip);
btnNext = (ImageButton) findViewById(R.id.btn_next);
btnSkip2 = (ImageButton) findViewById(R.id.btn_skip2);
btnNext2 = (ImageButton) findViewById(R.id.btn_next2);
tutorial = (RelativeLayout) findViewById(R.id.tutorial);
tutPage1 = (RelativeLayout) findViewById(R.id.page1);
tutPage2 = (RelativeLayout) findViewById(R.id.page2);
btnSkip.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnSkip2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.GONE);
tutPage2.setVisibility(View.VISIBLE);
}
});
btnNext2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tutPage1.setVisibility(View.VISIBLE);
tutPage2.setVisibility(View.GONE);
tutorial.setVisibility(View.VISIBLE);
finish();
}
});
}
}
why don't you try
if(firstRun){
firstRun = false;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Intent tut = new Intent(MainActivity.this, Tutorial.class);
startActivity(tut);
}
}
}, 200);
}
The value of firstRun will not be stored persistantly over several runs.
You should store this value in SharedPreferences so that it will retain its value even after the app has been closed. You can find a tutorial on how to use SharedPreferences here.