westlinkin / CacheUtilsLibrary

A simple Android utils library to write any type of data into cache files and read them later.
http://lifeofcoding.com/CacheUtilsLibrary/
Apache License 2.0
135 stars 29 forks source link

Error when reading from cached HashMap #4

Open jaytj95 opened 7 years ago

jaytj95 commented 7 years ago

I'm getting a com.google.gson.internal.LinkedTreeMap cannot be cast to <CustomClass> error when reading a HashMap from cache.

Writing to file:

Map<String, Bus> buses = new HashMap<>();
//after adding data
CacheUtils.writeDataMapFile(CACHE_NAME, buses);

Reading from file:

buses = CacheUtils.readDataMapFile(CACHE_NAME);
Bus b = buses.get("Route 1"); //Error here
jaytj95 commented 7 years ago

Found a solution to my problem. Ended up storing the hashmap as a JSON string and then doing the Type conversion myself.

CacheUtils.writeFile(CACHE_NAME, new Gson().toJson(buses));
//.......
String busesStr = CacheUtils.readFile(CACHE_NAME);
Type type = new TypeToken<HashMap<String, Bus>>(){}.getType();
HashMap<String, Bus> buses = new Gson().fromJson(busesStr, type);