2013-11-10 64 views
0

我試圖做出反擊,並試圖當你離開應用程序保存當前的價值,所以我試圖用onSaveInstanceStateonRestoreInstanceState,但它似乎沒有工作和的onSaveInstanceState似乎onRestoreInstanceState無法工作

代碼如下

package com.example.taekwondobuddy.util; 

import android.app.Activity; 

import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

public class Counter extends Activity { 

int counter; 
Button add; 
Button sub; 
TextView display; 


public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.counter); 

    counter = 0; 
    add = (Button) findViewById(R.id.button1); 
    sub = (Button) findViewById(R.id.button2); 
    display = (TextView) findViewById(R.id.tvDisplay); 
    add.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      counter++; 
      display.setText("Counter: " + counter); 
     } 
    }); 
    sub.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      counter--; 
      display.setText("Counter: " + counter); 
     } 
    }); 
} 

public void onSaveInstanceState(Bundle savedInstanceState) { 
     super.onSaveInstanceState(savedInstanceState); 


     savedInstanceState.putInt("counter", counter); 


    } 

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) { 
    super.onRestoreInstanceState(savedInstanceState); 


    counter = savedInstanceState.getInt("counter"); 

    } 



    } 

這是我第一次,我overring savedInstanceState,所以我在想,如果語法是正確的,我我用正確的方式?如果有的話,我的代碼有什麼問題?幫助和提示將不勝感激

+0

http://stackoverflow.com/questions/6525698/how-to-use-onsavedinstancestate-example-please已經是這個東西是這裏的例子.. –

回答

2

您需要交換方法中的順序,因爲父節點的實現方法將從方法返回並且代碼不會運行。此外,您需要檢查onRestoreInstanceState中的參數是否爲空。

public void onSaveInstanceState(Bundle savedInstanceState) { 
    savedInstanceState.putInt("counter", counter); 
    super.onSaveInstanceState(savedInstanceState); 
} 

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) { 
    if (savedInstanceState != null) { 
     counter = savedInstanceState.getInt("counter"); 
    } 
    super.onRestoreInstanceState(savedInstanceState); 
} 

您也說

我試圖做出反擊,並試圖當你離開應用程序

保存實例狀態僅適用於保存當前值當應用程序在內存中時(儘管應用程序不會刪除它)。如果它被殺死了,國家將會失去。

+0

我工作時,我帶着家離開,但當我推回去時(這是菜單的一部分,忘記說了),它沒有保存實例 – user2809321

1

你不需要onRestoreInstanceState()。這在onCreate()之後被調用,並且對於需要onCreate()中的數據的應用程序通常是毫無價值的。您想要在傳遞Bundle的onCreate()中檢索已保存的狀態。

在的onCreate():

counter = 0; 
if (savedInstanceState != null) { 
    counter = savedInstanceState.getInt("counter", 0); 
} 
相關問題