I'm having this peculiar problem in Android studio. I made this simple app, to understand screen rotation. I understand the concept when the screen rotates the Activity gets destroy, and recall the onCreate method. For you to save data you have to put it in a Bundle by Overriding the onSaveInstanceState method. I made an app with 2 buttons and a number in the middle. the number will change depending on what button is click. But for some reason, when I rotate the screen the number reset, but still kept the value it was on before the screen got to rotate. For Example, if I set the number to 5, and I rotate the screen the number goes to zero, but if I increase it, it goes to 6 if I decrease it goes 4. Somehow it still kept its value but reset to zero, I don't know why. Here's the code
package com.example.android.application;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button upButton, downButton;
TextView amount;
int change;
private static final String banza = "Bundle";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
change = savedInstanceState.getInt(banza);
}
upButton = (Button) findViewById(R.id.activity_main_up_button);
downButton = (Button) findViewById(R.id.activity_main_down_button);
amount = (TextView) findViewById(R.id.activity_main_textview_id);
upButton.setOnClickListener(this);
downButton.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == upButton) {
change++;
amount.setText(Integer.toString(change));
}
if (view == downButton) {
change--;
amount.setText(Integer.toString(change));
}
}
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(banza, change);
}
}
You missed the code of
amount.setText(Integer.toString(change));
in onCreate that's why it don't show value while rotating but have correct value when you increment or decrement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.