0

我已经通过关于该主题的保存前景活性会被破坏前的状态本文档...状态的应用程序后,2转

,一切现在工作真的很好(设备旋转后),但是当我的旋转后,再次转动我的设备,我会再失去我的数据:(

这里是我的代码

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    final MainActivity activity = this; 
    activity.setTitle("Cow Counter"); 

    TextView QntyResultField = findViewById(R.id.textView); 
    QntyResultField.setText(Integer.toString(cowQnty)); 
} 

// invoked when the activity may be temporarily destroyed, save the instance state here 
@Override 
public void onSaveInstanceState(Bundle outState) { 
    super.onSaveInstanceState(outState); 
    outState.putInt("qnty", cowQnty); 
} 

// How we retrieve the data after app crash... 
@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 
    //cowQnty = savedInstanceState.getInt("qnty"); 

    TextView QntyResultField = findViewById(R.id.textView); 
    QntyResultField.setText("Cows: "+Integer.toString(savedInstanceState.getInt("qnty"))); 
} 

我认为解决方案将可能实现一个检查,如果一个实例的状态已经恢复之前...

我已经试过那么这个位置:

if(savedInstanceState.getInt("qnty") != 0){ 
    TextView QntyResultField = findViewById(R.id.textView); 
    QntyResultField.setText("Cows: "+Integer.toString(savedInstanceState.getInt("qnty"))); 
} 

BUIT然后我在我的onCreate()inital部件的方法,将在我的结果字段写入零

TextView QntyResultField = findViewById(R.id.textView); 
QntyResultField.setText(Integer.toString(cowQnty)); 

谁能告诉我,如果我接近解决方案?

回答

1

您使用一种称为cowQnty变量来存储,然后保存在包您onSaveInstanceStateoutState.putInt("qnty", cowQnty);,那么当你在onRestoreInstanceState恢复它,你只设置TextView的值检索到的价值的价值,不更新值为cowQnty

您如何期待再次保存空白字段?有两种解决方案;

首先,如果cowQnty不是一个相当大的金额,你不介意使用的RAM一点点,让cowQnty一个static场,它会持续的数据,而无需将其保存在一个Bundle可言。

其次,刚刚成立cowQnty的价值,当你恢复状态(你为什么把它注释掉?),像这样再次:对我

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 
    cowQnty = savedInstanceState.getInt("qnty"); 

    TextView QntyResultField = findViewById(R.id.textView); 
    QntyResultField.setText("Cows: "+Integer.toString(savedInstanceState.getInt("qnty"))); 
} 
+0

耻辱:( 我的想法和思考并认为....它的绝对清除>>我必须设置我的时间,当我恢复我的状态#ahhhhhh谢谢你这么多! – nbg15

+0

哈哈没问题!快乐编码:) – Mercato