2010-10-25 69 views
3

文檔 http://developer.android.com/guide/topics/data/data-storage.html保存控件狀態

表明,有多種方式來保存數據,我需要做的這一個部件,每次我試圖挽救我得到的錯誤...

例如

 SharedPreferences settings = getSharedPreferences("NAME", 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putBoolean("silentMode", false); 

     // Commit the edits! 
     editor.commit(); 

錯誤

Description Resource Path Location Type 
The method getSharedPreferences(String, int) is undefined for the type AWidget 

另一嘗試:

 String FILENAME = "hello_file"; 
    String string = "hello world!"; 

    FileOutputStream fos = openFileOutput("Test.txt", Context.MODE_PRIVATE); 
    fos.write(string.getBytes()); 
    fos.close(); 

錯誤

Description Resource Path Location Type 
The method openFileOutput(String, int) is undefined for the type AWidget 

什麼交易?我發現沒有提到這在小部件中不起作用,那麼爲什麼這些示例不適合我?

保存這些數據的首選方法是什麼?

+2

AWidget的基本類型是什麼? – xandy 2010-10-25 03:54:03

+0

正如@ xandy所說的,瞭解您所在班級的類型很重要。 'getSharedPreferences()'在'Context'類中定義。 – 2010-10-25 05:12:15

回答

2

所以問題是,我不能只使用這個功能沒有實質上述代碼將工作正常,如果我與上下文做。在它的面前......

SharedPreferences settings = context.getSharedPreferences("NAME", 0); 
     SharedPreferences.Editor editor = settings.edit(); 
     editor.putBoolean("silentMode", false); 

     // Commit the edits! 
     editor.commit(); 

因此,大家可以看到這是所有是需要得到共享偏好...以及與此...

INT [] allids = AppWidgetManager .getInstance(context) .getAppWidgetIds(new ComponentName(context,AwarenessWidget.class));

我可以讓我的應用程序的所有ID和呼叫的onupdate和更新基於保存的喜好

如果有人需要,我可以更詳細每個那些意見...

Baffels我沒有人能夠找出那個並幫助我!現在看起來很直截了當!

1

我想如果你想保存一個特定的小部件的狀態,最好使用View框架中保存的狀態機制。 SharedPreferences對應用程序來說是全局的。因此,如果您有兩個AWidget實例,那麼在運行時就很難在兩者之間進行區分。

相反,你可能希望覆蓋:

onRestoreInstanceState(Parcelable狀態)

的onSaveInstanceState()

如果保存爲您的瀏覽啓用後,Android的應調用的onSaveInstanceState()在您的小工具將有有機會返回一個Parcelable,它可以在稍後在onRestoreInstanceState()中使用以恢復啓動的地方。

+0

我需要做的就是將一個小部件ID與一個int(它傳遞給函數)相關聯,我不需要保存視圖的狀態...只是想保存當手機重新啓動時設置爲背景的那張圖片 – morty346 2010-10-25 12:13:49

+1

我想也許我不知道你說了什麼,但是這是一個小部件,一個小部件沒有onSaveInstanceState – morty346 2010-10-26 00:28:13

+0

這就是爲什麼其他人要求因爲我們無法理解這是什麼意思。我假設你正在UI模塊或視圖中使用單詞部件。我假設你的意思是Application Widget。如果你想得到更準確的答案,請發佈更多的代碼或給更多的上下文 – 2010-10-26 16:59:45