onRestoreInstanceState does not get called? - android

I am having a simple code where i want to know when does onRestoreInstanceState get called during program execution in android?
Please help me out.
Thanks in advance.
My first Activity is as follows
public class AbcActivity extends Activity {
Button b1;
EditText ed1;
Bundle b = new Bundle();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v("Tag", "inside oncreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.button1);
ed1 = (EditText) findViewById(R.id.editText1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.v("Tag", "inside onsave instance state");
outState.putString("key", ed1.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.v("Tag", "inside on restore instance state");
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
Log.v("tag", "inside if");
String str = savedInstanceState.getString("key");
ed1.setText("" + str);
}
}
}
my second activity code is as follows
public class SecondActivity extends Activity {
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v("Tag", "inside 2 oncreate");
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
back = (Button) findViewById(R.id.button1);
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),
AbcActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Log.v("Tag", "inside 2 onsave instance state");
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.v("Tag", "inside 2 on restore instance state");
super.onRestoreInstanceState(savedInstanceState);
}
}

As the documentation states:
This method is called after onStart() when the activity is being re-initialized from a previously saved state
...
This method is called between onStart() and onPostCreate(Bundle)
This is the case when your Activity is re-created after being killed by the system or after a configuration change, and it saved its state in onSaveInstanceState(Bundle) - which is always called before an Activity is killed.

Related

Interacting with Other Apps: onActivityResult method not being called Android

I wish that when I click on the apply button firstapp, opens secondapp thus the data passed the press: What did I do wrong?
Secondapp is called but it print null.
App1
package pkg.firstapp;
public class MainActivity extends Activity{
private static final int REQUEST_CODE_START_APP = 12345;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PackageManager manager = getApplicationContext().getPackageManager();
try {
Intent i = manager.getLaunchIntentForPackage("pkg.secondapp");
if (i != null)
{
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.putExtra("key1", "value1");
i.setFlags(0);
setResult(RESULT_OK, i);
startActivityForResult(i, REQUEST_CODE_START_APP);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
If you want to get String from Intent, you should call getIntent().getStringExtra("key1"); in onCreate. onActivityResult is called in first Activity after finishing second. Read this for more info
onActivityResult is called in the activity which started other activity for result.
In order to get the data you're sending, in the second activity's onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String value1 = getIntent().getStringExtra("key1");
}

how to make image invisble in first activity when navigating from second activity to first activity

I have two imageviews in firstActivity(MainActivity) when i click signIn image then it moves to SignUp Activity...
here when i click on signUp image then again it will come to MainActivity..and here i have to make firstName image invisible..
public class MainActivity extends Activity {
ImageView firstName,signIn ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstName =(ImageView)findViewById(R.id.imageView1);
signIn =(ImageView)findViewById(R.id.imageView2);
signIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),SignUp.class);
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart");
String mm ="5";
Intent i= getIntent(); String s = i.getStringExtra("PrevAct");
if (mm ==s) {
firstName.setVisibility(View.GONE);
}
}
public class SignUp extends Activity {
ImageView signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
signUp =(ImageView)findViewById(R.id.imageView3);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("PrevAct","5");
startActivity(intent);
}
});
}}
While you try to launch the MainActivity Activity again, ensure that you re-use the same instance and not a new one for application better performance.
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("PrevAct","SignUP");
startActivity(intent);
Use a variable to check if the screen is rendered from SignUpActivity.
Intent i= getIntent();
String s = i.getExtra("PrevAct","NO");
Based on the String Value, you can decide to show/hide.
Please note that View.Invisible only hides the view from screen. But still it gets loaded and takes the space on screen. This is a bad UI implementation.
Therefore use View.GONE instead.
Your Source Code modified as below
public class MainActivity extends Activity {
ImageView firstName,signIn ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstName =(ImageView)findViewById(R.id.imageView1);
signIn =(ImageView)findViewById(R.id.imageView2);
signIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),SignUp.class);
startActivity(intent);
}
});
}
protected void onStart() {
super.onStart();
firstName = (ImageView)findViewById(R.id.textView1);
{
Intent i= getIntent();
if(i!=null){
String s = i.getExtra("PrevAct","NO");
if(s.equalsIgnoreCase("SignUP"))
firstName.setVisibility(View.GONE);
}
else
firstName.setVisibility(View.Visible);
}
}
public class SignUp extends Activity {
ImageView signUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
signUp =(ImageView)findViewById(R.id.imageView3);
signUp.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra("PrevAct","SignUP");
startActivity(intent);
}
});
}}
By clicking signIn image, use startActivityForResult to start your activity for signing up.
In signing up activity, use setResult and finish to return to login activity.
When returning to first activity, make firstName image invisible or gone as you like in onActivityResult.

how to save state of an activity while changing mode (land/port)?

i have a set of words in an array and i am displaying them one by one like a slideshow using Handlers. the problem is when i switch mode (land to portrait or vice verse) it starts again from the first word.
i know i have to save the variables in onSaveInstanceState() but the problem is the value of the variable 'i' which i want to save is in a different method (updateUI()).
this is my activity:
public class WatSlideShow extends Activity {
RefreshHandler refreshHandler = new RefreshHandler();
TextView watwords;
int i = 0;
String wat1[] = { "SICK", "FUTURE", "PROBLEM", "DECEIVE", "SUFFER",
"FAITH", "PROTECT", "SUICIDE", "STEP", "WNJOY", "FAIL" };
class RefreshHandler extends Handler {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
WatSlideShow.this.updateUI();
}
public void sleep(long delayMillis) {
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
};
public void updateUI() {
if (i < wat1.length) {
watwords.setText(wat1[i]);
refreshHandler.sleep(3000);
i++;
}
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.watslideshow);
updateUI();
}
how should i save the value of 'i' (which is the word being displayed) in onSaveInstanceState().
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
int currentI = ? // how to get value of 'i' here
outstate.putInt("Myint", currentI)
}
and then i can use this in oncreate():
int myInt = savedInstanceState.getInt("MyInt");
sorry but my java concepts not strong yet. still learning.
You declared i as a class member variable of your activty, you can access it anywhere in your activity.
protected void onSaveInstanceState(Bundle outState) {
outstate.putInt("Myint", i)
super.onSaveInstanceState(outState);
}
Update
public class MainActivity extends Activity {
private String[] wordList = { "SICK", "FUTURE", "PROBLEM", "DECEIVE", "SUFFER","FAITH", "PROTECT", "SUICIDE", "STEP", "WNJOY", "FAIL" };
private TextView tv;
private int current = 0;
private Handler handler = new Handler();
public void updateUI() {
current++;
if (current == wordList.length) current=0;
tv.setText(wordList[current]);
handler.postDelayed(new Runnable() {
#Override
public void run() {
updateUI();
}
}, 3000);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState!=null) current = savedInstanceState.getInt("current");
tv = (TextView) findViewById(R.id.tv);
updateUI();
}
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("current", current);
super.onSaveInstanceState(outState);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
}
Lets assume your textview is named as MyTextView in your layout xml file. Your activity will need the following:
private TextView mTextView;
private static final String KEY_TEXT_VALUE = "textValue";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.main);
if (savedInstanceState != null) {
String savedText = savedInstanceState.getString(KEY_TEXT_VALUE);
mTextView.setText(savedText);
}
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_TEXT_VALUE, mTextView.getText());
}
For more detail
see this
protected void onSaveInstanceState(Bundle bundle) {
bundle.putInt("Myint", i)
super.onSaveInstanceState(bundle);
}

Keeping activity

How to keep the button activity on background/pause or something like this when i press the physical back button . I want this activity to set on when i press again the button.(to show me what did i paint in last activity);
MainActivity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSave=(Button)findViewById(R.id.buttonDraw);
buttonSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(MainActivity.this,ButtonDraw.class));
}
});
}
ButtonDraw :
public class ButtonDraw extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(com.example.myfirstapp.R.layout.paintingfile);
BlackPixel blackPixel;
blackPixel = new BlackPixel(this);
setContentView(blackPixel);
blackPixel.requestFocus();
}
}
In your MainActivity include this method:-
#Override
public void onBackPressed() {
startActivity(new Intent(this,ButtonDraw.class));
finish(); // this line depends on you whether you want to finish the MainActivity or not.
}
The above method gives you control over the back button of android.

Update a TextView on resuming main activity

Friends in this code provided below, i want to refresh my text view upon resume from play intent. But whenever i try to define my textview out of OnCreate but inside my main class (after static int score), my app crashes.
public class MainProjectActivity extends Activity {
/** Called when the activity is first created. */
static int Score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Display Scores
final TextView displayScores = (TextView)findViewById(R.id.scoreDisplay);
displayScores.setText("Your Score : "+ Score);
//Play Game button activity
Button gameButton = (Button)findViewById(R.id.PlayButton);
gameButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
startActivity(play);
}
});
I'd start with adding super.onResume();:
#Override
protected void onResume(){
super.onResume();
// The rest
}
I would also remove that:
final TextView displayScores = (TextView)findViewById(R.id.scoreDisplay);
displayScores.setText("Your Score : "+ Score);
from onCreate,and add it to onResume() since every time onCreate is called, onResume is called as well.
also change from public to protected onResume()
try this:
public class MainProjectActivity extends Activity {
/** Called when the activity is first created. */
TextView displayScores;
static int Score = 0;
#Override
protected void onResume(){
super.onResume();
// code to update the date here
displayScores.setText("Your Score : "+ Score);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Display Scores
displayScores = (TextView)findViewById(R.id.scoreDisplay);
displayScores.setText("Your Score : "+ Score);
//Play Game button activity
Button gameButton = (Button)findViewById(R.id.PlayButton);
gameButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent play = new Intent(getApplicationContext(), com.sample.game.PlayScreen.class);
startActivity(play);
}
});
#Override
protected void onResume() {
// TODO Auto-generated method stub
displayScores.setText("Your Score : "+ Score);
super.onResume();
}

Categories

Resources