Android: How NOT to save instance state? - java

My app has login, once the access is granted, it creates a new html file to the sdcard, the output or the appearance of that html file depends on the account of the logger.
After writing, the app goes to the next activity
Intent nextActivity = new Intent(MyMainAct.this, AppView.class);
startActivity(nextActivity);
the AppView class is the next activity in which the UI is a webview. It views the html created on login.
When I click "login as different user" button, I go back to the Main Activity which is MyMainAct. I use the following code:
Intent nextActivity = new Intent(AppView.this, MyMainAct.class);
startActivity(nextActivity);
When I logged in again (as different user), I expected a different UI since the html created is different. But it did not happen. The same html of the first logger is presented by the webview.
I looked into the html code created by the second logger, it is different from the first. but the webview presents the html of the first logger.
Is it about instance state? That's what I think, that's why I don't want to save instance state (bundle).
EDIT:
How do I ignore savedInstanceState of my App?
my MainActivity:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
my AppView Activity:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);

Make sure that when user chooses the "login as different user" option, activity showing the HTML is finished (i.e. call the finish method on it). If you then ignore the savedInstanceState parameter in its onCreate event (which you likely do, I presume), the next time this activity is started it will be totally new instance of it.

Try this and see if it works.
Intent nextActivity = new Intent(AppView.this, MyMainAct.class);
startActivity(nextActivity);
finish();

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.).

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.

Where to put welcome activity code

I searched a lot but i did not find my answer. I have developed an android application where on the very first lunch user will be shown a welcome screen made of viewpager. The problem is i don't know which place is the best to put the welcome activity code in my application.
The simplest way it could be that in the main activity at the very fist line even before super.onCreate(), inside onCreate method where i try to get the shared preference value and then evaluate whether it is fist lunch. If it is, then i start the welcome activity as shown below
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean welcome = sharedPreferences.getBoolean(getString(R.string.key_welcome), true);
if (welcome) {
// go and start welcoming activity
Intent intent = new Intent(this, WelcomeSlideActivity.class);
startActivity(intent);
}
super.onCreate();
}
}
But i found another approach to deal with it. It is Application class. Since Application class is the first one, which runs even before any other codes in my application. So i thought, i would be nice to do it there as shown below
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean welcome = sharedPreferences.getBoolean(getString(R.string.key_welcome), true);
if (welcome) {
// go and start welcoming activity
Intent intent = new Intent(this, WelcomeSlideActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
So i am in dilemma, which one would be the best option to choose. And i am even not sure if i am doing it in the right way since there is no such documentation in android developer website or anywhere.
Have a look at how to create splash screens the correct way. https://www.bignerdranch.com/blog/splash-screens-the-right-way/
As for using the Application class - this is primarily used for Application-wide configuration for maintaining a global application state. Hence starting an activity from here does not make much sense as it's purpose has changed into becoming an entry point into the application rather than providing state for the app as a whole.
Furthermore, why not make the WelcomeSlideActivity the first 'launcher' activity? Then in there, you can create the logic of whether to launch the next activity without history or whether to show the current view.
Ideally, you should create a splash screen activity, which determines whether to show the WelcomeSlideActivity Or the MainActivity. The advantage of this is that while he app determines which Activity to launch, the user is presented with a splash screen that informs the user that the app has started

Get text of textView from another activity

I am trying to get text from textview which is located in class 2 to use it in class 1 by pressing a button. I do this by sending an Intent, but i got the error of my content. That is what i am trying to send (from class 2 to class 1):
public static void intent_send(){
Intent i = new Intent();
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
class2.startActivity(i);
}
text_view_current_page is a static TextView, otherwise it has an error in this void. I call this void by pressing a button in class 1:
Class2.intent_send();
Intent i = getIntent();
Bundle b = i.getExtras();
PagerNumber = b.getInt("number");
I have an error in the line of the content definition:
i.putExtra("number",Integer.parseInt(text_view_current_page.getText().toString()));
What should i do with this textView to be able get it's text from another class by pressing a button? Should it be static or should i declare it in that class which receives an intent?
In Android activities are fully separated components and hence those cannot access each other's stuff directly. Those have their own window and view hierarchy which are private only to the owner activity itself.
Nevertheless there are a couple of ways for activities to interact with each other.
Sending data when you are starting second activity via Intent.
Utilizing Application object as a share object among all app's components.
Registering in-activity broadcast receivers by which you can send signals between activities.
My Recommendation for your case:
If in your case, the second activity should have a very close relation with the first one (e.g. accessing its view hierarchy), you could implement the second activity as a dialog or fragment not an activity.

Error in using a checkbox between multiple activities

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/

Categories