Error in using a checkbox between multiple activities - java

I am trying to write a settings activity in an application on Eclipse. In the Main Activity, it has a button that runs a certain command. In the settings activity, I want to have a checkbox that when checked, changes what the button in the Main Activity runs when it is tapped. Right now, I have it so that when the checkbox is checked, it changes the value of a boolean and passes it to the main activity. When the button in the main activity is tapped, it checks to see if the boolean is true or false. All of this works perfectly, but when I return to the settings activity after that, the checkbox is unchecked. What should I do to have it stay checked after I go to another activity?

I believe the comment I posted is the answer:
You need to save the state of the activity. This information can be found at Saving Android Activity state using Save Instance State but in short you need to override these two methods:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
}
and
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}

you can use shared preference in android to store state. take look at this
http://developer.android.com/guide/topics/data/data-storage.html#pref
and
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/

Related

Android Java onCreate

So I followed Google's first Android app sample. If I tapped the send button, it opened up the DisplayMessageActivity. But upon tapped the back button (left arrow) from the DisplayMessageActivity, the onCreate(Bundle savedInstanceState) of the MainActivity got called again. It looks like it created a new instance of MainActivity. I could verify this by setting a bool value in onCreate of MainActivity and it was not retained.
How do you go back to the previous instance of MainActivity (the caller)?
You should have a look at Androids Activity Lifecycle.
If you want to access the state of the activity again, I would suggest to use the method
public void onSaveInstanceState(Bundle outState)
to save the current state.
Retrieve the previously saved values in this method:
public void onRestoreInstanceState(Bundle savedInstanceState)`
An example can be found here
You can call finish() in the onClickListener of the back arrow view. It will finish the DisplayMessageActivity and you will return to the caller activity (MainActivity in your case).
Something like:
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
It looks like it created a new instance of MainActivity.
Yes, I think, that was quite a normal behavior.
Basically, Android OS would keep only one Activity at once so that free as many memory resources as possible.
You should design your application with understanding about such lifecycle concepts.
You can save some of the states of your Activity in certain manners (Parcelable, Bundle or SharedPreferences, etc.).

Update RecyclerView after Dialog and orientation change

I have an app which uses only one activity. Inside, I load a fragment with a recyclerview.
Each item in the recyclerview is a dialog fragment. The user can change the items, therefore the recyclerview is updated when the dialog is dismissed.
The problem I'm having now is that when the app is rotated while the dialog is active, the recyclerview will not get updated after the dialog is dismissed.
My dialog gets recreated along with everything in the app when destroyed so I suspect the dismisslistener gets destroyed when recreating.
The dialog exposes a method to set the dismisslistener and then overrides the event to check if one was set.
public void setOnDismissListener(DialogInterface.OnDismissListener
onDismissListener) {
this.onDismissListener = onDismissListener;
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (onDismissListener != null) {
onDismissListener.onDismiss(dialog);
}
}
I then set a dismisslistener inside the onViewBindHolder of the recyclerview
editor.setOnDismissListener(dialog -> {
recycler.getAdapter().notifyDataSetChanged();
}
I'm unsure why this happens, but it seems that after changing the orientation and recreating everything, the recyclerview is never updated. I found out that the method is still called, because inside the ondismisslistener was another function that updated another view with getView().findViewById() which then crashed the app because getView returned null.
I couldn't find any other post about this here.
Does anyone know how I fix the dismisslistener or maybe any other way to wait for a dialogfragment to close?
Have you added android:configChanges="orientation|screenSize" to your activity in AndroidManifest?
Otherwise try (onRestoreInstanceState() and onSaveInstanceState()
Alright I've found out what went wrong.
When recreated, the dialog loses all his variables, just like everything else.
It could be theoretically possible to save those variables in the bundle and fetch them again on recreation, but I have not found a way to do this with an OnClickListener, since objects passed to a bundle must be serializable or parcable.
Therefore, my dialogues are now just dismissed when they do not have any variables via a check in OnCreate.

How do I change the main xml file from another activity?

I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.

Running a method before pressing a button, like a document.ready function

Is there in java something like the $(document).ready(function()?
When my app runs, the score that is saved using shared preferences refreshes only after i press the "check it" button, and I'd need to do that before everything else, just after the app loads.
What should I do ?
You are looking for
#Override
public void onCreate(Bundle savedInstanceState) {}
Please read up on Activity Lifecycle

Iconsistent results when returning to a previous activity

I have an android app that has various activities.
for example there is a home screen and an update screen.
The home screen is a list activity.
A button on the home screen brings you to the update screen that updates the database from a server. In theory when Returning to teh homescreen after an update, the list should be changed to reflect the update just done.
the code for going to the update screen is as follows:
Button synch = (Button) findViewById(R.id.synchButton);
synch.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
Intent intent = new Intent(HomeScreen.this, SynchScreen.class);
startActivity(intent);
}
});
and the code for returning back to the homescreen after the updates is:
main_menu.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
finish();
}
});
the list is compiled from an async task that runs in onStart, so my understanding is that onStart should run when I return to the homescreen, thus always displaying the most up to date version of the list.
On my Emulator I always get teh updated list, but when I run it on my phone the list is never updated, it just returns to the state of teh screen before I did the update.
any ideas?
thanks
Kevin
Check the Activity lifecycle section of the Android documentation. The code updating the view should probably be moved to onResume, since the Activity might not get killed when launching a new one.
Put the code for starting the Asynctask in onResume. Read the documentation related to activity life cycle.
#Override
public void onResume() {
super.onResume();
Apaptor.refreshListView(Vector);
}

Categories