I have an Activity, from there I start a task (consider like uploading multiple files to server) using IntentService. Once each and every upload is completed I send back the result of upload to Activity using ResultReceiver. I'm getting the result back to an Activity and updating the UI.
While uploading the files, I close my Activity. IntentService is still running and returning the result. But Activity is not alive to receive the result as it was destroyed. Now again I open the Activity I want to continue to show the uploading progress. But it's not happening. I'm sharing the code what I have done.
MyResultReceiver.java
public class MyResultReceiver extends ResultReceiver {
private Receiver receiver;
public MyResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
this.receiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (receiver != null) {
receiver.onReceiveResult(resultCode, resultData);
}
}
}
MainActivity.java
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
resultReceiver = new MyResultReceiver(new Handler());
resultReceiver.setReceiver(new MyResultReceiver.Receiver() {
#Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == RESULT_OK) {
isCompleted = resultData.getBoolean("IsCompleted");
textView.setText(resultData.getString("Message"));
}
}
});
Intent intent = new Intent(MainActivity.this, MyIntentService.class);
intent.putExtra("receiver", resultReceiver);
startService(intent);
}
MyIntentService.java
#Override
protected void onHandleIntent(final Intent intent) {
for (int count = 0; count <= i; count--) {
ResultReceiver receiver = intent.getParcelableExtra("receiver");
i -= 1;
Bundle bundle = new Bundle();
if (count == i)
bundle.putBoolean("IsCompleted", true);
else
bundle.putBoolean("IsCompleted", false);
bundle.putString("Message", "This is " + i);
receiver.send(Activity.RESULT_OK, bundle);
Log.i("Intent Service", "This is " + i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In the above code all I'm trying to display the decremented count in TextView.
I have tried using onSaveInstanceState, but according to the documentation it just saves only when OS decides. In my case I want to store this data all time and restore it whenever the activity is re-created.
Any help or reference will be encouraged.
EDIT : How I tried to store and restore the instance
Intent intent = new Intent(MainActivity.this, MyIntentService.class);
if (savedInstanceState != null) {
intent.putExtra("receiver", savedInstanceState.getParcelable("savedReceiver"));
} else
intent.putExtra("receiver", resultReceiver);
startService(intent);
I tried something like this. But didn't help. And I can't use savedInstanceState as it will not be called all the time. Hope this help!
Related
I am trying to pass Bundle from second activity to the first(launch) activity. In order not to get NPE on launch, I am checking if bundle != null, however, it looks, like even after returning from second activity with Bundle, it still doesn't run the "if" body.
Here is my part of code of first activity
Bundle bundle = getIntent().getExtras();
if (bundle!=null) {
Player player = new Player();
player.setStatus(bundle.getInt("Status"));
player.setName(bundle.getString("Name"));
addPlayerToList(player);
Log.e("Player with a name " + player.getName(), "Has been created");
}
And code of second activity
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(getApplicationContext(),StartActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("Status",status);
bundle.putString("Name", name);
Log.d("Object " + name, "Status: " + status);
startActivity(i);
}
});
Thanks for any help/advice
Use startActivityForResult() for this situation.
1) You open second activity from the first using this method, not startActivity()
2) Do whatever you want in the second activity
3) Set result bundle
4) Finish activity
5) Open bundle in the first activity
In your case it will look like:
1) Call second activity like this:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, REQUEST_SECOND_ACTIVITY); // request code const
2-4)
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = nameEditText.getText().toString();
if (defaultRadioButton.isChecked()) {
status=0;
} else if (driverRadioButton.isChecked()) {
status=1;
} else {
Toast.makeText(getApplicationContext(), "Suka viberi galochku", Toast.LENGTH_SHORT).show();
}
final Intent returnIntent = new Intent();
returnIntent.putExtra("Status", status); // set values
returnIntent.putExtra("Name", name);
setResult(Activity.RESULT_OK, returnIntent); // set result code
finish(); // finish this activity and go back to the previous one
}
});
5) Override this method in the first activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case REQUEST_SECOND_ACTIVITY: // same request code const
if(resultCode == Activity.RESULT_OK){
Player player = new Player();
player.setStatus(data.getIntExtra("Status"));
player.setName(data.getStringExtra("Name"));
addPlayerToList(player);
}
break;
}
}
try Intent.putExtra() instead of putting data into a bundle, and use Intent.getStringExtra() to get a String data;
In your code, there is no code to put your bundle into intent. actually you never pass the bundle to first activity. you can use this answer to solve your problem.
good luck!
here is the code provided by the official guide, while this is a snippet causing problems.
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GooglePlayServicesUtil.getErrorDialog()
mResolvingError = true;
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, REQUEST_RESOLVE_ERROR)
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
mResolvingError = false;
}
});
}
}
If I use it in a Service, when you read the variable this passed as argument to those functions, they expect an Activity type.
How should I do? It's a Service.
For the same reason I can't get activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
This answer assumes your service is a "started" service. If it is a bound service or intent service, indicate that in a comment and I'll update the description and code included here.
The solution I suggest is to implement the activity shown below to handle the resolution UI. Replace the onConnectionFailed() method in your service with this code to hand off the resolution processing to the ResolverActivity:
#Override
public void onConnectionFailed(ConnectionResult result) {
Intent i = new Intent(this, ResolverActivity.class);
i.putExtra(ResolverActivity.CONNECT_RESULT_KEY, result);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
Add the activity shown below to your app. When the connection request in your service fails, the connection result, which is a Parcelable, is passed to the activity. The activity handles the resolution UI and when finished, returns the status to the service as an intent extra. You will need to modify the code in your service's onStartCommand() to examine the extras in the intent to determine if it is being called to start the service for the first time, or to receive resolution status from the ResolverActivity.
An enhancement to this approach would be to post a notification with a PendingIntent for ResolverActivity instead of launching the activity immediately. That would give the user the option of deferring resolution of the connection failure.
public class ResolverActivity extends AppCompatActivity {
public static final String TAG = "ResolverActivity";
public static final String CONNECT_RESULT_KEY = "connectResult";
public static final String CONN_STATUS_KEY = "connectionStatus";
public static final int CONN_SUCCESS = 1;
public static final int CONN_FAILED = 2;
public static final int CONN_CANCELLED = 3;
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1111;
private static final String ERROR_CODE_KEY = "errorCode";
private static final String DIALOG_FRAG_TAG = "errorDialog";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate()");
// No content needed.
//setContentView(R.layout.activity_main);
Intent i = getIntent();
ConnectionResult result = i.getParcelableExtra(CONNECT_RESULT_KEY);
if (result.hasResolution()) {
try {
Log.i(TAG, "Starting error resolution...");
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent.
sendStatusToService(CONN_FAILED);
finish();
}
} else {
// Show dialog using GooglePlayServicesUtil.getErrorDialog()
ErrorDialogFragment.newInstance(result.getErrorCode())
.show(getSupportFragmentManager(), DIALOG_FRAG_TAG);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
if (resultCode == RESULT_OK) {
Log.i(TAG, "onActivityResult(): Connection problem resolved");
sendStatusToService(CONN_SUCCESS);
} else {
sendStatusToService(CONN_CANCELLED);
Log.w(TAG, "onActivityResult(): Resolution cancelled");
}
// Nothing more to do in this activity
finish();
}
}
private void sendStatusToService(int status) {
Intent i = new Intent(this, MyGoogleApiService.class);
i.putExtra(CONN_STATUS_KEY, status);
startService(i);
}
// Fragment to display an error dialog
public static class ErrorDialogFragment extends DialogFragment {
public static ErrorDialogFragment newInstance(int errorCode) {
ErrorDialogFragment f = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(ERROR_CODE_KEY, errorCode);
f.setArguments(args);
return f;
}
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = getArguments().getInt(ERROR_CODE_KEY);
return GooglePlayServicesUtil.getErrorDialog(
errorCode, getActivity(), REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
Log.i(TAG, "Dialog dismissed");
}
}
}
I am a beginner in android and I am trying to learn how to use intent.
In my code, I am trying to send 2 integers to a different activity and perform some calculation and return back in the Main activity with the answer.
This is my main activity and with a click of a button it should send 10, 50 to my calculate class and from there I will click operator buttons like add, multiply, divide and send back the answer here in main activity.
So far I am able to received these numbers to my Calculate class and perform operation there but I am not sure how to get back here in main activity with the answers.
Main Activity
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(getIntent() != null){
String msg = getIntent().getStringExtra("MSG");
int result = getIntent().getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivity(i);
}
}
Calculate class
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent i = new Intent(this, MainActivity.class);
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
}
}
you can use startActivityForResult and onActivityResult methods. fist in main activity you call startActivityForResult that means you want to get result from secondActivity (Calculate activity) and then override onActivityResult in main activity to get result.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(getIntent() != null){
String msg = getIntent().getStringExtra("MSG");
int result = getIntent().getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivityForResult(i, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
}
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent returnIntent = Intent(this, MainActivity.class);
returnIntent.putExtra("result",calc );
setResult(RESULT_OK,returnIntent);
finish();
}
}
public class Calculate extends Activity{
private int calc;
private int first;
private int second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent i = getIntent();
if(getIntent() != null){
String msg = i.getStringExtra("MSG");
first = i.getIntExtra("first", 0);
second = i.getIntExtra("second", 0);
Toast.makeText(this, "" + msg + first + " and " + second, Toast.LENGTH_LONG).show();
}
}
public void add(View v){
calc = first + second;
Intent i = new Intent(this, MainActivity.class);
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
startActivity(i);
}
}
You need a startActivity(i); in add() function.
You can do this by
onActivityResult()
method of android intent.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(data.getExtras().containsKey("widthInfo")){
width.setText(data.getStringExtra("widthInfo"));
}
if(data.getExtras().containsKey("heightInfo")){
height.setText(data.getStringExtra("heightInfo"));
}
}
See these links for more info:
http://developer.android.com/training/basics/intents/result.html
http://www.java2s.com/Code/Android/UI/CheckActivityresultandonActivityResult.htm
http://www.mybringback.com/android-sdk/12204/onactivityresult-android-tutorial/
It looks like you should be using startActivityForResult() here.
So, in your MainActivity, your onClick() would be modified to call startActivityForResult():
public void onClick(View v){
Intent i = new Intent(this, Calculate.class);
i.putExtra("MSG", "Receive two numbers : ");
i.putExtra("second", 10);
i.putExtra("first", 50);
startActivityForResult(i, 100); //modified
}
Then in MainActivity, you would also add onActivityResult to get the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK){
String msg = data.getStringExtra("MSG");
int result = data.getIntExtra("result", 0);
Toast.makeText(this, "" + msg + result, Toast.LENGTH_LONG).show();
}
}
Then, in the Calculate Activity, you would calculate the result, and send it back to MainActivity in an Intent, which will send the the MSG and result to onActivityResult() in MainActivity:
public void add(View v){
calc = first + second;
Intent i = new Intent(); //modified
i.putExtra("MSG", "Answer");
i.putExtra("result",calc);
setResult(RESULT_OK,i); //added
finish(); //added
}
Note that the reason it would be better for you to use startActivityForResult() here is that it would prevent having to add multiple Activities onto the back stack.
Say for example, you do two calculations (two trips from MainActivity to Calculate and back).
If you just used startActivity(), your back stack would then look like this:
MainActivity->Calculate->MainActivity->Calculate->MainActivity
And, it would just keep growing the more calculations you do.
Using startActivityForResult(), you are always just adding an instance of Calculate to the back stack, and then popping it and returning to the same instance of MainActivity. So, your back stack would always be just:
MainActivity
or...
MainActivity->Calculate
depending on which Activity you are currently in. As you can see, this is a huge improvement over the first option, which just keeps growing as you do more calculations.
I have passed a ResultReceiver from my Activity to my Service.
Activity code example to pass the ResultReceiver to my service so the service can make a callback to the Activity:
ResultReceiver receiver = new ResultReceiver(new Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
//process results
}
}
Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);
context.startService(instructionServiceIntent);
InstructionService code example:
protected void onHandleIntent(Intent intent) {
Bundle parameters = intent.getExtras();
ResultReceiver resultReceiver = parameters.getParcelable("receiver");
resultReceiver.send(METHOD_STATUS_RUNNING, Bundle.EMPTY);
}
Now, this works fine as when I call the resultReceiver.send method in my service, the corresponding onReceiveResult method in the activity is executed.
My question is, how does this work? As far as I understand, the ResultReceiver is being passed from the activity to the service as a Parcelable, which means its a "copy" of that object, and not a reference to the original ResultReceiver object which was created in the Activity. Therefore, how can a call to the send method on the copy of the ResultReceiver in the service class, make it so that the original ResultReceiver object in the activity runs it's onReceiveResult method?
ResultReciver implements Parcelable so it can be passed in an intent.
For the startservice it's easier just to load the intent used to start the service with data just like an intent sent to an activity then in the service process the intent data in onStartComand();
If you want to send messages back in forth to a service you should bind to the service startboundservice and in the service return a handler in onBind() to the activity.
This is where the magic of ResultReceiver works. It's just a message that has prepopulated handler so it can be serialized and passed back.
If you just want to get a reply from some fragment class that you create on the fly or something out of the norm actually serialize a callback you can pass in a message populated with the handler that will process the message.
Below I create a handler then create a message with the handler. Then I start a fragment that does something obscure and finally returns the message. So ineffect the message is just a copy but it is actually a callback that is passed in a bundle.
This is new code so I don't know how stable it is...
public void get_UserEmail(final MyGooglePlayCallback userEmailCallback) {
//handle message gets called when the fragment calls msg.sendToTarget()
//
class JX implements Handler.Callback {
#Override
public boolean handleMessage(Message msg) {
Bundle b = msg.getData();
String s = "";
if (b != null) {
s = b.getString("email");
}
msg.recycle();
userEmailCallback.onComplete(s);
return true;
}
}
JX jx = new JX();
Handler h = new Handler(jx);
final Message msg = Message.obtain(h);
MyGooglePlayCallback cb;
// start the account picker to get the email
String[] accountTypes = new String[]{"com.google"};
Intent intentx = AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);
MyFragmentActivityForResult2 f = MyFragmentActivityForResult2.newInstance(
intentx, REQUEST_CODE_PICK_ACCOUNT, msg);
FragmentTransaction fragmentTransaction = fragManager
.beginTransaction();
fragmentTransaction.add(f, "xx" + REQUEST_CODE_PICK_ACCOUNT);
fragmentTransaction.commit();
}
public static class MyFragmentActivityForResult2 extends Fragment {
private Message msg;
private int requestCode;
private Intent intent;
static MyFragmentActivityForResult2 newInstance(Intent intent, int requestCode,
Message message) {
MyFragmentActivityForResult2 f = new MyFragmentActivityForResult2();
Bundle args = new Bundle();
args.putInt("requestCode", requestCode);
args.putParcelable("message", message);
args.putParcelable("intent", intent);
f.setArguments(args);
return f;
}
MyFragmentActivityForResult2() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Bundle b = this.getArguments();
requestCode = b.getInt("requestCode");
msg = b.getParcelable("message");
intent = b.getParcelable("intent");
startActivityForResult(intent, requestCode);
}
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == this.requestCode) {
String mEmail = "";
if (resultCode == Activity.RESULT_OK) {
mEmail = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
}
Bundle b = new Bundle();
b.putString("email", mEmail);
msg.setData(b);
msg.arg1 = requestCode;
msg.arg2 = resultCode;
msg.sendToTarget();
}
fragManager.beginTransaction().remove(this).commit();
}
}
I am trying to save some data in "MainActivity" when switching to another activity, and restoring that data as I switch back to it.
In "MainActivity": (restoring data)
protected void onCreate(Bundle savedInstanceState) {
// do usual stuff
restoreData();
}
In "MainActivity": (switching to "StatusActivity"):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivity(intent);
In "StatusActivity":
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
startActivity(intent);
My saveData() function:
private Bundle saveData() {
Log.d(TAG, "Started saving state");
Bundle data = new Bundle();
// store stuff in the bundle
return data;
}
My restoreData() function:
private void restoreData() {
Log.d(TAG, "Started restoring state");
Bundle data = getIntent().getExtras();
// restore stuff in the bundle
}
LogCat:
My bundle is fine when sending to StatusActivity:
Sending data to status activity intent:
Bundle[{obj0=Bundle[{timeSinceLastPooped=3224, hunger=5,
id=2130837505, timeSinceLastHungerUpdate=3224,
timeSinceLastFed=0, timeSinceLastHappinessUpdate=3224,
timeSinceLastEvolution=3224, posY=0.0, posX=0.0,
isDead=false, happiness=5, evolutionStage=0, type=pet}],
time=7.794168E7}]
But then sending back to MainActivity:
Sending data to main activity intent: Bundle[mParcelledData.dataSize=648]
What do I do with mParcelledData to get the original bundle back? Thanks!
Answer:
In "MainActivity": (restoring data)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == 1) {
if(resultCode == RESULT_OK) {
restoreData(intent);
}
}
}
In "MainActivity": (switching to "StatusActivity"):
Bundle data = saveData();
Log.d(TAG, "Sending data to status activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), StatusActivity.class);
intent.putExtras(data);
startActivityForResult(intent, 1);
In "StatusActivity":
Bundle data = getIntent().getExtras();
Log.d(TAG, "Sending data to main activity intent: " +data);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtras(data);
setResult(RESULT_OK, getIntent());
finish();
You can use onRestoreInstanceState() witch is called after onStart(), whereas onCreate() is called before onStart().
Use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putInt("value", value);
}
And restore the value in onCreate():
public void onCreate(Bundle bundle) {
if (bundle!= null){
value = bundle.getInt("value");
}
}