Reputation: 822
This might be more of a pure CS question, but I am having a trouble understanding how SHARED PREFERENCES
works in the context of saving and resuming an application when saving Objects in GSON
Format.
When you save GSON to Shared Preferences, is the GSON Strings themselves the only things that are saved (ie. the objects are lost)?
And if this is true, when you resume the application, how are the objects retrieved ?
Are they re-instantiated with the GSON data or does the GSON data store a location in memory within itself, or is the Shared Preferences the overall location stored in memory?
For example,
Context
TaskManager.java
class TaskManager {
String managerName;
LinkedList<Task> taskList = new LinkedList<Task>();
}
Task.java
class Task {
String taskName;
int Time;
}
FooBarActivity.java
class FooBarActivity extends Activity {
TaskManager manager = new TaskManager("manager1")
Task newTask = new Task("task1");
manager.taskList.add(newTask);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(manager);
prefsEditor.putString("manager", json);
prefsEditor.commit();
}
manager object JSON:
{"manager":[
{"name":"manager1"
"taskList":"[task1]"}
]}
Is that task1 element of the List:
Upvotes: 0
Views: 723
Reputation: 39846
You're making a big confusion of very distinction stuff.
note that JSON and GSON have very little to do with Android. One is a data representation format and the other is a Java library.
Now that we have some basic concepts laid out, let's check your questions:
prefsEditor.putString("manager", json);
this line is only getting a string and saving it into the SharedPreferences.Editor. Nothing more.
at some point you'll have to code String json = prefs.getString("manager", null);
and the only thing this line is to get a String from the SharedPrefenreces (if it exists).
and later on when you code TaskManager manager = gson.fromJson(json, TaskManager.class);
, this is creating a NEW TaskManager
object that have the same managerName
and that the taskList
contains Task
s objects with the same taskName
and time
as the previous tasks objects you had before. But those are all new objects.
I hope it's more clear.
Upvotes: 1