Wednesday, April 15, 2015

Android : Activity's savedInstanceState() not being called when going to new Activity via ActionBar



Any Help would be appreciated because I am almost finished and this one little thing is bugging me so much!


I have 1 of three activities that in onCreate() it populates a TextView from a query of a database. This activity is also the main activity. The other 2 activities you travel through via the action Bar like the code below shows. I have both savedInstanceState() and onRestoreInstanceState() in play here and they only work when you exit out of the application completely, which is good but I also want it so that when you go to another Activity from the actionBar then the TextView will still be the same.


I tried using the finish() and the onStop() methods to help terminate the activity so that saveOnInstanceState() would be called when the Activity is destroyed but it either isn't working or I am not placing it in the right place. Any Thoughts Please?!?!?!


applying savedInstanceState in onCreate():



if(savedInstanceState != null){
String SavedStory = savedInstanceState.getString(SavedStoryHere);
String SavedTitle = savedInstanceState.getString(SavedTitleHere);
OpenningTextView.setText(SavedStory);
TitleTextView.setText(SavedTitle);
}
else{
OpenningTextView.setText(StoryText);
TitleTextView.setText(TitleString);
}


The onSavedInstanceState() and the onRestoreInstanceState():



protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
String text = OpenningTextView.getText().toString();
String titleText = TitleTextView.getText().toString();
savedInstanceState.putString(SavedStoryHere, text);
savedInstanceState.putString(SavedTitleHere, titleText);
}

protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
OpenningTextView.setText(savedInstanceState.getString(SavedStoryHere));
TitleTextView.setText(savedInstanceState.getString(SavedTitleHere));
}


Going to Different Activities via the ActionBar:



public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.Openning_Screen:
Toast.makeText(this, "This is the Story of the Day", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.The_List:
Intent A_ListIntent = new Intent(this, A_Where_List.class);
startActivity(A_ListIntent);
return true;
case R.id.Settings:
Intent SavedStoriesIntent = new Intent(this, Settings.class);
startActivity(SavedStoriesIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}

No comments:

Post a Comment