我试图将onactivityresult返回的意图数据保存到SharedReferences,我使用gson对其进行序列化,然后反序列化,以便将其存储为字符串,我的代码在保存对象和应用程序运行时完美地保存和检索数据,但当我关闭应用程序时,再次启动它并尝试获取intent数据对象我没有得到与以前完全相同的东西,从调试器中我看到mparceleddata.datasize不一样。当代码工作时
当它不起作用的时候
除此之外,一切似乎都是一样的。
下面是我如何获得意图并将其存储到SharedReferences的方法:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != REQUEST_CODE && resultCode != RESULT_OK) {
Toast.makeText(this,
"Permission Denied", Toast.LENGTH_SHORT).show();
mToggleButton.setChecked(false);
}else if (requestCode == REQUEST_CODE && resultCode == RESULT_OK){
Toast.makeText(this,
"Permission granted, so save the intent", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = settings.edit();
Gson gson = new GsonBuilder().serializeNulls().create();
String dataS= gson.toJson(data);
editor.putString(PERMISSION_INTENT, dataS);
editor.putBoolean(PERMISSION_BOOLEAN,true);
editor.putInt(PERMISSION_CODE,resultCode);
editor.commit();
}
}
下面是我如何检索意图的
myButton.setOnClickListener(v -> {
String intentStored= settings.getString(PERMISSION_INTENT, null);
Gson gson = new GsonBuilder().serializeNulls().create();
int mResultCode = settings.getInt(PERMISSION_CODE,0);
gotPermission = settings.getBoolean(PERMISSION_BOOLEAN,false);
Intent mData = gson.fromJsonintentStored= Intent.class);
});
这是我的参考资料
private SharedPreferences settings;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
mToggleButton = (ToggleButton) findViewById(R.id.toggle);
recordButton = findViewById(R.id.record_btn);
settings = getApplicationContext().getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
暂无答案!
目前还没有任何答案,快来回答吧!