我已经测试了所有内容,并花了最后3个小时来修复此错误。我不为什么,但是我的应用程序从textView删除了所有数据。我做了onSaveInstance和onRestore,但这是同样的问题。
我知道我可以通过onCreate解决此问题,但我不是我真正需要做的。
public class MainActivity extends AppCompatActivity {
EditText et_min,et_max;
Button button;
TextView tv_output;
Random r;
int min, max, output;
static final String OUT_PUT = "output";
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (output!= 0){
savedInstanceState.putInt(OUT_PUT, 0);
}
super.onSaveInstanceState(savedInstanceState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
output = savedInstanceState.getInt(OUT_PUT);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r = new Random();
et_max = (EditText) findViewById(R.id.et_max);
et_min = (EditText) findViewById(R.id.et_min);
button = (Button) findViewById(R.id.button);
tv_output = (TextView) findViewById(R.id.tv_output);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String tempMin, tempMax;
tempMin = et_min.getText().toString();
tempMax = et_max.getText().toString();
if (!tempMin.equals("") && !tempMax.equals(""))//ovde stavljam ih u poziciju gde su slobodni za pisanje
min = Integer.parseInt(tempMin);
max = Integer.parseInt(tempMax);//ova dva sluze kako bi pretvorili stringove u intove za potrebe dole methoda
if (max > min) {
output = r.nextInt((max - min) + 1) + min;//nextInt sluzi kako bi dao random broj izmedju dva broja u ovom slucaju min i max
tv_output.setText("" + output);
}
}
});
}
}
答案 0 :(得分:1)
是的,您需要使用onSaveInstanceState
。此方法将保存您的textViews或其他内容中的变量。在您的情况下,您需要像findViewById
和onSaveInstanceState
中的onRestoreInstanceState
那样声明视图。您可以尝试执行以下操作,此代码有效:
public class MainActivity extends AppCompatActivity {
Button Btn;
TextView textView;
String cnt = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Btn = (Button) findViewById(R.id.button);
}
public void onBtnClick(View view) {
textView = (TextView) findViewById(R.id.textView);
textView.setText("Hehe");
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
textView = (TextView) findViewById(R.id.textView);
cnt = (String) textView.getText();
outState.putString("count", cnt);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
cnt = savedInstanceState.getString("count");
textView = (TextView) findViewById(R.id.textView);
textView.setText(cnt);
}
}