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