当我更改为横向模式时,我想保存信息,我编写了这段代码,但是当我启动程序时它会显示 ResourceNotFoundException ,为什么?
public class ActivityB extends AppCompatActivity {
int value = 0;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_b);
text = (TextView) findViewById(R.id.textView);
Button b = (Button) findViewById(R.id.button);
//Toast.makeText(this," svd : "+savedInstanceState,Toast.LENGTH_LONG).show();
if (savedInstanceState != null) {
value = savedInstanceState.getInt("count");
text.setText("" + value); // here is the Error! why ?
}
}
public void Incrementation(View view) {
value++;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", value);
}
}
LOG
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.othma.udemy/com.example.othma.udemy.ActivityB}: android.content.res.Resources$NotFoundException: String resource ID #0x6*
答案 0 :(得分:0)
首先,您需要正确处理onCreate中的逻辑。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_b);
text = (TextView) findViewById(R.id.textView);
Button b = (Button) findViewById(R.id.button);
//Toast.makeText(this," svd : "+savedInstanceState,Toast.LENGTH_LONG).show();
if (savedInstanceState != null) {
value = savedInstanceState.getInt("count"); // here where we retrieve back the value
} else {
text.setText("" + value); //first time init savedInstanceState will be null
}
}
我认为您也需要对此重新排序。
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("count", value); // used to store data before pausing the activity.
super.onSaveInstanceState(outState);
}
希望有帮助!