Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

putObject method doesnt recognize Custom Object #31

Open
amruta-pani opened this issue Jun 5, 2017 · 2 comments
Open

putObject method doesnt recognize Custom Object #31

amruta-pani opened this issue Jun 5, 2017 · 2 comments

Comments

@amruta-pani
Copy link

amruta-pani commented Jun 5, 2017

Using this method to save an object of a class wrapping a HashMap object is resulting in a LinkTreeMap Class casting error.
Eg Class:

public class Categories {
    private String categoryName;
    private ActivityMasterModel amm;

    @SerializedName("activities")
    @Expose
    private ArrayList<ActivityMasterModel> allActivities;

    private HashMap<String, ArrayList<ActivityMasterModel>> allActivitiesByCategory;

    public ArrayList<ActivityMasterModel> getAllActivities() {
        return allActivities;
    }

    public void setAllActivities(ArrayList<ActivityMasterModel> allActivities) {
        this.allActivities = allActivities;
    }

I couldnt save allActivitiesByCategory object into shared preferences using putObject method. Hence I created the above class to be used with putObject method. However, the object allActivitiesByCategory is saved using the below modified method.

public void putHashMapObject(String key, Object obj) {
       checkForNullKey(key);
       Type type = new TypeToken<Map<String, ArrayList<ActivityMasterModel>>>() {}.getType();
       Gson gson = new Gson();
       putString(key, gson.toJson(obj, type));
   }

I was following the below link and it helped a lot.
https://stackoverflow.com/questions/32444863/google-gson-linkedtreemap-class-cast-to-myclass

However, the same solution didnt work for SparseArray instead of HashMap. I couldnt solve the issue yet. I am not a Java guy, I should say a beginner, and trying to get my head around it.

@kcochibili
Copy link
Owner

I am happy you were able to find a hint online that enabled you to save the HashMap.

SparseArray is a little more complicated for Gson which TinyDB uses for saving Objects. To save a SparseArray, you'd have to create a custom put object method based on this example here.
https://stackoverflow.com/a/18644836/1463931

@amruta-pani
Copy link
Author

amruta-pani commented Jun 7, 2017 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants