Switch goes back to off - java

When turn the switch on it stays on.. however when i leave the activity and come back to it.. it goes back to off. I want it to stay ON OR OFF depending on whats last pressed. I have tried the code below but does not resolve my issue
SwitchButton.setChecked(true);
SwitchButton.setChecked(false);

What you need to do is override these methods in your activity:
#Override
protected void onSaveInstanceState (Bundle outState){
super.onSaveInstanceState(outState);
outState.putBoolean("CHECKED", SwitchButton.isChecked());
}
then in onCreate:
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstaceState);
if(savedInstanceState != null){
boolean isChecked = savedInstanceState.getBoolean("CHECKED");
SwitchButton.setChecked(isChecked);
}
}

If you are minimizing the activity and then returning back to it, and you want all controls to retain their states, then look into implementing saved instance state. This will persist the control values while you minimize / maximize the activity or rotate it. No data is permanently saved to the device. Sample code here:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState
If you are closing the app completely and want the app to remember the settings, then consider SharedPreferences, which can be used to save data locally on the device. The data persists until your app explicitly deletes it or you uninstall the app. Sample code here:
http://developer.android.com/training/basics/data-storage/shared-preferences.html

Related

Android - Save current onCreate state when switching between different activities

I am new to java and android studio and after reading documentation I am still a little confused with the activity lifecycle and how to use it effectively.
I am building an application which has several activities. There is key data loaded in when the app is first opened in the main activity. However when I move to another activity and then back to the main, the onCreate is invoked again which I do not want. I am aware there is a way to save the instance of your onCreate but I am still unsure of how to do this. Here is what I have done:
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
if (outState != null) {
// Restore value of members from saved state
outState.putString("step_count", String.valueOf(stepCount));
outState.putString("cal_count", String.valueOf(calCount));
outState.putString("dis_count", String.valueOf(disCount));
android.util.Log.d(TAG, "onSaveInstanceState");
} else {
// Probably initialize members with default values for a new instance
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getString("step_count", String.valueOf(stepCount));
savedInstanceState.getString("cal_count", String.valueOf(calCount));
savedInstanceState.getString("dis_count", String.valueOf(disCount));
stepCount.setText(String.valueOf(stepCount));
calCount.setText(String.valueOf(calCount));
disCount.setText(String.valueOf(disCount));
android.util.Log.d(TAG, "onRestoreInstanceState");
}
Would appreciate any sort of support and guidance. Thank you.
Again - not a simple question.
First of all: Yes, you can save data "from last session" by overriding: onSaveInstanceState() and restore it overriding onRestoreInstanceState(savedInstanceState: Bundle?). Look here: https://developer.android.com/guide/components/activities/activity-lifecycle#saras
Second of all: According to your description it seems that you need SharedPreferences more than this. If you need a key to anything and it should be used from opening of the app until it is killed or user is logged out, SharedPreferences are the most common solution.
onSaveinstanceState() was created to make possibility to remember what was on the screen "in the last session" without "calculating" it again. For example EditText.text or ImageView.url or similar.

How to show Online of a user?

I'm trying to get an app to show all the users online... I'm using the following way to achieve it
#Override
public void onStart(){
super.onStart();
mDatabaseReference.child("Online").setValue(true);
}
#Override
public void onStop(){
super.onStop();
mDatabaseReference.child("Online").setValue(false);
}
I'm not using ondisconnect because it shows offline only if the app is completely closed(not running in the background). SO i used this method on each activity... But the problem is that whenever i open an activity it shows online and the next second turns offline... I'm guessing that its because the prev activity closes after opening the new activity so the presents activity's on start is executed before the next activity's on stop. So since the activity's onstop is executed last it shows offline. How do i solve this problem
Your guess is completely correct.
Starting a new Activity will cause the onPause() and onStop() methods to be called for the first Activity.
Based on your description, I'm assuming that you want the Online status to remain true for as long as the app remains in the foreground and you are putting it in every Activity because your app doesn't only open from a single main Activity.
Your current code will work without a problem if you switched to using a Single-Activity Architecture, which is simply to use a single Activity and have it display different Fragments instead of new Activities. This solution will work with your existing code because onStop() and onStart() will only be called when your app enters the background.
If you look at the Navigation section in the official Android Developers Blog, you'll see that Google wants to encourage developers to switch to using the Single-Activity Architecture.
However, if you still wish to use multiple Activities, then you might want to consider an alternative way to keep track of Online status to take into account of multiple Activities.
For example, rather than using a simple boolean value, you can use an int value.
#Override
public void onStart(){
super.onStart();
mDatabaseReference.child("Online").addValue();
}
#Override
public void onStop(){
super.onStop();
mDatabaseReference.child("Online").removeValue();
}
With the addValue() and removeValue() being:
private void addValue(){
activityCount++;
onlineStatus = true;
}
private void removeValue(){
activityCount--;
if(activityCount <= 0)
onlineStatus = false;
}
Please keep in mind that this is only an example and doesn't take into account of how your app is designed. Bottom line is, you'll have to think of a solution that takes into account of multiple Activities that are displayed.
I do heavily suggest the Single-Activity approach.

Retrieving keys from a savedinstancestate when a user navigates away from an activity and then back

I'm having a problem with SavedInstanceStates. In the Main Activity of my app, a listview is populated with names from a database. When you click on one of the names, a new activity is opened, which shows another listview drawn from a separate database and details various information about the person. The items on this listview are only shown if their characterID, set according to the person whose name they are created under, and the id of the person in the original database match. So long story short, you can create a person Trevor, there are then a number of pieces of information shown specific to Trevor when you click on Trevor. You can also click on those pieces of information to open a new activity and edit that info/ do stuff with the info. I did this by saving the Uri of the person clicked with setData, and then getting that uri with getData and parsing the id from it for my second query.
When a user clicks a piece of information about Trevor and it opens in a new activity, the variable containing the id is destroyed as is the data I set in the first activity. So when I click back, it crashes due to a NullPointerException. So I now check if the data from getData() is null before performing my database query. But that just leaves the listview empty since it has no id to use when querying the database.
So I tried to used onSaveInstanceState to save the characterId variable. But using onRestoreInstanceState doesn't seem to work. Navigating to the third activity, and then finishing it by clicking back, does not seem to call onRestoreInstanceState. I also tried to check if the savedInstanceState is null in onCreate, see if it contains they key I set, and then withdraw it, but the savedInstanceState is null in onCreate whether Im first navigating to it, or hitting the back button to return to it. I've looked around for a few hours trying to figure out the answer. Is this the wrong tool for the job? Am I missing something?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(savedCIdString)) {
characterId = savedInstanceState.getInt(savedCIdString);
}...
A snippet of my onCreate where I try to retrieve the variable, but SavedInstanceState is null when I first navigate to it, and when I press back from the activity after it.
#Override
protected void onSaveInstanceState (Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(savedCIdString, characterId);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
characterId = savedInstanceState.getInt(savedCIdString);
}

How to keep entered text in edittext field?

I'm creating an app that require user to enter name, email, date and etc in Main_Activity.xml. Then, the user will click submit. The entered data will be displayed in confirm.xml. In confirm.xml, user need to verify entered data and if the want to edit entered data, they will click back button to edit data again. I tried to do that but once I click back button, all the data I entered in editText field disappeared. I want to keep the data I entered in MainActivity.xml's editText field, so I can change only some field that need to be edited. How can I do this? Thank you.
This can happen when the activity where you entered data is destroyed. How do you open the new confirmation activity? That's the part of the code that probably contains the error.
If you call finish() when you open the new activity then activity will be destroyed and data kept in EditText cleared.
To open a new activity and preserve data of the current one you just need to call startActivity(...) without finish().
Intent intent = new Intent(context, ConfirmationActivity.class);
startActivity(intent);
Anyway, the activity can be destroyed by android to free up memory when needed. That happens when you open another application that needs memory but memory is used by your application, so the system destroys your activities and it's up to you to save data on disk by using Bundles and restoring them.
I suggest you to read this guide https://developer.android.com/guide/components/activities/activity-lifecycle.html
You can overwrite the onSaveInstanceState(Bundle savedInstanceState) function and use the savedInstanceState to save the various data that you want to get back during the onCreate(Bundle instanceState) or onRestoreInstanceState(Bundle instanceState).
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("TextFieldX", "Data To Retrieve");
}
And get it back:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get back value
String value = savedInstanceState.getString("TextFieldX");
}
https://developer.android.com/reference/android/os/Bundle.html
For longer lived persistance of your data, you would write it to SQLite.
You can save all your information to String's like private String Name;
write/set this Name when user enter's the Name and use it again like as follows:
if(name != null && !name.toString().isEmpty()) {
set name String on your editText widget.
}
You can use shared preference object to save value of edittext value in user's phone. When code execute second time, you just check about variable in shared preference. If variable is not null, fetch value from it and set that string using setText() method.

What is better for my needs, onPause() or onSaveInstanceState()?

i have an app that has three pages, one of them is the main page. the user can enter in a few fields that i would like to save if the user goes to one of the two sub pages. i have been looking into the onPause() and into onSaveInstanceState(). i guess i just want a clear explanation on the two, and if onPause() is better and example of the code. this is what i ahve for onSaveInstanceState().
protected void onSaveInstanceState(Bundle outState) {
// Save away the original text, so we still have it if the activity
// needs to be killed while paused.
outState.putDouble("quizPts",qpts);
outState.putDouble("quizV",qvalue);
outState.putDouble("tPts",tpts);
outState.putDouble("tValue", tvalue);
outState.putDouble("hPts", hpts);
so that is how i am setting up bundle, by giving it an ID and a value.
public void onRestoreInstanceState(Bundle outState) {
super.onRestoreInstanceState(outState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
qpts = outState.getDouble("quizPts");
qvalue = outState.getDouble("quizV");
tpts = outState.getDouble("tPts");
tvalue = outState.getDouble("tValue");
hpts = outState.getDouble("hPts");
this is how i plan to retore it, the problem is i dont understand how to pass the Bundle around to restore it. i am setting the variables that i need to back to the variables that get set to the UI.
any advice would be great
thanks from a beginner androider
The best option will be a shared preference. The onpause is designed for attending your concerns when app is paused due to a phone call or something. But if you use shared preference it gives you the method for saving your data and recover it wit default values if the saved value is not available. This data will persist across user sessions (even if your application is killed). But it is not a good option if you are planning to save something other than primitive data types like bool,int etc.
see http://developer.android.com/guide/topics/data/data-storage.html#pref
You don't need to pass the bundle around yourself: the Activity framework takes care of that. Use onSaveInstanceState(): if your Activity class is destroyed for any reason by the system it will be called so you should be fine putting your logic in there. onPause will always be called if you leave your Activity, regardless of if the Activity is destroyed.
I would also add a check in your onRestoreInstanceState:
public void onRestoreInstanceState(Bundle outState) {
super.onRestoreInstanceState(outState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
if(outState.containsKey("quizPts")) qpts = outState.getDouble("quizPts");
if(outState.containsKey("quizV")) qvalue = outState.getDouble("quizV");
if(outState.containsKey("tPts")) tpts = outState.getDouble("tPts");
if(outState.containsKey("tValue")) tvalue = outState.getDouble("tValue");
if(outState.containsKey("hPts")) hpts = outState.getDouble("hPts");

Categories

Resources