user15203210
user15203210

Reputation:

How can I can save HashMap in my Android app?

I have member variable HashMap<Integer, HashMap<String[], Integer>> in some activity in my Android app. The HashMap supposed to survive from user launch app for the first time till the app will be deleted. I can't use shared preferences because there aren't such put method. I know about room database but I don't really want to use that in this case. Please, tell me which options are there to save HashMap and store it in memory.

Upvotes: 0

Views: 257

Answers (2)

Shahriar Zaman
Shahriar Zaman

Reputation: 938

You can try to serialize HashMap to string. Import this library in your build.gradle file first.

implementation 'com.google.code.gson:gson:2.8.6'

To have serialize data you can follow this code:

public static String hashToString (HashMap<Integer, HashMap<String[], Integer>> hashMap) {
    if (hashMap == null) return null;
    
    Gson gson = new Gson();
    //import java.lang.reflect.Type;
    //import com.google.gson.reflect.TypeToken;
    Type type = new TypeToken<HashMap<Integer, HashMap<String[], Integer>>(){}.getType();

    return gson.toJson(hashMap, type);
}

Now you can convert any object to string you can use this method..

To get back object from string:

public static HashMap<Integer, HashMap<String[], Integer>> stringToHash (String json) {
    if (json == null) return null;
    
    Gson gson = new Gson();
    //import java.lang.reflect.Type;
    //import com.google.gson.reflect.TypeToken;
    Type type = new TypeToken<HashMap<Integer, HashMap<String[], Integer>>(){}.getType();

    return gson.fromJson(json, type);
}

Upvotes: 2

Hamid Shaikh
Hamid Shaikh

Reputation: 41

PaperDB library is best for store anything believe i use paperDB to store HashMap,POJO Class Object, Array and so on... and it just serializes the any object store in local storage.

Github Link Of PaperDB : https://github.com/pilgr/Paper

In Above Link you can learn about how to use this!

Upvotes: 1

Related Questions