'How to save ArrayList<Webview> Objects in local database in android

I have a requirement of staying logged in with multiple emails for the same website. So, when i open app for 1st time, I create a new webview instance and login with email-1, then i create another webview instance and login in same website with email-2 and so on.

Before i close my app, I am trying to save those objects in local DB using GSON. When i reopen my app, I am trying to load those objects from local DB using GSON. But, it is not working. I observed that Android is not able to save the webview object or the Arraylist objects in local DB. Below are the methods I tried with no success.

public void saveArrayList(ArrayList<WebView> list, String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(global_ctx);
        SharedPreferences.Editor editor = prefs.edit();
        Gson gson = new Gson();
        String json = gson.toJson(list);
        editor.putString(key, json);
        editor.apply();
    }

    public ArrayList<WebView> getArrayList(String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(global_ctx);
        Gson gson = new Gson();
        String json = prefs.getString(key, null);
        Type type = new TypeToken<ArrayList<WebView>>() {
        }.getType();
        ArrayList<WebView> arrayList = gson.fromJson(json, type);
        if (arrayList == null ||
                arrayList.size() == 0) arrayList = new ArrayList<>();
        return arrayList;
    }

    public static void saveObjectToSharedPreference(String serializedObjectKey, Object object) {
        try {
            SharedPreferences sharedPreferences = global_ctx.getSharedPreferences("webFile", 0);
            SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
            final Gson gson = new Gson();
            String serializedObject = gson.toJson(object);
            sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
            sharedPreferencesEditor.apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <GenericClass> GenericClass getSavedObjectFromPreference(String preferenceKey, Class<GenericClass> classType) {
        SharedPreferences sharedPreferences = global_ctx.getSharedPreferences("webFile", 0);
        if (sharedPreferences.contains(preferenceKey)) {
            final Gson gson = new Gson();
            return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
        }
        return null;
    }

Can anyone suggest a best solution for this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source