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.
Related
I want to make a activity in an app which shows up only when the user installs the app and never again. How can I do that?
1.store value in sharedPrefernces.
SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("screen_show", false);
editor.commit();
2. get value from sharedPreferences
SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
preferences.getBoolean("screen_show", false);
3.It is false first time always
if( ! preferences.getBoolean("screen_show", false)){
// if show screen
Intent showscreenIntent=new(this,ShowScreen_Intent.class);
startActivity(showscreenIntent);
} else {
//
}
4.after showing screen first time set true in shared prefernece like this.
SharedPreferences preferences = this.getSharedPreferences("SoldiPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("screen_show", true);
editor.commit();
Now whenever step 3 execute else condition run and Activity will never show again.
hope it helps !!!
My issue solved by trying out this
boolean isFirstRun = getSharedPreferences("Preference", MODE_PRIVATE).getBoolean("isfirstrun",true);
if(isFirstRun){
getSharedPreferences("Preference", MODE_PRIVATE).edit().putBoolean("isfirstrun",false).commit();
Intent IntentFirstRunAct = new Intent(MainActivity.this,FirstRunActivity.class);
startActivity(IntentFirstRunAct);
}
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 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.
I have developed an App where the user has to login into the app using the login Activity. After successful login, the app is directed to Activity B. The app doesn't provide any signout options.So next time when the user uses the app I want to hide the login Activity's layout. Is it possible to do so?If yes, how is it possible?
In LoginActivity do as Suggested by nr4bt but instead of int Put & get Boolean Value in SharedPreference.
write this code
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putValue("loginStatus", true);
editor.commit();
& onCreate() of LoginActivity Write this code
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getBoolean("loginStatus", false);
if (restoredText == true) {
// start activity
finish(); // destroy login so user can't come back with back button
}
Hope this helps you.
Keep a variable in sharedpreferences and check it when your login activity starts
in LoginActivity, when the user press login button and if success,
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putInt("loginStatus", 1);// removed ""
editor.commit();
Then in onCreate check the variable,
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
int restoredText = prefs.getInt("loginStatus", 0);
if (restoredText == 1) {
// start activity
finish(); // destroy login so user can't come back with back button
}
It is quite simple to achive with SharedPreferences. You just save that user has loged in and later on start check if he already done it or not and act properly.