2017-10-13 67 views
0

我有一個設計活動中,用戶可以像添加文字,並添加圖片這麼多東西。Android的保存和恢復活動上下文或佈局數據

現在我需要給一個選項,他們的工作保存爲草稿,所以他們的背景/相對佈局被轉換成數據並保存到一些文件,它甚至可以應用收盤後進行檢索。

我不能使用和的onSaveInstanceState作爲onRestoreInstanceState我有同樣活動的許多實例。

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) 
{ 
// Always call the superclass so it can save the view hierarchy state 
    super.onSaveInstanceState(savedInstanceState); 
} 

@Override 
public void onRestoreInstanceState(Bundle savedInstanceState) 
{ 
// Always call the superclass so it can restore the view hierarchy 
    super.onRestoreInstanceState(savedInstanceState); 

} 

所以需要不同的方法,我可以在保存按鈕點擊和實例狀態存儲與鍵後單擊編輯按鈕,並通過將一個關鍵

但需要得到相同的實例與像下面的東西

public void onSaveButtonClick(Bundle savedInstanceState, Sting Key) 
{ 
    // save the activity to bundle with key and convert the bundle as data to store 
} 

public void onRestoreButtonClick(Bundle savedInstanceState, Sting Key) 
{ 
    // convert the data to bindle and start the activity with restored bundle 

} 

回答

0

要持久保存數據,您可以使用SharedPreferences。這允許您將保存數據作爲鍵值對。看看https://developer.android.com/training/basics/data-storage/shared-preferences.html

注意SharedPreferences只能處理一組有限的數據類型。

+0

共享首選項可以存儲int,string。我可以將整個活動狀態存儲爲共享首選項嗎? –

+0

你的狀態也只是一個數據包,對吧?因此,即使您需要存儲更復雜的數據,您也可以使用Gson(https://github.com/google/gson)將json表示中的對象轉換並保存。 – Headcracker

+0

我在嘗試轉換上下文時遇到此錯誤。 E /的MessageQueue-JNI:java.lang.SecurityException異常:不能讓方法構造訪問 –