2017-06-01 61 views
1

我想將值保存在我的ProgressBar中,因此如果關閉應用程序(終止它)並再次運行它,則會再次顯示相同的值。我通過使用sharedpreferences嘗試了這一點,但它仍然沒有保存,我不知道如何解決它。我查了一下在互聯網上可以找到的所有東西,但它總是保持非常簡單,比如「如何將一個entertext保存爲txt/xml」,但這不是我正在尋找的。保存我的ProgressBar的當前狀態

protected void onPause(){ 
    super.onPause(); 
    fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar); 
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
    incFuel = sharedPref.getInt(FUELBAR, fuelBar.getProgress()); 
    fuelBar.setProgress(incFuel); 
} 

public void onResume(){ 
    super.onResume(); 
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPref.edit(); 
    editor.putInt(FUELBAR, fuelBar.getProgress()); 
    editor.commit(); 
} 

public void onStop(){ 
    super.onStop(); 
    fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar); 
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
    incFuel = sharedPref.getInt(FUELBAR, fuelBar.getProgress()); 
    fuelBar.setProgress(incFuel); 
} 

在我的onCreate我也有這些變量聲明

SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 

在我的MainActivity

int incFuel = 0; 
final String FUELBAR = "fuelBar"; 

SharedPreferences sharedPref; 
SharedPreferences.Editor editor; 

我真的不是一個單一的線索,我錯過了什麼,並會高度讚賞一些幫助。

+0

我只能看到你的SharedPreference對象上的調用。你曾經打電話過「得到」嗎? – tobifasc

+0

我編輯了代碼,請再看一遍。 –

回答

1

我可以看到一些問題。

  1. 首先,不需要你onStop(),作爲和onResume就足夠了。您的和onResume是相反的。 (onResume在活動加載後調用,onPause在活動關閉時發生)

  2. 您還需要使用加載的值設置進度。

下面的代碼應該指向正確的方向。

protected void onPause(){ 
    super.onPause(); 
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPref.edit(); 
    editor.putInt(FUELBAR, fuelBar.getProgress()); 
    editor.commit(); 

} 

public void onResume(){ 
    super.onResume(); 
    fuelBar = (ProgressBar) findViewById(R.id.fuelProgressBar); 
    SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE); 
    incFuel = sharedPref.getInt(FUELBAR, 0); 
    fuelBar.setProgress(incFuel); 
} 

public void onStop(){ 
    super.onStop(); 
} 
+1

gr8 thx爲解釋它真的幫助和程序正在完善現在。 –