2012-09-30 98 views
0

每當我按下後退按鈕,我的應用程序不會調用onSaveInstanceState(),我無法保存數據。我試圖製作一個調度程序應用程序,我需要保存已經設置的時間表,即使在我按下後退按鈕後也是如此。我想通過從源文件向stringArray添加新數據來動態編輯ListView。我遇到的問題是文件schedules.txt沒有保存。每當程序打開一個新的活動,該文件現在是空白的。如何永久保存數據,以便以後在Android中訪問它?

這是我的代碼至今:

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

    setContentView(R.layout.activity_schedules); 
    ListView listview = (ListView) findViewById(R.id.scheduleListView); 
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, schedulesList); 
    listview.setAdapter(adapter); 
    Log.v("myapp", "currentlist of files associated with this program are: " + fileList()); 

    try { 

     FileOutputStream fout = openFileOutput("schedules.txt", MODE_PRIVATE); 
     Log.v("myapp", "FileOutputStream ran"); 

    } catch (FileNotFoundException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

try { 
     Log.v("myapp", "first get old schedules call"); 
     getOldSchedules(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 


public void editFile(String format) throws IOException { 

    Log.v("myapp", "editFile ran"); 
    FileOutputStream fout = openFileOutput("schedules.txt", MODE_PRIVATE); 
    OutputStreamWriter writer = new OutputStreamWriter(fout); 

    writer.write("hello alex"); 
    writer.flush(); 
    writer.close(); 
    Log.v("myapp", "secondary getoldschedules call"); 
    getOldSchedules(); 
} 

public void getOldSchedules() throws IOException{ 

    FileInputStream fis = openFileInput("schedules.txt"); 
    InputStreamReader reader = new InputStreamReader(fis); 

    char[] inputbuffer = new char[32]; 
    reader.read(inputbuffer); 
    String data = new String(inputbuffer); 
    Log.v("myapp", "data in file reads: " + data); 

    reader.close(); 


} 
+0

您可能有興趣使用SQLite。不錯的教程:[SQLite數據庫和ContentProvider](http://www.vogella.com/articles/AndroidSQLite/article.html) – nkr

回答

1

據正如我所知,保存代碼沒有任何問題。 onSaveInstanceState沒有被調用的原因是因爲在這種情況下它是錯誤的工具。該方法只有在系統殺死一個活動時纔會調用該方法,目的是將其還回。從Android文檔:

一個實例時的onPause()和的onStop()被調用,而不是此方法是當一個用戶從活動乙導航回活動A的:沒有必要調用的onSaveInstanceState(包),因爲該特定實例永遠不會被恢復,所以系統避免了調用它。

使用後退按鈕離開Activity是上述場景的一個示例 - 活動正在銷燬,所以狀態不需要保存以供以後恢復。 onSaveInstanceState專爲小UI用戶設計,比如複選框中有檢查項,或者輸入字段中的文本 - 不是持久性數據存儲。您應該考慮將保存呼叫存入(如果很快),onStoponDestroy

相關問題