How to save Button Text with SharedPreferances set by EditText - java

I set the Button Text trough editText and a long Button Click. Afterwards the editText is set to an emptyString again. How do i save the Button name in SharedPreferances (as a String i guess) and read it when i restart the app?
package com.example.myapplication;
import ...
public class MainActivity<button1> extends AppCompatActivity {
Button button
EditText editText1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button3);
button.setOnClickListener(v -> opensecondone());
button.setOnLongClickListener(v -> naming());
editText1 = (EditText) findViewById(R.id.tv_textView);
}
public boolean naming() {
button = this.findViewById(R.id.button3);
button.setText(editText1.getText().toString());
editText1.setText(" ");
return true;
}
public void opensecondone() {
Intent intent = new Intent(this, firmaeins.class);
startActivity(intent);
}
}

first you store your name in naming function
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("yourMessageKey", message);
editor.commit();
then you get the value inside your oncreate of activity :
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String message = sharedPref.getString("yourMessageKey", "");

Related

how to save EditText's value after performing an other activity

i have my first activity with two EditText fields with hint's as first name and last name, when ever i go to my second activity and return to my first activity by a widget button the EditText fields in my first activity gets reset.
SIMPLY i want my EditText fields to remain same in my first activity as i re-visit my first activity from my second activity.
MY MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButton1Click(View v)
{
Intent intent = new Intent (this,MainActivity2.class);
startActivity(intent);
}
}
My MainActivity2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
SOLUTION - i changed my second activity to this. just added reference to my Button and applied an onClickListener with onBackPressed(); code.
setContentView(R.layout.activity_main2);
Button button = (Button)findViewById(R.id.button3); //gave reference of button in second activity
button.setOnClickListener(new View.OnClickListener() { //and applied an onClickListener with code onBackpressed();
public void onClick(View v) {
onBackPressed();
// Code here executes on main thread after user presses button
}
});
}
Really Really thnx to #Narendra Sorathiya for his guidance.
Open secondActivity like below,
Intent i = new Intent(A.this,B.class);
startActivity(i);
finish();
to
Intent i = new Intent(A.this,B.class);
startActivityForResult(i,1);
do not open 1st Activity from 2nd Activity, just need to back press.
try this
declare all variavle at top of activity
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String FNAME = "fname";
public static final String LNAME = "lname";
SharedPreferences sharedpreferences;
write this code when you move to your next activity
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// store login data in sharedpreferences
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(FNAME, edittext.getText());
editor.putString(LNAME, edittext2.getText());
editor.commit(); //save data in sharedpreferences
write this code in your oncreate method after you bind your controls
and get data from sharedprefrence like this
String fname= prefs.getString(FNAME, "");
String fname= prefs.getString(LNAME, "");
than set it to your editext like this
editext.setText(fname);
editext2.setText(lname);
let me know in case of any query

Use shared preferences in checkbox to make checked for always when button is clicked

I am using shared preferences to make the ckeckbox checked for always when button is clicked. But I'm getting errors, unknown type 'getChecked'. , code is givenbellow:
#Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = this.getSharedPreferences("pref", 0);
boolean checkedSearch = sharedPreferences.getBoolean("checkedSearch", false);
Button button = (Button) dialog.findViewById(R.id.button);
final CheckBox checkBox1 = (CheckBox) dialog.findViewById(R.id.checkBox1);
checkBox1.setChecked(checkedSearch ? true : false );
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(
checkBox1.getChecked()==false){
checkBox1.setChecked(true);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("checkedSearch",true)
.commit();
}
final SharedPreferences sharedPreferences=this.getSharedPreferences("pref", 0);
you have missed = sign

Check which one of two buttons has been pressed and pass a value to sharedpreferences

I have an activity with two buttons. Both buttons bring you to the next activity and at the same time a value is being given to sharedpreferences. I want to access this value in my very last activity.
How do I check which of the two buttons has been pressed?
What is the problem in my code? I always get the same value in the end. So it seems like I always press the same button, which I don't.
Here the first activity where the two buttons are in:
public void imagebutton (){
ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name2", "Geschlecht");
editor.clear();
editor.apply();
startActivity(new Intent(Akt1.this, Akt2.class));
}
});
}
//buttonclick mit datapass gemixt
private void imagebutton1 () {
ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name","Geschlecht");
editor.commit();
Intent intent = new Intent (Akt1.this,Akt2.class);
startActivity(intent);
And here the code from the last activity where I want to access the value that has been passed to sharedpreferences from the buttonclick:
public class Akt6 extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Hiermit Layout mit Activity verbinden
setContentView(R.layout.activity_akt6);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name",null);
name ="Männlich";
SharedPreferences preferences2 = PreferenceManager.getDefaultSharedPreferences(this);
String name2 = preferences.getString("Name", "default");
name2 ="Weiblich";
//zeige Wert on screen
TextView textView19 = (TextView) findViewById(R.id.textView19);
textView19.setText(name);
You are getting the same value because of this:
String name = preferences.getString("Name", null);
...
String name2 = preferences.getString("Name", "default");
You're using the same key "Name". You stored the values with the keys "name" and "name2".
So if you want to get those values you need to write something like this:
String name = preferences.getString("name", null);
...
String name2 = preferences.getString("name2", "default");
Also you are storing always the same value "Geschlecht":
editor.putString("name2", "Geschlecht");
editor.putString("name","Geschlecht");
I'm not sure what are you doing on your activity, but if you need to know wich button has been pressed you can do the follow:
To your button listeners add this:
public void imagebutton (){
...
editor.putString("name2", "Geschlecht");
editor.putString("ButtonPressed","Button1"); // This is the new line
...
}
...
public void imagebutton1 (){
...
editor.putString("name2", "Geschlecht");
editor.putString("ButtonPressed","Button2"); // This is the new line
...
}
Then, to get the value of the button pressed in your activity do this:
...
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String button = preferences.getString("ButtonPressed","");
if(!button.isEmpty()){
switch(button){
case "Button":
//You have pressed the first button
break;
case "Button2":
//You have pressed the second button
break;
}
}
You should use constants for every String passed as sharedpref name and value to avoid human mistakes on your code.
Good luck!
What is the problem in my code? I always get the same value in the
end. So it seems like I always press the same button, which I don't.
1. In your method imagebutton1(), you are storing value for name into different sharedPreferences (myprefs):
// Akt1
SharedPreferences preferences = getSharedPreferences("myprefs", MODE_PRIVATE);
and trying to get value of name from default sharedPreferences:
// Akt6
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
2. You have used KEY name to store value:
// Akt1
editor.putString("name","Geschlecht");
and getting value by using different KEY Name which is totally wrong.
// Akt6
String name = preferences.getString("Name", null);
How do I check which of the two buttons has been pressed?
SOLUTION:
Use same SharedPreferences to store and retrieve value.
Use same KEY "name" to store and retrieve value for name from SharedPreferences
Update your code as below:
Akt1.java
public void imageButton (){
ImageButton btn = (ImageButton) findViewById(R.id.imageButton3);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name", "Male");
editor.commit();
startActivity(new Intent(Akt1.this, Akt2.class));
}
});
}
private void imageButton1 () {
ImageButton btn = (ImageButton) findViewById(R.id.imageButton4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(Akt1.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("name", "Female");
editor.commit();
startActivity(new Intent(Akt1.this, Akt2.class));
}
});
}
Akt6.java
public class Akt6 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akt6);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("name", "default");
TextView textView19 = (TextView) findViewById(R.id.textView19);
textView19.setText(name);
}
}
Hope this will help~

Shared preferences in Android doesn't save when i switch activity or close app

I checked similar questionsions and noting seems to work. I can't figure out what seems to be the problem. Value goes to 0 after every app restart or activity switch.
//just parts of code from activity1
SharedPreferences pref;
SharedPreferences.Editor editor;
// On create....
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = pref.edit();
max=pref.getInt("mxtime", 0);
//If something>something...
editor.putInt("mxtime", max);
editor.commit();
In the first part i declare SharedPreferences in main Activity. I save it in "max" int and its always 0 on startup since if empty value is 0. On second activity I have a button, where on click it should empty the value from SharedPreferences.
Activity 2:
public class settings extends AppCompatActivity {
private Button myButton;
private Button myButton2;
private Button myButton3;
//sharedPrefs
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
editor = pref.edit();
myButton = (Button) findViewById(R.id.button3);
myButton2 = (Button) findViewById(R.id.button4);
myButton3 = (Button) findViewById(R.id.button5);
myButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
myButton2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
//sharedPrefs
editor.remove("mxtime");
editor.commit();
}
});
}
}
Try to use SharedPreferences like this:
SharedPreferences preferences = getApplicationContext().getSharedPreferences("loginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Activity 1:
SharedPreferences sp = getSharedPreferences("YourSharedPreference", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
int DEFAULT_VALUE = 0;
editor.putInt("VARIABLE_KEY", DEFAULT_VALUE);
//If something > something..
int VALUE_TO_PASS = <your value here>;
editor.putInt("VARIABLE_KEY", VALUE_TO_PASS);
// Before screen shift
editor.commit();
...........................................
Activity 2:
SharedPreferences sp = getSharedPreferences("YourSharedPreference", Activity.MODE_PRIVATE);
int DEFAULT_FALLBACK_VALUE = 0; //When value is not received, show this
int VALUE_PASSED = sp.getInt("VARIABLE_KEY", DEFAULT_FALLBACK_VALUE);
// On button click:
int DEFAULT_VALUE = 0;
editor.putInt("VARIABLE_KEY", DEFAULT_VALUE);
editor.commit();

Reload SharedPreferences

I'm quite new to Android Prorgramming and have a problem understandig SharedPreferences.
I have a Main Activity and a Settings Activity.
I want to be able to change a SharedPreference (here called firstWaitTime) in the Settings Activity and work with it in the Main Activity.
I can Set the new value in the settings, but in the Main Activity i only see the new value when i close and reopen the app.
I Think i would need a OnPrefrenceChanged Listender but i have no idea how to implement it...
The Main one looks like this:
public class MainActivity extends ActionBarActivity {
//Radio Button
private int stufe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
int firstWaitTime = settings.getInt("firstWaitTime", 12);
int secondWaitTime = settings.getInt("secondWaitTime", 8);
int thirdWaitTime = settings.getInt("thirdWaitTime", 6);
//TEST
final TextView test = (TextView) findViewById(R.id.test);
test.setText("" + firstWaitTime);
}
The Settings Activity looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE);
//BUTTON
final EditText edit1 = (EditText) findViewById(R.id.edit1);
Button save=(Button) findViewById(R.id.savebtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//prefs = getSharedPreferences(prefName, MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
SharedPreferences.Editor editor = settings.edit();
//---save the values in the EditText view to preferences---
editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString()));
//---saves the values---
editor.commit();
Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
}
What is the best way to achieve this?
onCreate() will not be called as Android hasn't killed the Activity. Try putting your code in onResume() instead. For more info read up on the Android Activity lifecycle.

Categories