How to save the state of a button in AndroidStudio? - java

I am new at programing in Java and I am taking a course of Android application. I am building a button inside an activity. But when I exit the activity, the button changes to it's original state. I know I am not doing anything to save its state, but how do I do it?
Here is the xml file (only the button part):
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Catch"
android:id="#+id/button"
android:onClick="toggleCatch" />
And here is toggleCatch:
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
}
What could I do to make it work?

you should store the data that indicate on it state in some place:
1. SQLlite
2. Server
3. SharedPreference
and then when you create the activity you set the state of the btn based on the data you loaded.
if you do it just for practice, I believe that the sharepreference will be just fine.
https://developer.android.com/training/data-storage/shared-preferences
to store any data locally in the sharedPreference:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", trueOrFalse);
editor.commit();
to get the saved data:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean stateBtn = sharedPref.getBoolean("SOME_NAME_FOR_YOUR_VARIABLE_EX_BTN_STATE", defaultValueForExTrue);
sharedPref.getBoolean can be used also for sharedPref.getString, sharedPref.getInt Etc..
hope that helped..
My recommendation for you is to read about the subjects above.(SQLlite, SharedPreference)

You need to save button state in persistent storage; there are several types of persistent storage that Android supports, like SharedPreference, DataBase, internal/external storage File... The most appropriate for your question is the SharedPreference as it stores small data.
To achieve that in your code sample
public static final String PREFS_NAME = "PREFS_NAME";
public static final String BUTTON_STATUS = "status";
private boolean isCaught = false;
#SuppressLint("SetTextI18n")
public void toggleCatch(View view) {
Button button = findViewById(R.id.button);
if (isCaught) {
button.setText("Catch");
isCaught = false;
} else {
button.setText("Release");
isCaught = true;
}
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(BUTTON_STATUS, isCaught);
editor.apply();
}
And you need to retrieve the value again from the shared preference when the app is launched, so in your activity onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
isCaught = prefs.getBoolean(BUTTON_STATUS, false);
if (isCaught) {
button.setText("Release");
} else {
button.setText("Catch");
}
}

Related

How do you save checkbox state in shared preferences after save data button is clicked

I have set up shared preferences to store the values of an ArrayList after a save data button is clicked within my app. This part is working fine.
The trouble I am having is that I have a recyclerview adapter which populates a recyclerview with rows. Each row contains a check box which turns the text in that row green when checked to indicate it has been completed.
My question is how can I add the checkbox state to my shared preferences and save that state so when I re-open the app the checkbox is saved.
Save button in oncreate in main activity
//Functionality for save button
final Button saveButton =findViewById(R.id.saveButtonGame);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveData();
}
});
Here is my code for my shared preferences in Main Activity (outside oncreate) to save arraylist. How can I implement my checkbox state into this?
//Save data when save button is clicked
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(gameList);
editor.putString("game list", json);
editor.apply();
}
//Load data on app start up
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("game list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
gameList = gson.fromJson(json, type);
if(gameList == null){
gameList = new ArrayList<>();
}
}
You could create three integers for "On" and "Off" states and one to hold the switch value either on or off. This is how I did mine.
int reminderState;
int REMINDER_ON = 1;
int REMINDER_OFF = 0;
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
reminderState = REMINDER_ON;
} else {
reminderState = REMINDER_OFF;
}
}
});
So in your saveData() method, you store the reminderSate value in your shared preferences.
And in loadData() you check if the reminderState is on or off then set your switch according to the switch state.

How to get Preferences in Android?

I don't understand how preferences work.
I have a preferences activity and one field on it:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<EditTextPreference
android:key = "#string/pr_rest_service_url"
android:title = "#string/rest_service_url"
android:summary = "%s"
android:shouldDisableView="false"
android:selectable="true"
android:enabled="true"
android:defaultValue="543543543"
/>
</PreferenceScreen>
In preference activity i use this code to edit it:
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
String editTextPrefKey = getString(R.string.pr_rest_service_url);
EditTextPreference restUrlTExtEdit = (EditTextPreference) findPreference(editTextPrefKey);
restUrlTExtEdit.getEditText().setInputType(InputType.TYPE_CLASS_TEXT);
restUrlTExtEdit.setSummary(restUrlTExtEdit.getText());
restUrlTExtEdit.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
Preference saveButton = findPreference(getString(R.string.preference_save_button));
saveButton.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
finish();
return true;
}
});
}
}
And its works. Works nice.
Now i want to get preferense from another parts of application. I put this code in MainActivity:
String key = this.getString(R.string.pr_rest_service_url);
SharedPreferences mSharedPreferences = getSharedPreferences(key, Context.MODE_PRIVATE);
String g = mSharedPreferences.getString(key, null);
And got null.
So how gonna work with preferences?
Or i made mistake on ths start and should not use PreferenceActivity as settings screen? Or preferenses binded to activity?
So how can i get
UPDATE
I tried
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String name = sp.getString("myKey", "");
But got empty string.
Update: Use this then:
SharedPreferences yourOutputdata =
context.getSharedPreferences("YourKEY", MODE_PRIVATE); // Save as YourKEY in the Activity which you're passing data to this one ...
Because of this:
String key = this.getString(R.string.pr_rest_service_url);
You are actually getting string from resource file and saving it to preference which I believe this causes the null.
Try this:
To save:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("key","your text-data here");
editor.apply();
And to get:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("key", "");
🚩Get Android Shared Preferences from default shared preferences in java language:-
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
sharedPreferences.getString("your_key", null);
Hope this works...😊

SharedPreferences not working/saving data from EditText field

I am using shared preferences but my code is not working. I don't know what's wrong with it. Am I implementing something wrong?
My main java activity(relevant bit of code) is:
public class MainActivity extends AppCompatActivity {
private String s;
public static final String subjectKey = "SubjectID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences sharedPreferences = getSharedPreferences(subjectKey, Context.MODE_PRIVATE);
TextView calc_monday = (TextView) findViewById(R.id.monday_calc);
calc_monday.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.show();
TextView text1 = (TextView) cdd.findViewById(R.id.Subject_ID);
String text = sharedPreferences.getString(subjectKey, " ");
if(text != " ")
{
text1.setText(text); /* Edit the value here*/
}
TextView text2 = (TextView) cdd.findViewById(R.id.Room_ID);
text2.setText("6 (SEECS)");
TextView text3 = (TextView) cdd.findViewById(R.id.Time_ID);
text3.setText("09:00am - 09:50am");
}
}
);
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
SDC.show();
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
return true;
}
}
);
Basically I want that when I longClick a textbox (calc_monday), a dialog box should appear which appears. Now I should be able to write something on the EditText field which appears on this dialog box. Whatever I write should be stored and then displayed when I SINGLE CLICK on the same textbox (calc_monday)
Please see the 2 methods: onClick and onLongClick to understand.
The code is not working, i.e the text I write on EditText field on onLongCLick dialog box is not being displayed when I single click on the textbox.
What's wrong with the code
When you long press calc_monday, it just show your custom dialog with empty value for EditText. To save your text when input in EditText, create a button in your custom dialog, and call onClickListener action for this button, then save value to SharePreferences.
calc_monday.setOnLongClickListener(
new Button.OnLongClickListener() {
public boolean onLongClick(View v) {
SettingDialogClass SDC = new SettingDialogClass(MainActivity.this);
EditText texii = (EditText) SDC.findViewById(R.id.set_Subject_ID);
Button btnSave = (Button)SDC.findViewById(R.id.your_custom_button);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(subjectKey, texii.getText().toString());
editor.apply();
SDC.dismiss();
}
});
SDC.show();
return true;
}
}
);
I think it's should be :
String text = sharedPreferences.getString("Name", " ");
Try these methods for saving and loading Strings with preferences:
//save prefs
public void savePrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
//get prefs
public String loadPrefs(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String data = sharedPreferences.getString(key, value);
return data;
}
You can call the load method like this:
subjectKey = loadPrefs("YouCanNameThisAnything", subjectKey);
And you can call the save method like this:
savePrefs("YouCanNameThisAnything", subjectKey);
More details on how to use shared preferences is also available in the documentation here:
http://developer.android.com/reference/android/content/SharedPreferences.html
//create and initialize the intance of shared preference
SharedPreferences sharedPreferences = getSharedPreferences("Session", MODE_PRIVATE);
//save a string
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(subjectKey , texii.getText().toString());
edit.commit();
//retrieve the string
String subject = sharedPreferences.getString(subjectKey, "");

Load strings from sharedpreferences in EditText (two classes)

I have two different activity's. First one only showed to the user first time - to store phonenumber inside sharedprefs. I think the problem is my load from prefs method but just in case I will leave everything here to make it more relevant to future users. It looks like in both activitys the "mobilnummer" is saved - but I am having problem to display them.
The idea is it to be overwritten if user updates it - I think the method will do that?
OnStartUp.java
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
final Button button = (Button) findViewById(R.id.ntonboarding);}
public void SaveToMobile(View v) {
if (mobilnummer.getText().toString().length() >= 8) {
FragmentedUser.SaveMobile(mobilnummer.getText().toString()); // just saves to Parse.com (This works)
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
}
}
Profile
EditText mobilnummer;
public static final String PREFS_NAME = "MobileNumberSaved";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mobilnummer = (EditText) findViewById(R.id.mobilnummer);
This is the issue/problem i think! (Code below)
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
String tempMobilnummer = mobilnummer.getText().toString();
mobilnummer.setText(tempMobilnummer);
// IF user wants to change mobilenumber
mobilnummer.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
if (mobilnummer.getText().toString().length() >= 8)
FragmentedUser.SaveMobile(mobilnummer.getText().toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("mobilnummer", mobilnummer.toString());
editor.commit();
tlfstatus.setImageResource(R.drawable.ok);
handled = true;
}
return handled;
}
});
I think here is your error:
SharedPreferences MobileNumberSaved = this.getSharedPreferences("mobilnummer", Context.MODE_PRIVATE);
//here it should be MobileNumberSaved instead of mobilnummer, because tehre is no sense to set the same text to the textView again after you got it from there
String tempMobilnummer = MobileNumberSaved.getText().toString();
mobilnummer.setText(tempMobilnummer);
But the correct way to get a value from shared preferences is something like this:
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String savedMobileNumber = prefs.getString("mobilnummer", "");
mobilnummer.setText(savedMobileNumber);
Update: when you save the value in the shared preferences, you save only the editText, not it's value, so do something like this when saving:
SharedPreferences.Editor editor = settings.edit();
//mobilnumber is your EditText, so get it's text like this
editor.putString("mobilnummer", mobilnummer.getText().toString());
editor.commit();
And everything else is still the same that I wrote above

Using SharedPreferences between Activity

I have a configuration page which has a form on it. When the button is pressed, I want to save that value to a SharedPreference. This SharedPreference value then needs to be accessed from elsewhere in my app.
I am trying to save the value like the below. I want to save the collectionID so I can use it elsewhere
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
Button mButton;
EditText mEdit;
String collectionID;
String key = "GregKey";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
SharedPreferences settings =
getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, collectionID);
editor.commit();
}
});
}
}
Once it has been saved, I then need to access it in another class, however I can't figure out how to do this. The example above crashes the application at the moment so something isn't quite right
I want to save the collectionID so I can use it elsewhere
Use mButton Button onClick event for saving EditText text in SharedPreferences as :
mButton.setOnClickListener( new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
// save value here in SharedPreferences
SharedPreferences settings =
ConfigPage.this.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, collectionID);
editor.commit();
}
});
Your crash occurs because your value is null:
String savedID;
You need to add a value to the variable:
String savedID = "somevalue";
Also, your key is null as long as the Button is not pressed which will also lead to a crash.
The putString(String key, String value) method enables you to store a specific value with a specific key, that can later be used to reaccess the stored value.
Example:
String key = "somekey";
String value = "yourvaluetostore";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value); // store the value
editor.commit();
In another Activity:
String key = "somekey";
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
// get the value "" is default
String value = sharedPreferences.getString(key, "");
All you need in the other Activity is the key you stored the value with. With this key, you can pull the correct stored value out of the SharedPreferences. --> The key is needed to identify the value.
Since you are using the part of code :
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(collectionID, savedID);
editor.commit();
Log.d("Saved as", savedID);
in the onCreate method, that translates to
...
editor.putString(null, null);
Log.d("Saved as", null);
Correct your code so that you fill those elements before. I guess you wanted to make the save in the OnClick part
Yes something its not quite right here because as i see you are saving nothing. on shared pref you should have a "key" which will be use to identify the saved value in your example it should be something like this
public class ConfigPage extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public static final String COLLECTIONID_KEY = "COLLECTIONID_KEY";
Button mButton;
EditText mEdit;
String collectionID;
String savedID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
getActionBar().hide();
mButton = (Button)findViewById(R.id.setCollection);
mEdit = (EditText)findViewById(R.id.collectionName);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
collectionID = mEdit.getText().toString();
Log.d("EditText", collectionID);
}
});
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(COLLECTIONID_KEY, collectionID);
editor.commit();
Log.d("Saved as", COLLECTIONID_KEY);
}
}
then to retrieve it :
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
String mySavedCollectionID = sharedPreferences.getString(COLLECTIONID_KEY);
and make sure that its done on the Onclick event otherwise you might end up with crash again because after the on-click event in your code the lines below will run anyway and save null!

Categories

Resources