Android的保存和恢复活动上下文或布局数据
问题描述:
我有一个设计活动中,用户可以像添加文字,并添加图片这么多东西。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
}
答
要持久保存数据,您可以使用SharedPreferences。这允许您将保存数据作为键值对。看看https://developer.android.com/training/basics/data-storage/shared-preferences.html
注意SharedPreferences只能处理一组有限的数据类型。
共享首选项可以存储int,string。我可以将整个活动状态存储为共享首选项吗? –
你的状态也只是一个数据包,对吧?因此,即使您需要存储更复杂的数据,您也可以使用Gson(https://github.com/google/gson)将json表示中的对象转换并保存。 – Headcracker
我在尝试转换上下文时遇到此错误。 E /的MessageQueue-JNI:java.lang.SecurityException异常:不能让方法构造访问 –