How to maintain CheckBox state across the activities
I checked a CheckBox in FirstActivity.java but when i move back to FirstActivity.java from any other activity, say from SecondActivity.java..
Then, I am not getting my CheckBox as check which i checked earlier.
Using onSaveInstanceState & onRestoreInstanceState, see complete code below:-
public class FirstActivity extends Activity {
CheckBox cb1;
Button btnNext;
private boolean boolCheck1 = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cb_cb1 = (CheckBox) findViewById(R.id.cb1);
btnNext = (Button) findViewById(R.id.btnNext);
// control status of body frame checkboxes
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
}
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("Enable", cb1.isChecked());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolCheck1 = savedInstanceState.getBoolean("Enable");
}
}
Your best option is to use sharedPreferences.
In your activity where the checkbox is located, in your onCreate() put the following:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Then, in your intent to go to another activity, or "save" button, or whatever you want, use the following:
editor.putBoolean("checkbox", yourCheckbox.isChecked());
editor.commit(); // commit changes
Now, the setting is saved.
When you come back to your activity, use this in your onCreate:
if (pref.getBoolean("checkbox", false) == true){ //false is default value
yourCheckbox.setChecked(true); //it was checked
} else{
yourCheckbox.setChecked(false); //it was NOT checked
}
You can read more here.
Hope this helped
Use SharedPreferences or SQLiteDatabase to store the value of check box and you can use it after fetching from Database or SharedPreference.
If you use onSaveInstanceState & onRestoreInstanceState all reference will clear when user close the app and the app is no longer in Memory.
Tutorial for SharedPreference
Tutorial for Database
To maintain state across activities you have to use SharedPreferences, or database. In your case SharedPreferences is the best option
You have used OnSavedInstance it will only save the instance until the activity is not destroyed i.e it stays on the stack.
Check activity lifecycle to understand more about when an activity is destroyed.
For each checkbox you can store its value in sharedPreference and on
onCreate() of you activity you should check the checkboxes according
to the sharedPreference values
Here is how you use shared prefs
SharedPreferences prefs= context.getSharedPreferences("myPrefs", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkbox1", true);//true if checked
editor.commit();
// get stored value , if no value is stored then assume its false
prefs.getBoolean("checkbox1", false);
Related
I implement dark mode with SwitchPreference in the second activity and in the first activity just a button take me to the second activity (Setting) the problem is when the app destroyed and i launched it again the dark mode not implemented until the second activity launched.
//First Activity
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences( this/* Activity context */);
Boolean theme = sharedPreferences.getBoolean("darkMode", false);
button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2=new Intent(MainActivity.this,Settings.class);
startActivity(intent2);
}
});
}
}
i have some idea that i should use sharedpreferences but i don't know how can i set it
//Second Activity
public class MySettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(#Nullable Bundle savedInstanceState, #Nullable String rootKey) {
setPreferencesFromResource(R.xml.preferences,rootKey);
SwitchPreference switchPreference=findPreference("darkMode");
if (switchPreference.isChecked()){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
Overview:-
You can change dark mode or light mode via this function.
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.HERE_YOUR_MODE);
You can access the mode like this:
AppCompatDelegate.MODE_NIGHT_YES // for dark mode
AppCompatDelegate.MODE_NIGHT_NO // for light mode
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM // for set as your devices theme
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM // when you are in battery saver
Implementation:-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Boolean theme = sharedPreferences.getBoolean("darkMode", false);
if (theme){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); // implement here.
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); // implement here.
}
}
Well as per your code , you are just one step away from achieving result
you just need to use below code in every activity's onCreate method
if (isDarkMode){ // isDarkMode is boolean which we can get from preference
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
```
The theme changes in current activity(Settings Activity), but I have to restart the other background activities to apply the new theme. I'm thinking that the background activities should be restarted in the settings activity, but I can't find how.
This is my Settings Activity:
public class SettingsActivity extends FragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SettingsHelper.onActivityCreateSetTheme(this);
getSupportFragmentManager()
.beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
protected void onResume() {
super.onResume();
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
prefs.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("theme")) {
boolean isDark = prefs.getBoolean("theme", false);
prefs.edit().putBoolean("theme", isDark).apply();
SettingsHelper.changeToTheme(this);
}
}
switch (cTheme)
{
case BLACK:
int myTheme = R.style.Default
activity.setTheme(myTheme);
//Save your activity theme color
saveTheme(myTheme);
break;
case YELLOW:
int myTheme = R.style.Green
activity.setTheme(myTheme);
//Save your activity theme color
saveTheme(myTheme);
break;
}
and change your onActivityCreateSetTheme(Activity activity) to:
public static void onActivityCreateSetTheme(Activity activity, Int cTheme)
Save method
public void saveTheme(int theme)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
prefEditor.putInt("Theme",theme);
}
Load method
public int loadTheme(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//Load theme color
int theme = sharedPreferences.getInt("Theme",Color.RED); //RED is default color, when nothing is saved yet
return theme;
}
Important: call loadTheme() before setContentView() so your onCreate() should be like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int theme = loadTheme(); //Load your theme here!!!!
CustomazationProcess.onActivityCreateSetTheme(this, theme);
setContentView(R.layout.something1);
findViewById(R.id.black).setOnClickListener(this);
findViewById(R.id.yellow).setOnClickListener(this);
}
The answer was indeed to recreate the activity but only after checking that the value got onCreate is different from the one onResume.
Link to a related SO question: Refresh(recreate) the activities in back stack when change locale at run time
#Override
protected void onCreate() {
super.onCreate()
preferences = PreferenceManager.getDefaultSharedPreferences(this);
isDark = preferences.getBoolean("theme", false);
}
#Override
protected void onResume() {
super.onResume();
if(isDark != preferences.getBoolean("theme", false))
recreate();
}
There is nothing called restart activity while it is in background and still keep it in background.
you can simply finish this activity so next start will be using the new theme.
or if your theme can be manually applied then you can apply the new theme at it's onResume (or onStart, depending on your logic).
You can also recreate the activity at onResume (if theme changed) but I don't recommend this as this resume will be unnecessary and you can simply use first option.
In all of your activities, try to put below code in onResume() method:
#Override
public void onResume(){
super.onResume();
boolean isDark = prefs.getBoolean("theme", false);
if(!isDark){
recreate();
}
}
recreate() needs to be invoked to recreate the activity so that the new theme can be applied on the current screen.
I am trying to save my programmatically created CardView and TextView using OnSaveInstanceState and OnRestoreInstanceState as in the sample code.
While debugging, I notice that values are saved but when I quit the app and reopen it, nothing is being restored.
What am I doing wrong?
**#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("key", userInput.getText().toString());
savedInstanceState.putInt("LayoutId", mConstraintLayout.getId());
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getString("key");
savedInstanceState.getInt("LayoutId");
}**
This are the methods I am using after 'OnCreate'
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
mConstraintLayout = findViewById(R.id.top_left);
addButton = findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View popup = findViewById(R.id.popup);
popup.setVisibility(View.VISIBLE);
}
});
mButton = (Button) findViewById(R.id.create);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CardView sticker = new CardView(mContext);
CardView.LayoutParams params = new CardView.LayoutParams(
CardView.LayoutParams.WRAP_CONTENT,
CardView.LayoutParams.WRAP_CONTENT
);
params.height=500;
params.width=500;
CheckBox privateCalendar = findViewById(R.id.checkPrivate);
CheckBox workCalendar = findViewById(R.id.checkWork);
CheckBox holidayCalendar = findViewById(R.id.checkHoliday);
if (privateCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#FFCC00"));
}
else if (workCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#FF8080"));
}
else if (holidayCalendar.isChecked()){
sticker.setCardBackgroundColor(Color.parseColor("#66B3FF"));
}
else{
sticker.setCardBackgroundColor(Color.parseColor("#FFCC00"));
}
sticker.setId(CardView.generateViewId());
sticker.getId();
sticker.setTag(CARD_VIEW_TAG);
sticker.setLayoutParams(params);
sticker.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence) sticker.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData data = new ClipData(sticker.getTag().toString(), mimeTypes, item);
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(sticker);
sticker.startDrag(data
, shadowBuilder
, sticker
, 0
);
sticker.setVisibility(View.INVISIBLE);
return true;
}
});
TextView tv = new TextView(mContext);
tv.setLayoutParams(params);
tv.setBackgroundColor(Color.TRANSPARENT);
tv.setGravity(Gravity.CENTER);
userInput = findViewById(R.id.editText);
tv.setText(userInput.getText());
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
tv.setTextColor(Color.BLACK);
sticker.addView(tv);
mConstraintLayout.addView(sticker);
View popup = findViewById(R.id.popup);
popup.setVisibility(View.GONE);
}
});
}
SavedInstanceState and RestoreInstanceState will work if activity is recreated due to config change like orientation change or android system killed that activity due to memory issue, Then only savedInstanceState and restoreInstanceState comes in role.
If you finish activity by yourself and start activity again then there is no use of these methods.
Try to save data in SharedPreference instead savedInstanceState.
SharedPreferences pref =
getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
For Storing data:-
editor.putString("key", userInput.getText().toString());
editor.putInt("LayoutId", mConstraintLayout.getId());
editor.apply();
For retriving data:-
editor.getString("key", null); // getting String
editor.getInt("LayoutId", 0); // getting Integer
First of all if by "close the app" you mean destroy it, this will never work for you.
Second of all in onRestoreInstanceState you don't do anything with those values, you simply read them but don't store them anywhere.
If you mean to recreate the old form after switching back and forth between apps, with your app being destroyed in the background then, you need to only set values in onSaveInstanceState like you did, and in onCreate(Bundle savedInstance), you should do something like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstance == null) {
//read values from getIntent()
key = getIntent().getString("key);
LayoutId = getIntent().getInt("LayoutId");
} else {
//read values from savedInstanceState
key = savedInstanceState.getString("key");
LayoutId = savedInstanceState.getInt("LayoutId");
}
}
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
The Preference class allows for an Intent to be set, to have a preference activate another activity when clicked, but I'm unable to find a way to handle the result from an activity using this method. There's also the DialogPreference where I can provide a custom view, but I don't have direct access to the view I want to use, only an activity.
Digging a bit further, it looks like the RingtonePreference uses a few package internal methods on PreferenceManager to receive results from a started sub-activity, but as these are package internal I am unable to do the same.
Is there any other way of handling a custom preference with an activity that returns a result (where the result is to be saved as the value of the preference)?
I have also noticed PreferenceActivity does not return onActivityResult. That being said, is there a reason your SubActivity couldn't save the preference directly? If you need to check the value of it, you could check it at onResume of your PreferenceActivity as a workaround..
//SubActivity onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.Button01);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences(TestPreferenceActivity.PREFS_FILE, MODE_WORLD_READABLE);
prefs.edit().putString("mykey", "someValue").commit();
finish();
}});
}
//PreferenceActivity onResume
#Override
protected void onResume() {
Log.d(TAG, "Preferences Resumed");
//Check for new Preference Values
SharedPreferences prefs = getSharedPreferences(PREFS_FILE, MODE_WORLD_READABLE);
String value = prefs.getString("mykey", "defValue");
Log.d(TAG, "Current value is: " + value);
super.onResume();
}