I have got a DialogActivity with a "do not show anymore" CheckBox.
What I need it to do is exactly like the CheckBox says. When the CheckBox is checked the Activity doesn't have to be displayed to the user anymore, no matter if the app is restarted or killed.
public class PopUpInfoActivity extends Activity {
static final String PREFS = "preference_file";
#Override
public void onCreate(Bundle state) {
setContentView(R.layout.popupinfo_layout);
CheckBox chk = (CheckBox) findViewById(R.id.dontshow_checkbox);
chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false));
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//store isChecked to Preferences
SharedPreferences settings = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", false);
PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).apply();
}
});
Intent intent = new Intent(PopUpInfoActivity.this, ChordsListActivity.class);
if (!chk.isChecked()) {
// run activity
super.onCreate(state);
} else {
startActivity(intent);
}
}
}
If I do it like this the App crashes.
If I replace the else with:
else {
onStop()
}
The code doesn't work as expected.
I would really appreciate if you could help me fix this problem!
EDIT:
This is what I have got in my ChordsListActivity, which is the activity that calls the PopUpInfoActivity but I do not get what I should put in my if() statement.
Intent legendaIntent = new Intent(ChordsListActivity.this, PopUpInfoActivity.class);
if(/*what's here?*/)
startActivity(legendaIntent);
In that MainActivity read your preference key (Show_Dialog), if it is true then launch PopUpInfoActivity otherwise launch ChordsListActivity.
The logic should be in the Mother Activity
In your PopUpInfoActivity you should only edit the preference key to false if the user checks out the ChekBox
To do so, please create a preferences.xml file under res/xml, inside this file you have to create a key (Boolean) that you will store inside the status of PopUpInfoActivity.Checkbox, the default will be (True).
here is an example
<CheckBoxPreference
android:key="Show_Dialog"
android:defaultValue="true" />
From your MainActivity you should read this value like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Boolean showDlg = sharedPref.getBoolean("Show_Dialog", true);
if the showDlg is true then you popup your dialog, otherwise continue what you want to do.
of course you need to change the value of Show_Dialog if the user checks the checkbox, you can do it like this:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor preferencesEditor = sharedPref.edit();
preferencesEditor.putBoolean("Show_Dialog", false);
preferencesEditor.commit();
in this way, you can be sure that your main activity will read the Show_Dialog as false next time the user launches your application
Good luck
Firstly, super.onCreate() must be the first call in any Activity's onCreate().
Secondly, store the value of the SharedPrefence in a boolean instead of directly setting the CheckBox, and use that before setContentView() to finish your current Activity and launch the next one if true. If not, carry on with the UI stuff and anything else you need.
Related
So my question is how I can get the state of a Switch.
I have this Code:
notificationSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(notificationSwitch.isChecked()){
System.out.println("Checked");
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("value", true);
editor.apply();
notificationSwitch.setChecked(true);
}else{
System.out.println("not checked");
SharedPreferences.Editor editor = getSharedPreferences("save", MODE_PRIVATE).edit();
editor.putBoolean("value", false);
editor.apply();
notificationSwitch.setChecked(false);
}
}
});
The state of the switch is saved in the Shared Preferences and if I start the app the Switch is on the same state as when I left the app. But when I start the app is should print checked or not checked but it doesn't print out anything
I will answer based on the title:
To get the state of the switch in onCreate():
//in onCreate:
SharedPreferences prefrences = getSharedPreferences("save", MODE_PRIVATE);
//false mean if not found set to false as default
boolean stateSwitch = prefrences.getBoolean("value",false);
//set state for switch
notificationSwitch.setChecked(stateSwitch);
//log the state
if(stateSwitch == true){
Log.d("TAG","checked");
}else{
Log.d("TAG","not checked");
}
UPDATE
keep your onclicklistener the same, and add the code I provided before your onclicklistener in onCreate:
1) when you turn switch on and leave activity and come back it must stay on.
2) when you turn switch off and leave activity and come back it must stay off.
3) if you do nothing leave activity and come back it must stay off.
I am working on one application in which i move from Activity A(Main Activity) to Activity B to Activity C.
All of this is working fine but the problem occurs when user killed the app by removing it from Task tray.
To understand my problem say user moved from A to B and then C but before finishing the task in activity C user killed the app.
so when user again opens the app by pressing App icon i want to start the last activity C where user was when he killed the app instead of android default behavior of starting(Main Activity A) a fresh instance of app again.
What i have tried:
1) I tried using "onSaveInstanceState" and "onRestoreInstanceState", but i think they are used when orientation is changed or we go back by pressing back button.
2) I tried to save everything in "onPause" as onpause calls 99.99% times when activity destroyed and by using static flags i opens the last activity and it worked for me but i want some good example or technique to this work.
so can anyone help me on achieving the same..??
I request fellow members to provide code examples.
thanks in advance.
Store the state in every Activity's #onPause().
So in every Activity you want:
#Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = getSharedPreferences("RESTART", MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("last_left", getClass().getName());
editor.commit();
}
And a Shell Activity which will be a Launcher, Main Activity:
public class Shell extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Class<?> classActivity;
try {
SharedPreferences prefs = getSharedPreferences("RESTART", MODE_PRIVATE);
classActivity = Class.forName(prefs.getString("last_left", getClass.getName()));
}
catch(ClassNotFoundException ex) {
classActivity = your_Activity1.class;
}
startActivity(new Intent(this, classActivity));
}
}
[Source Modified]
you can use SharedPreferences to store last user state.#onPause activity
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("state", "A/B/C");
editor.commit();
OnResume Activity
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String stateApp = prefs.getString("state", null);
if (stateApp != null) {
switc(stateApp){
case 'A':
// Go TO A activity
break;
case 'B':
// Go TO B activity
break;
default:
// Go TO C activity
break;
}
}
The Intent that was used to launch the activity is saved by the system when the process is about to be killed.Once the user returns into the app which has been killed, then the app is restored and the same Intent (Activity A in your case) is fired to launch the activity including all the extras that it might have.
Go for SharedPrefrences:https://developer.android.com/reference/android/content/SharedPreferences.html
refer the official documentation.
Try to use sharedPreferences concept, save the activity name in sharedPreferences while the opening of that activity, then check the sharedPreferences value while reopening the application. I think you got it!
sample tutorial link:
https://developer.android.com/training/basics/data-storage/shared-preferences.html
I need some help getting a checkbox's state. Basically I want to get if a checkbox from an activity is checked then if it is, show some text on the main activity. I've read lots and lots of SO Q&As but nothing worked. I got this:
CheckBox show = (CheckBox) findViewById(R.id.checkBox);
public CheckBox getShow() {
return show;
}
So I'd use
CheckBox setty = Settings.getCheck();
on the other class. But I get an error:
Cannot resolve method 'getCheck()'
How can I do this? I need to get if it's on or off and display it on the main activity. Remember that I can't use Intents because I won't have a button to transition, the text and value must be always there on the main class.
you can use shared preference to store a checkbox check/uncheck value..and based on that value you can show text in your other activity.
here is the code:
public static final String MyPREFERENCES = "MyPrefs";
initialize shared preference in onCreate() method of first activity
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
CheckBox check1 = (CheckBox) view.findViewById(R.id.your_checkbox_id);
//now initialize listener for checkbox
check1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("checked", "1");
editor.commit();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("checked", "0");
editor.commit();
}
}
});
Now in another activity you just have to load the shared preference data and show message based on condition
public void Load_checkbox() {
//define MyPREFERENCES in other activity too- same as first activity
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (shared.getString("checked", "").equals("1")) {
Toast.makeText(getApplicationContext(), "CheckBox Checked " ,Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "CheckBox unchecked " ,Toast.LENGTH_LONG).show();
}
}
call this Load_checkbox() method in your second activity where u want to check the checkbox state of first activity
I have some SwitchCompat in my Activity, I set the OnCheckedChangeListener to one of them but (using SharedPreferences), every time I start the Activity, the action of OnCheckedChangeListener is performed regardless of whether it is on or off (Which is very very bad for performance as the On state action is to run a shell script and show a SnackBar as it takes some time).
Here is a small piece of code...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//Private stuffs...
SwitchCompat play; //and many others
public static final String PREFS_NAME = "SwitchButton";
protected void onCreate(Bundle savedInstanceState) {
// ...
play = (SwitchCompat) findViewById(R.id.play_switch);
play.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Shell.SU.run("sh /data/data/br.com.packagename/play_on");
Snackbar snack_play_on = Snackbar.make(play, R.string.play_on, Snackbar.LENGTH_SHORT);
snack_play_on.show();
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onPlay", true);
editor.apply();
} else {
Shell.SU.run("sh /data/data/br.com.packagename/play_off");
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onPlay", false);
editor.apply();
Snackbar snack_play_off = Snackbar.make(play, R.string.play_off, Snackbar.LENGTH_SHORT);
snack_play_off.show();
}
}
});
play.setChecked(sharedPrefs.getBoolean("onPlay", false));
So... Every time a open the activity (ot the app itself) that Snackbar shows, and the linked action to the On state of the SwitchCompat runs.
This causes too many frames skip when loading the Activity (arround to 230 in a 1GB, 1.2GHz quad device). There is more then one Switch, four or five.
What should I do? Am I missing soomething or putting the code in the wrong place? Should I use other methods like OnResume, OnPause etc?
Calling setChecked() invokes the listener they same way a user click would.
I now handle setting up all checkboxes like this:
play = (SwitchCompat) findViewById(R.id.play_switch);
play.setOnCheckedChangeListener(null);
play.setChecked(sharedPrefs.getBoolean("onPlay", false));
play.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
...
I want to have the status of a checkbox be saved into my prefs.
I set a listener on the checkbox, and if it is checked I do a prefs.putBoolean("cbstatus", true), and it is it unchecked i do a prefs.putBoolean("cbstatus", false);
Trouble is, in my onStart() when I get prefs, my Boolean getcbstatus = prefs.getBoolean("cbstatus", false); will always return a true, regardless of how my listener should have set that status previously.
What am I doing wrong? I have working prefs for other things like spinners, textviews, and edit texts, but what should be the simplest type (a boolean) is giving me a hard time.
I've even tried taking out all code related to listeners and pref setting for this checkbox, so that the only code in the entire activity that deals with the checkbox is in the line
Boolean getcbstat = prefs.getBoolean("cbon", false);
if (getcbstat = true) {
cb1.setChecked(true);
}
else {
cb1.setChecked(false);
format.setVisibility(View.VISIBLE);
}
Since there is no cbon preference (i deleted them all), it should return false by default and the box should be unchecked since. cb1, of course, is the name of my checkbox.
Any ideas?
Update on the code:
OnClickListener cb = new OnClickListener() {
public void onClick(View v) {
if (cb1.isChecked()) {
prefs.putBoolean("cbon", true);
}
else {
prefs.putBoolean("cbon", false);
}
}
};
And in the onStart():
Boolean getcbstat = prefs.getBoolean("cbon", false);
cb1.setChecked(getcbstat);
You've accidentally assigned it to true in your if statement.
Change it to this
if (getcbstat == true)
[Edit -- How to use shared preferences (instead of Java's preferences class)]
How to use SharedPreferences:
private SharedPreferences mPref;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
mPref = getSharedPreferences("my_prefs_file", MODE_PRIVATE);
//Other onCreate code goes here...
}
//Example of where you might want to save preferences
#Override
protected void onPause() {
super.onPause();
Editor prefEdit = pref.edit();
prefEdit.putBoolean("cbon", true);
prefEdit.commit();
}
When you need to read it later:
//Example of where you might want to save preferences
#Override
protected void onResume() {
super.onResume();
boolean getcbstat = pref.getBoolean("cbon", false);
}
It would probably be a good idea to make the pref variable class level and get the preferences object in the onCreate section. Change "my_prefs_file" to whatever you like, but remember that that string is what you will use to access that that particular set of preferences from within your application. I also recommend using constants instead of raw strings for the access keys (like "cbon").
Good luck:)