0

I'm trying to save an Intent object to SharedPreferences and the result code from onActivityResult() so I can use it later. I have already tired to store it as a json using Gson, but there is data loss. I have also tried to save it as uri, but the Intent.toURi() method returns empty string or a string that is not complete. Is there any other way to save it than as a string ? The intent has extras and I need to save all of its data, not just some parts of it.

This is what I've tried for storing it as uri:

SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
String uriString = data.toUri(0);
editor.putString("SavedIntentData", uriString);
editor.putInt("SavedResultCode", resultCode);
editor.apply();

and for restoring it:

SharedPreferences settings = getSharedPreferences(PREFERENCES, 0);
String intentData = settings.getString("SavedIntentData", null);
int resultCode = settings.getInt("SavedResultCode", 0);
if(resultCode !=0 && intentData != null) {
    data = Intent.parseUri(intentData, 0);
}

And for json:

String intentData = new Gson().toJson(data);

to restore it:

data= new Gson().fromJson(intentData, Intent.class);
andreea
  • 9
  • 1
  • Maybe post some code? – Darshan Aug 02 '22 at 07:49
  • Please provide enough code so others can better understand or reproduce the problem. – Community Aug 02 '22 at 07:51
  • @DarShan sure :) – andreea Aug 02 '22 at 07:59
  • Possible duplicate [https://stackoverflow.com/questions/7145606/how-do-you-save-store-objects-in-sharedpreferences-on-android] – Mustufa Ansari Aug 02 '22 at 08:09
  • @MustufaAnsari my problem is that i get data loss using Gson to retrieve the intent object from shared pref. it works just fine with any other object type, but there is a problem with intent, and i've also seen other people complaining about this. – andreea Aug 02 '22 at 08:34
  • `String uriString = data.toUri(0);` You want a string and toUri() will deliver an uri. So what is it hat you get? You should save Uri.toString() to be clear. Please post complete onActivityResult. – blackapps Aug 02 '22 at 12:29
  • `This is what I've tried for storing it as uri:` No you are not savin an Uri instance. You are saving a String. Which is ok.. – blackapps Aug 02 '22 at 12:31
  • `data = Intent.parseUri(intentData, 0);` ???? Better: `Uri uri = Uri.parse(intentData);` – blackapps Aug 02 '22 at 12:33
  • `editor.putString("SavedIntentData", uriString);` Change to `editor.putString("uristring", uriString);` to make your code readable. – blackapps Aug 02 '22 at 12:35

0 Answers0