EDIT: After adding onPause() and onResume(), the app no longer crashes; however, the instance is still not saving, and I lose the text I put inside the EditText. I speculate that I'm supposed to save the instance using onPause(), onStop(), and recall it using onResume() (or maybe using this and onSaveInstanceState(), onRestoreInstanceState() together) - I'm reading up on how to use these three methods now, and I would appreciate any pointers.
I'm currently writing a simple Android App with only a four (maybe five) activities. The app's function is to provide help and advice to students in university, where they are required to add the courses themselves (which appear on the activity_main_page page as buttons) - when the button is pressed, it will take the student to the advice page.
What I'm currently working on is the course adding page: activity_add_course. I'm trying to add a way to save the state of the EditText's text (this is where the user adds the course name) when the activity is paused/stopped (for example when user presses the back button or home button), and to have it recalled when the user returns to the page.
The app worked fine (using dummy intents to connect activities - I havent added an SQL database to actually make the app work) before I tried adding instance state saving to the App. Now that I have added instance state saving and recalling, the app stops running when I click the back button and I have no idea why? or how to fix it? - This issue has been solved. Thanks #peresisUser
This is the code for the back button
btBk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent New = new Intent(AddCourse.this, MainPage.class);
startActivity(New);
}
});
}
And these are the codes I use for instance save and restore.
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//Save instance state
savedInstanceState.putString("edC1", edCourse1.getText()+"");
savedInstanceState.putString("edC2", edCourse2.getText()+"");
savedInstanceState.putString("edC3", edCourse3.getText()+"");
savedInstanceState.putString("edC4", edCourse4.getText()+"");
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//Restore instance state
String edC1 = savedInstanceState.getString("edC1");
edCourse1.setText(edC1+"");
String edC2 = savedInstanceState.getString("edC2");
edCourse2.setText(edC2+"");
String edC3 = savedInstanceState.getString("edC3");
edCourse3.setText(edC3+"");
String edC4 = savedInstanceState.getString("edC4");
edCourse4.setText(edC4+"");
}
edCourse1-4 are all different EditTexts.
From my understanding, the onSaveInstanceState() will save edC1 as the text from edCourse1.getText()+"" and so on, then the onRestoreInstanceState() will restore the String inside edC1 to edCourse1 and so on.
Having trouble on this, I have no idea how I would solve my next issue, which has to save the state of buttons on the page activity_main_page. Here I would have 10 buttons which start off as invisible and nameless, where activity_add_course will add a name to the button and make it visible. I speculate that the issue I will run into is: that all the buttons would become invisible when the app is restarted.
It looks to me that your should just add the super call in onPause() which is probably deleted in your code.
First row of the stack trace:
android.util.SuperNotCalledException: Activity {com.example.user.icecres/com.example.user.icecres.AddCourse} did not call through to super.onPause()
Let me know if that helped.
So I've figured out how to do all of this, next task: doing the same thing for buttons!
Feel free to add/edit anything appropriate to this answer.
This is my final source code:
package com.example.user.icecres;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
public class AddCourse extends AppCompatActivity {
private EditText edCourse1, edCourse2, edCourse3,edCourse4;
private Button btConfirm, btReset, btBk;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_add_course);
if(state != null){
//restore state onStop()
SharedPreferences pText = getSharedPreferences(PREFS_NAME,0);
String edC1 = pText.getString("edC1", "");
String edC2 = pText.getString("edC2", "");
String edC3 = pText.getString("edC3", "");
String edC4 = pText.getString("edC4", "");
edCourse1.setText(edC1);
edCourse2.setText(edC2);
edCourse3.setText(edC3);
edCourse4.setText(edC4);
} else {
btConfirm = (Button) findViewById(R.id.btConfirm);
btReset = (Button) findViewById(R.id.btReset);
edCourse1 = (EditText) findViewById(R.id.edCourse1);
edCourse2 = (EditText) findViewById(R.id.edCourse2);
edCourse3 = (EditText) findViewById(R.id.edCourse3);
edCourse4 = (EditText) findViewById(R.id.edCourse4);
btBk = (Button) findViewById(R.id.btBk);
}
btConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// add course to database
edCourse1.setText("");
edCourse2.setText("");
edCourse3.setText("");
edCourse4.setText("");
AlertDialog.Builder d = new AlertDialog.Builder(
AddCourse.this);
d.setTitle("Success");
d.setMessage("Courses have been added");
d.setPositiveButton("OK", null);
}
});
btReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder c = new AlertDialog.Builder(
AddCourse.this);
c.setTitle("Confirmation");
c.setMessage("Would you like to clear all fields?");
c.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
edCourse1.setText("");
edCourse2.setText("");
edCourse3.setText("");
edCourse4.setText("");
}
});
c.setNegativeButton("NO",null);
c.show();
}
});
btBk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent New = new Intent(AddCourse.this, MainPage.class);
startActivity(New);
}
});
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences pText = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = pText.edit();
edit.putString("edC1",edCourse1.getText()+"");
edit.putString("edC2",edCourse2.getText()+"");
edit.putString("edC3",edCourse3.getText()+"");
edit.putString("edC4",edCourse4.getText()+"");
edit.commit();
}
#Override
protected void onStop() {
super.onStop();
SharedPreferences pText = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = pText.edit();
edit.putString("edC1",edCourse1.getText()+"");
edit.putString("edC2",edCourse2.getText()+"");
edit.putString("edC3",edCourse3.getText()+"");
edit.putString("edC4",edCourse4.getText()+"");
edit.commit();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences pText = getSharedPreferences(PREFS_NAME,0);
String edC1 = pText.getString("edC1", "");
String edC2 = pText.getString("edC2", "");
String edC3 = pText.getString("edC3", "");
String edC4 = pText.getString("edC4", "");
edCourse1.setText(edC1);
edCourse2.setText(edC2);
edCourse3.setText(edC3);
edCourse4.setText(edC4);
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
//Save instance state
state.putString("edC1", edCourse1.getText()+"");
state.putString("edC2", edCourse2.getText()+"");
state.putString("edC3", edCourse3.getText()+"");
state.putString("edC4", edCourse4.getText()+"");
}
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
//Restore instance state on crash
String edC1 = state.getString("edC1","");
String edC2 = state.getString("edC2","");
String edC3 = state.getString("edC3","");
String edC4 = state.getString("edC4","");
edCourse2.setText(edC2+"");
edCourse3.setText(edC3+"");
edCourse1.setText(edC1+"");
edCourse4.setText(edC4+"");
}
}
So the onPause() and onStop() are used to save the text inside the EditText fields to the file initialized at the top. The onResume() is used to call the texts saved and apply them to the relevant EditText fields. The onSaveInstanceState() is used to save the state and onRestoreInstanceState() is used to restore the state on crash. The if else in the onCreate(), is used to determine if there was a previous state to be restored or not (by onStop), and the values are called/initialised depending on this condition.
Hope this helps someone with similar problems!
Related
This is the code for an Activity named as Interest Activity. It is a dashboard which consist of four interest/hobbies (gaming, singing, sports, and coding). The user is asked to choose one of the them and then he/she is redirected to the particular activity. I used Cardview to represent the interest they behave like a button. This is the code:
package com.example.meetup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class InterestActivity extends AppCompatActivity {
CardView cardGame;
CardView cardSports;
CardView cardSing;
CardView cardCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interest);
cardGame = findViewById(R.id.cardGame);
cardCode = findViewById(R.id.cardCode);
cardSing = findViewById(R.id.cardSing);
cardSports = findViewById(R.id.cardSports);
cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Gaming", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
cardSports.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Sports", Toast.LENGTH_SHORT).show();
}
});
cardSing.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Singing", Toast.LENGTH_SHORT).show();
}
});
cardCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Coding", Toast.LENGTH_SHORT).show();
}
});
}
}
Now the problem is that whenever I am reopening the app, it takes me to the interest activity again even though I chose an interest once. Then I got to know about shared preference as how it stores the user data and intent accordingly.
I saw many tutorials on YouTube as to how could I use it, but they all were taking something as input like text. But in my case I’m not taking any input just pushing a button. How do I use a shared preference in my case? Can you give a shared preference code for if the user chooses gaming?
Define some constants to manage saved selected interest
public class InterestActivity extends AppCompatActivity {
// Define a string key for SharedPreference value
private static final String SP_INTEREST = "interest"
// Define integer codes for each interest
private static final int INTEREST_NONE = 0
private static final int INTEREST_GAME = 1
private static final int INTEREST_SPORTS = 2
private static final int INTEREST_SING = 3
private static final int INTEREST_CODE = 4
SharedPreferences sp;
SharedPreferences.Editor editor;
CardView cardGame;
CardView cardSports;
CardView cardSing;
CardView cardCode;
// Rest of the code
}
Then for saving the choosen interest, repeat it for each on click:
cardGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(InterestActivity.this, "Gaming", Toast.LENGTH_SHORT).show();
// Here first save the choosen interest
editor.putInt(SP_INTEREST, INTEREST_GAME);
editor.apply();
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
And when you restart the app, in on create method check the saved interest code and start the corresponding activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get and init SharedPreferences and editor
SharedPreferences sp = getSharedPreferences(getPackageName(), MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// INTEREST_NONE is the default value if there no registry.
int savedInterest = sp.getInt(SP_INTEREST, INTEREST_NONE);
if(INTEREST_GAME == savedInterest) {
// Start game activity using intent
Intent intent = new Intent(InterestActivity.this,GameActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
else if(INTEREST_SPORTS == savedInterest) {
// Start sports activity using intent
}
else if(INTEREST_SING == savedInterest) {
// Start sing activity using intent
}
else if(INTEREST_CODE == savedInterest) {
// Start code activity using intent
}
setContentView(R.layout.activity_interest);
// Rest of the onCreate codes
}
If you want to store what the user clicked the last time and do something about it, you can follow this to write/read from shared preferences: https://stackoverflow.com/a/3624358/7365491
Every time the user clicks on one of your CardViews you store a value of the last selected interest.
Every time the user opens the app in the onCreate, check if the preference exists and read the last stored value in it. With that then you can decide what you want to do when the app is opened and the user has previously selected a value.
In my MainActiviy class I want to display image views of smiley faces based on the number of clicks that occur on the buttons jokes, poems and funnystories combined. However my switch statement does not seem to working as no images appear. Also if any of those image views become visible, then they should remain visible even after the user closing the app and reopening it.
I also notice a click count increasing by one when the user opens the app which is not correct. It should increase based on the buttons mentioned previously being clicked.
public class MainActivity extends AppCompatActivity {
SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
ImageView yellowSmileyFace = findViewById(R.id.yellow_happy);
ImageView greenSmileyFace = findViewById(R.id.green_happy);
ImageView redSmileyFace = findViewById(R.id.red_happy);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("jokes");
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("poems");
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("funnystories");
}
});
TextView clickCountText = findViewById(R.id.click_count);
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
switch (prefManager.increaseClickCount()){
case 4 :
yellowSmileyFace.setVisibility(View.VISIBLE);
break;
case 8 :
greenSmileyFace.setVisibility(View.VISIBLE);
break;
case 12 :
redSmileyFace.setVisibility(View.VISIBLE);
break;
default :
yellowSmileyFace.setVisibility(View.INVISIBLE);
greenSmileyFace.setVisibility(View.INVISIBLE);
redsmileyFace.setVisibility(View.INVISIBLE);
}
}
private void openContentPage(String v) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intentContentPage.putExtra("keyPage", v);
startActivity(intentContentPage);
}
}
below is the Shared preferences class
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String NUMBER_OF_CLICKS = "numberOfClicks";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs = context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public int increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
return clickCount;
}
}
You need to add a getter for your clicks
public int getClicks(){
return sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
}
Whenever you want to get your clicks currently you are calling increaseClickCount() which causes your clicks to increment before returning them. That is why it gains clicks every time you open the stage and why your switch isn't working correctly
so add the above getter to your SharedPrefrenceManager and change these two lines
switch (prefManager.increaseClickCount()){
to
switch (prefManager.getClicks()){
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
to
clickCountText.setText(Integer.toString(prefManager.getClicks()));
Tell me if that fixes your problem
The reason for counts' increase is you use increaseClickCount() to receive click count.You have to create another method to receive current clickCount. Your switch statement works only when they equal to 4,8 or 12. Maybe you should use if instead.
I also notice a click count increasing by one when the user opens the app which is not correct
It looks to me like this line of code, in MainActivity.onCreate() method will pass a text String of count 1 to clickCountText.
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
Also, every time you call SharedPreferencesManager.increaseClickCount, you are assigning a value to clickCount, and whatever was there gets overwritten.
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
What is that value?
System.out.println is your friend.
I use this pattern
System.out.println("MyClass, MyMethod, MyVariable:" + myVariable);
I always include the class and method because it can be annoying trying to figure out where println are coming from if you leave several in for debugging purposes and want to get rid of them later.
My Goal:
So I need help putting a boolean primitives into a bundle and retrieving it from the bundle when there is a screen orientation change in Android. I am using that boolean value in a conditional statement that helps decide if 2 Button views (mTrueButton, mFalseButton) should be enabled or not. What i have so far is causing the app to shut down (aka crash) when there is a screen rotation. I think I am not retrieving or writing my boolean from my bundle or into my bundle correctly, and it is causing the app to crash.
How The App Should Works:
When a user touches the mTrueButton or mFalseButton button to answer a question, both buttons become disabled so the user is not allowed to answer again. I want those buttons to keep being disabled when the user answers and then rotates the screen.**
I know that when a user rotates their Android device, onDestroy() is called because runtime configuration changes take place, causing the app to be relaunched without having knowledge of it's previous state, (unless store my necessary data onto a bundle and pass it onto my onCreate method).
These are SOME global variables in my activity class
private int index = 0;
priavate Button mTrueButton,mFalseButton;
private static final String KEY_INDEX = "index";
private static final String BTTN_ENABLED = "bttnEnabled";
private boolean trueFalseButtonsEnabled = true;
These are SOME statements in my onCreate() method of the same activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if(savedInstanceState != null) {
index = savedInstanceState.getInt(KEY_INDEX, 0);
changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true));
}
mTrueButton = (Button)findViewById(R.id.true_button);
mFalseButton = (Button)findViewById(R.id.false_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkAnswer(true);
changeButtonEnableStatus(false);
}
});
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
changeButtonEnableStatus(false);
}
});
}
These are SOME methods in the same activity class but not in my onCreate()
private void changeButtonEnableStatus(boolean bool){
trueFalseButtonsEnabled = bool;
mTrueButton.setEnabled(bool);
mFalseButton.setEnabled(bool);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG,"onSavedInstanceState() called");
savedInstanceState.putInt(KEY_INDEX,index);
savedInstanceState.putBoolean(BTTN_ENABLED, trueFalseButtonsEnabled);
}
Note that:
index = savedInstanceState.getInt(KEY_INDEX, 0);
works properly. It is setting global variable "index" to equal to the int primitive what was stored in into keywork "KEY_INDEX".
However I don't think: changeButtonEnableStatus(savedInstanceState.getBoolean(BTTN_ENABLED,true)); is working properly. My app seems to crash when I include that statement and run the app, and then rotate the device.
I have a fragment with a button that sets a background theme for the whole app. I have set up an interface so the fragment can tell the main activity to set the background or remove it depending on what button the user clicks.
The problem is that every time the app is opened the background isn't saved and needs to be toggled again. I have seen that this can be solved with SharedPreferences but implementing it here is confusing me
In my fragment This presents two buttons that send the values 1 or 2 to the main activity to toggle the background
enable = (Button) rootView.findViewById(R.id.enable);
enable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
});
disable = (Button) rootView.findViewById(R.id.disable);
disable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.themechanged(1);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
});
In my Main Activity This takes the value from the listener and toggles the background depending on what the value is
#Override
public void themechanged(int value) {
if(value==2) {
if (isDarkTheme) {
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
} else {
appbackground.setVisibility(View.VISIBLE);
shade.setVisibility(View.VISIBLE);
}
}else if(value!=2||value==1){
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
}
}
Use SharedPrefence to store the value for theme like-:
Global Variable
SharedPreferences pref;
SharedPreferences.Editor editor;
In OnCreateView()
pref = getActivity().getSharedPreferences("Theme", Context.MODE_PRIVATE);
editor = pref.edit();
Now, store preferences on Button click
enable = (Button) rootView.findViewById(R.id.enable);
enable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("yourTheme", 2);
editor.commit();
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
});
disable = (Button) rootView.findViewById(R.id.disable);
disable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putInt("yourTheme", 1);
editor.commit();
listener.themechanged(1);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
});
and then, In OnCreate() of MainActivity you can check like
SharedPreferences pref = getSharedPreferences("Theme", MODE_PRIVATE);
value= pref.getInt("yourTheme", 1);//1 is default value
if(value==2) {
if (isDarkTheme) {
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
} else {
appbackground.setVisibility(View.VISIBLE);
shade.setVisibility(View.VISIBLE);
}
}else if(value==1){
appbackground.setVisibility(View.GONE);
shade.setVisibility(View.GONE);
}
Done, it may be helpful
In the onClick() you should do 2 things:
Sent the value to the listener (you're already doing this)
Save this value to the preferences (already posted how to do that here)
Then, in the onCreate() of your MainActivity you should check for that preference and do the same you are doing on themechanged(int)
Actually, you could use only one onClickListener(), this way:
// Not need to cast to `Button`, since all views can have an onClickListener
rootView.findViewById(R.id.enable).setOnClickListener(clickListener)
rootView.findViewById(R.id.enable).setOnClickListener(clickListener)
// Put this as a member of your Fragment class.
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.enable) {
// Save your preference here
// ...
listener.themechanged(2);
enable.setVisibility(View.GONE);
disable.setVisibility(View.VISIBLE);
}
if (v.getId() == R.id.R.id.disable) {
// Save your preference here
// ...
listener.themechanged(2);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
}
}
Let me share this more complex example which can cover this and future needs: https://gist.github.com/walterpalladino/4f5509cbc8fc3ecf1497f05e37675111
The PersistenceManager class is generic, all your app data should be included in the Settings class.
I hope it helps.
I have an app where I take the Name of the user in an editText and I have it storing to firebase but when I get out of the activity and go back into it, the editText field does not show the Name of the user anymore. I want their name to stay in the editText field.
also how would I do the same thing but for an image in an ImageView that the user puts in. Please help.
IDEA:
You can use shared preference. When user launches his application first task will be load his user name and password from shared preference.
By doing this you can also manage a session manager for better user experience.
For example: After every successful authentication you can store the basic information of the user that is needed to update the screen everytime.
Benefit:
This will help you to show old data on screen if user launches your app without internet enabled. You can check the internet and if disabled then simply show the old data from preference.
You Can do something like this
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
text.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
{
prefs.edit().putString("autoSave", s.toString()).commit();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
//At here you can call some method to get the text from shared preferences and display it on EDitText
}
or You can save into DB at onTextChanged() method
Here is a little activity example which saves the username into SharedPreferences at stop of activity and restores the value to the EditText when activity is (re)started:
public class Test extends Activity {
EditText edtUser;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
edtUser = (EditText) findViewById(R.id.editTextUser);
edtUser.setText(preferences.getString("username", ""));
}
#Override
protected void onStop() {
super.onStop();
preferences.edit().putString("username", edtUser.getText().toString()).commit();
}
}
Set on click listener to edit text.
Inside on click enable edit text and write to firebase using setValue.
Set on click to parent layout or check is focus changed of edit text. Inside read from firebase using add value event listener.
In Oncreate disable edit text and read from firebase using add value event listener.
This will auto save and retrieve edit text data seamlessly.
In OnCreate create method of activity
//Initialize edittext
mEditText = (EditText) findViewById(R.id.edittext);
// Disable mEditText
mEditText.setEnabled(false);
//Read from firebase and set text to mEditText if mTextEdit is not in focus
if (!mEditText.isFocused()){
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String editTextData = (String) dataSnapshot.getValue();
mEditText.setText(editTextData);
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
}
// Set onclick listener to mEditText
mEditText.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mEditText.setEnabled(true);
editTextData = mEditText.getText().toString();
mFirebaseRef.setValue(editTextData);
}
});
This works for me and UI looks simple without any extra buttons to switch between edit and save.
Hope I understood your requirement correctly. Thanks