Gson & SharedPreferences lead to a NullPointerException - java

I'm trying to put an ArrayList of self-created objects in SharedPreferences. While the saving seems to work, I get the following error when getSharedPreferences() is called:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object com.google.gson.Gson.fromJson(java.lang.String, java.lang.reflect.Type)' on a null object reference
The code where I put it into SharedPreferences:
// FYI: gson = new Gson(); is set earlier on
// same goes for: ArrayList<MovieModel> movieModelList = new ArrayList<>();
// and: Type listType;
movieModelList.add(result);
String jsonMovieModelList = gson.toJson(movieModelList);
SharedPreferences prefs = getSharedPreferences("settings",
MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("jsonMovieModelList", jsonMovieModelList);
editor.apply();
And the SharedPreferences class:
public void getSharedPreferences() {
SharedPreferences prefs = getSharedPreferences("settings",
MODE_PRIVATE);
String jsonMovieModelList = prefs.getString("jsonMovieModelList", null);
Log.d("TAG", "Message" + jsonMovieModelList); // output is as expected
// if not filled in, no action necessary
if (jsonMovieModelList != null) {
listType = new TypeToken<ArrayList<MovieModel>>(){}.getType();
ArrayList<MovieModel> movieModelListSaved = gson.fromJson(jsonMovieModelList, listType);
MovieModel lastMovie = movieModelListSaved.get(movieModelListSaved.size() - 1);
showTitleSecond = (TextView)findViewById(R.id.show_title_2);
showTitleSecond.setText(lastMovie.getTitle());
}
}
The gson code is based on: https://google.github.io/gson/apidocs/com/google/gson/Gson.html
To be clear:
I do understand what a NullPointerException is, but I don't understand why I receive one in this situation since I check before executing that the String jsonMovieModelList is at least not null. Why is gson 'losing' the reference?
I look at this question: Android ArrayList of custom objects - Save to SharedPreferences - Serializable? and the only difference I see is that I have an ArrayList

Seems like you've not initialized variable gson before its usage in this method. Just add Gson gson = new GsonBuilder().create(); before the first usage, or in this method you're calling and that should fix it.

Related

ArrayList<Class> sharedpreferences

Is it any way to save ArrayList to sharedpreferences? Thank you
ArrayList<Class> activityList = new ArrayList<>();
activityList.add(Level1Activity.class);
activityList.add(Level2Activity.class);
activityList.add(Level3Activity.class);
activityList.add(Level4Activity.class);
activityList.add(Level5Activity.class);
I already answered this to your other question but just in case, I'll re-write it here and explain it more a bit.
You can use Gson to convert your list into a Json String so that you can save it in SharedPreferences.
You will need to add implementation 'com.google.code.gson:gson:2.8.6' inside your app gradle dependencies to be able to use Gson.
But, you cannot simply parse the list using Gson to Json or viceversa when you use the Class class. In order to do so, you will need to create your own serializer and deserializer for it. Or you'll face this exception:
java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: com.etc.etc.Level1Activity. Forgot to register a type adapter?
So let's create a custom adapter that implements JsonSerializer and JsonDeserializer. Don't forget to put inside the angle brackets the type we're working with, which is Class.
ClassAdapter class
public class ClassAdapter implements JsonSerializer<Class>, JsonDeserializer<Class> {
#Override
public JsonElement serialize(Class src, Type typeOfSrc, JsonSerializationContext context) {
// Get our class 'src' name
return new JsonPrimitive(src.getName());
}
#Override
public Class deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
// Get class
return Class.forName(json.getAsString());
} catch (ClassNotFoundException e) {
// If class could not be found or did not exists, handle error here...
e.printStackTrace();
}
return null;
}
}
To convert our list to Json String and save it inside SharedPreferences:
// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());
// Initialize our list of levels (ie. classes)
List<Class> classes = new ArrayList<>();
classes.add(Level1Activity.class);
classes.add(Level2Activity.class);
classes.add(Level3Activity.class);
classes.add(Level4Activity.class);
classes.add(Level5Activity.class);
// Create Gson from GsonBuilder and convert list to json
Gson gson = gsonBuilder.create();
String json = gson.toJson(classes);
// Save json to SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
sharedPreferences.edit().putString("levels", json).apply();
And to retrieve the list back:
// Retrieve json from SharedPreferences
SharedPreferences sharedPreferences = getSharedPreferences("app_name", MODE_PRIVATE);
String json = sharedPreferences.getString("levels", null);
// Handle here if json doesn't exist yet
if (json == null) {
// ...
}
// Create new GsonBuilder and register our adapter for Class objects
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Class.class, new ClassAdapter());
// Create Gson from GsonBuilder and specify type of list
Gson gson = gsonBuilder.create();
Type type = new TypeToken<ArrayList<Class>>(){}.getType();
// Convert json to list
List<Class> classes = gson.fromJson(json, type);
Hope this helps, happy coding!

Deserializing a List<MyInterface> that contains a List<MyOtherInterface> using Gson

I had huge problems deserializing a List<IWorkout>, since it would throw
java.lang.RuntimeException: Unable to start activity ComponentInfo{MY PACKAGE}: java.lang.RuntimeException: Unable to invoke no-args constructor for interface MY INTERFACE. Registering an InstanceCreator with Gson for this type may fix this problem.
But I solved it by deserializing it to a List<Workout> (which implements the interface IWorkout), and then adding it to a List<IWorkout>.
Code example of my solution :
public ArrayList <IWorkout> loadUserWorkoutList(){
Gson gson = new Gson();
Type workoutListType = new TypeToken<ArrayList<Workout>>(){}.getType();
List <Workout> workoutList = gson.fromJson(loadWorkoutDataFromSharedPreferences(), workoutListType);
if (workoutList == null){
workoutList = new ArrayList<>();
}
ArrayList<IWorkout> iWorkoutList = new ArrayList<>(workoutList);
return iWorkoutList;
}
But the problem now is that the Workout contains another List<IExercise> which I can't (or at least can't figure out how to) perform this "trick" on. The entire IWorkout list is serialized like this :
private String workoutListToJsonString(List<IWorkout> list) {
Gson gson = new Gson();
String jsonString = gson.toJson(list);
return jsonString;
}
and it throws the same error as before when I try to deserialize it.
Does anyone have any ideas on how to solve this?
I've tried using the adapter provided by Narthi, but to no success.
Thanks in advance

Gson deserialize the boolean JSON only with false, regardless to input

My object consists of five fields :
public class ConfigurationItem {
#SerializedName("show_interest")
boolean show_interest;
#SerializedName("bid_with_price")
boolean bid_with_price;
#SerializedName("anonymous_orders")
boolean anonymous_orders;
#SerializedName("orders_progress_status")
boolean orders_progress_status;
#SerializedName("orders_progress_messages")
boolean orders_progress_messages;
}
I parse this items from the web server and receive string like this :
{
"ordersProgressStatus":true,
"showInterest":false,
"anonymousOrders":true,
"bidWithPrice":true,
"ordersProgressMessages":true
}
I receive the JSON and save it to the SharedPreferences like this :
public static void saveCurrentConfiguration(Context mContext, JSONObject jsonObject ) {
SharedPreferences sharedPreferences = mContext.getApplicationContext().getSharedPreferences(Constants.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
prefsEditor.putString(Constants.SHARED_CURRENT_CONFIG, jsonObject.toString());
prefsEditor.apply();
}
But when I want to read the saved object :
public static ConfigurationItem getCurrentConfiguration(Context mContext)
{
SharedPreferences sharedPreferences = mContext.getApplicationContext().getSharedPreferences(Constants.SHARED_PREFS_NAME, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString(Constants.SHARED_CURRENT_CONFIG, null);
ConfigurationItem configurationItem = gson.fromJson(json, ConfigurationItem.class);
Log.i(TAG + " loaded config", configurationItem.toString());
return configurationItem;
}
in the configurationItem I get only false values. Besides, the read string from the SharedPreference is correct, but when I use Gson for deserialize, the object is filled with wrong values.
What can be the solution ?
When using the annotation #SerializedName this references the key value in the JSON string. So instead of doing #SerializedName("show_interest") to serialize the value from "showInterest" do #SerializedName("showInterest")
Using serialized name is handy when you don't want to tie the name of a JSON key to name of a field. For instance when you prefer to use the JAVA standaard convention of prefixing private field with m like private boolean mShowInterest; so when later you refactor the field name to something else you can do a easy refactor, or if the JSON key changes you on have to change the annotation.

How to save an arrayList<LatLng> with SharedPreferences

I was looking for this - but found only how to save an arrayList for example this code:
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();
I want to store this object(point) which is LatLng in SharedPreferences, after that i will need to get it from this save. Here is what i want to save:
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
mMap.addMarker(new MarkerOptions().position(point));
**checkPoints.add(point);**
}
Instead of using preferences you can use Sqlite database. But if you insist on using SharedPreferences then I don't think you have much choice as you can only store boolean, float, int, long, String or StringSet. The only possible way I see is that you concatenate all of the values with your own separator like
1123.4456:1234.223|1123.4456:1234.1233|1123.4456:1234.223|1123.4456:1234.223
and then just parse when retrieving it.

Android SharedPreferences Best Practices

In an application I have been building we rely on SharedPreferences quite a bit, this got me thinking about what is best practice when it comes to accessing SharedPreferences. For instance many people say the appropriate way to access it is via this call:
PreferenceManager.getDefaultSharedPreferences(Context context)
However it seems like this could be dangerous. If you have a large application that is relying on SharedPreferences you could have key duplication, especially in the case of using some third party library that relies on SharedPreferences as well. It seems to me that the better call to use would be:
Context.getSharedPreferences(String name, int mode)
This way if you have a class that heavily relies on SharedPreferences you can create a preference file that is used only by your class. You could use the fully qualified name of the class to ensure that the file will most likely not be duplicated by someone else.
Also based on this SO question: Should accessing SharedPreferences be done off the UI Thread?, it seems that accesses SharedPreferences should be done off the UI thread which makes sense.
Are there any other best practices Android developers should be aware of when using SharedPreferences in their applications?
I've wrote a little article that can also be found here. It describes what SharedPreferences is :
Best Practice: SharedPreferences
Android provides many ways of storing application data. One of those ways leads us to the SharedPreferences object which is used to store private primitive data in key-value pairs.
All logic are based only on three simple classes:
SharedPreferences
SharedPreferences.Editor
SharedPreferences.OnSharedPreferenceChangeListener
SharedPreferences
SharedPreferences is main of them. It's responsible for getting (parsing) stored data, provides interface for getting Editor object and interfaces for adding and removing OnSharedPreferenceChangeListener
To create SharedPreferences you will need Context object (can be an application Context)
getSharedPreferences method parses Preference file and creates Map object for it
You can create it in few modes provided by Context. You should always use MODE_PRIVATE, as all the other modes are deprecated since API level 17.
// parse Preference file
SharedPreferences preferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// get values from Map
preferences.getBoolean("key", defaultValue)
preferences.get..("key", defaultValue)
// you can get all Map but be careful you must not modify the collection returned by this
// method, or alter any of its contents.
Map<String, ?> all = preferences.getAll();
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
//add on Change Listener
preferences.registerOnSharedPreferenceChangeListener(mListener);
//remove on Change Listener
preferences.unregisterOnSharedPreferenceChangeListener(mListener);
// listener example
SharedPreferences.OnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener
= new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
};
Editor
SharedPreferences.Editor is an Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
Use simple interface to put values in Editor
Save values synchronous with commit() or asynchronous with apply which is faster. In fact of using different threads using commit() is safer. Thats why I prefer to use commit().
Remove single value with remove() or clear all values with clear()
// get Editor object
SharedPreferences.Editor editor = preferences.edit();
// put values in editor
editor.putBoolean("key", value);
editor.put..("key", value);
// remove single value by key
editor.remove("key");
// remove all values
editor.clear();
// commit your putted values to the SharedPreferences object synchronously
// returns true if success
boolean result = editor.commit();
// do the same as commit() but asynchronously (faster but not safely)
// returns nothing
editor.apply();
Performance & Tips
SharedPreferences is a Singleton object so you can easily get as many references as you want, it opens file only when you call getSharedPreferences first time, or create only one reference for it.
// There are 1000 String values in preferences
SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 4 milliseconds
SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// call time = 0 milliseconds
As SharedPreferences is a Singleton object you can change any of It's instances and not be scared that their data will be different
first.edit().putInt("key",15).commit();
int firstValue = first.getInt("key",0)); // firstValue is 15
int secondValue = second.getInt("key",0)); // secondValue is also 15
Remember the larger the Preference object is the longer get, commit, apply, remove and clear operations will be. So it's highly recommended to separate your data in different small objects.
Your Preferences will not be removed after Application update. So there are cases when you need to create some migration scheme. For example you have Application that parse local JSON in start of application, to do this only after first start you decided to save boolean flag wasLocalDataLoaded. After some time you updated that JSON and released new application version. Users will update their applications but they will not load new JSON because they already done it in first application version.
public class MigrationManager {
private final static String KEY_PREFERENCES_VERSION = "key_preferences_version";
private final static int PREFERENCES_VERSION = 2;
public static void migrate(Context context) {
SharedPreferences preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
checkPreferences(preferences);
}
private static void checkPreferences(SharedPreferences thePreferences) {
final double oldVersion = thePreferences.getInt(KEY_PREFERENCES_VERSION, 1);
if (oldVersion < PREFERENCES_VERSION) {
final SharedPreferences.Editor edit = thePreferences.edit();
edit.clear();
edit.putInt(KEY_PREFERENCES_VERSION, currentVersion);
edit.commit();
}
}
}
SharedPreferences are stored in an xml file in the app data folder
// yours preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
// default preferences
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
Android guide.
Sample Code
public class PreferencesManager {
private static final String PREF_NAME = "com.example.app.PREF_NAME";
private static final String KEY_VALUE = "com.example.app.KEY_VALUE";
private static PreferencesManager sInstance;
private final SharedPreferences mPref;
private PreferencesManager(Context context) {
mPref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}
public static synchronized void initializeInstance(Context context) {
if (sInstance == null) {
sInstance = new PreferencesManager(context);
}
}
public static synchronized PreferencesManager getInstance() {
if (sInstance == null) {
throw new IllegalStateException(PreferencesManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return sInstance;
}
public void setValue(long value) {
mPref.edit()
.putLong(KEY_VALUE, value)
.commit();
}
public long getValue() {
return mPref.getLong(KEY_VALUE, 0);
}
public void remove(String key) {
mPref.edit()
.remove(key)
.commit();
}
public boolean clear() {
return mPref.edit()
.clear()
.commit();
}
}
If you have a large application that is relying on SharedPreferences you could have key duplication, especially in the case of using some third party library that relies on SharedPreferences as well.
Libraries should not use that particular SharedPreferences. The default SharedPreferences should only be used by the application.
This way if you have a class that heavily relies on SharedPreferences you can create a preference file that is used only by your class.
You are certainly welcome to do this. I wouldn't, at the application level, as the primary reason for SharedPreferences is to have them be shared among the components in the application. A development team should have no problem managing this namespace, just as they should have no problem managing names of classes, packages, resources, or other project-level stuff. Moreover, the default SharedPreferences are what your PreferenceActivity will use.
However, going back to your libraries point, reusable libraries should use a separate SharedPreferences for their library only. I would not base it on a class name, because then you are one refactoring away from breaking your app. Instead, pick a name that is unique (e.g., based on the library name, such as "com.commonsware.cwac.wakeful.WakefulIntentService") but stable.
it seems that accesses SharedPreferences should be done off the UI thread which makes sense.
Ideally, yes. I recently released a SharedPreferencesLoader that helps with this.
Are there any other best practices Android developers should be aware of when using SharedPreferences in their applications?
Don't over-rely upon them. They are stored in XML files and are not transactional. A database should be your primary data store, particularly for data you really don't want to lose.
In kotlin, use of SharedPreferences can be simplified in the following way.
class Prefs(context: Context) {
companion object {
private const val PREFS_FILENAME = "app_prefs"
private const val KEY_MY_STRING = "my_string"
private const val KEY_MY_BOOLEAN = "my_boolean"
private const val KEY_MY_ARRAY = "string_array"
}
private val sharedPrefs: SharedPreferences =
context.getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE)
var myString: String
get() = sharedPrefs.getString(KEY_MY_STRING, "") ?: ""
set(value) = sharedPrefs.edit { putString(KEY_MY_STRING, value) }
var myBoolean: Boolean
get() = sharedPrefs.getBoolean(KEY_MY_BOOLEAN, false)
set(value) = sharedPrefs.edit { putBoolean(KEY_MY_BOOLEAN, value) }
var myStringArray: Array<String>
get() = sharedPrefs.getStringSet(KEY_MY_ARRAY, emptySet())?.toTypedArray()
?: emptyArray()
set(value) = sharedPrefs.edit { putStringSet(KEY_MY_ARRAY, value.toSet()) }
Here, sharedPrefs.edit{...} is provided by the android core ktx library and should be implemented by adding dependency implementation "androidx.core:core-ktx:1.0.2" in appliation level build.gradle.
You can get the instance of SharedPreferences by using code:
val prefs = Prefs(context)
Furthermore, you can create the Singleton object of Prefs and use from anywhere within the app.
val prefs: Prefs by lazy {
Prefs(App.instance)
}
where, App extends Application and should be included in AndroidManifest.xml
App.kt
class App:Application() {
companion object {
lateinit var instance: App
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest .....
<application
android:name=".App"
....
Example Usage:
// get stored value
val myString = prefs.myString
// store value
prefs.myString = "My String Value"
// get stored array
val myStringArray = prefs.myStringArray
// store array
prefs.myStringArray = arrayOf("String 1","String 2","String 3")
This is my way
for write
SharedPreferences settings = context.getSharedPreferences("prefs", 0);
SharedPreferences.Editor editore = settings.edit();
editore.putString("key", "some value");
editore.apply();
to read
SharedPreferences settings = getSharedPreferences("prefs", 0);
Strings value = settings.getString("key", "");
Let's assume in a project, with multiple developers working on it, they are defining SharedPreference within an Activity like this:
SharedPreferences sharedPref = context.getSharedPreferences("prefName", 0);
At one point or another two developers can define the SharedPreference with the same name or insert equivalent Key - Value pairs, which will lead to problems in using the keys.
The solution relies on two options, whether to use;
SharedPreferences Singleton that uses String keys.
SharedPreferences Singleton that uses Enum keys.
Personally and According to this Sharepreference Documentation, I prefer to use Enum keys as it enforces stricter control when there are multiple programmers working on a project. A programmer has no choice but to declare a new key in the appropriate enum class and so all the keys are in the same place.
And to avoid boilerplate code writing create the SharedPreference singleton.
This SharedPreferences singleton Class help to centralize and simplify reading and writing of SharedPreferences in your Android app.
The source code for the two provided solutions can be found in GitHub

Categories