Resolved! com.google.gson.internal.LinkedTreeMap cannot be cast to

This post is a quick hack to resolve this issue if any of you facing a similar issue. In the Android application, I am using retrofit2 and okhttp3 to communicate remove services written in PHP and sending JSON data. There is an activity in which I have to show server JSON response in a ListView, but I was facing a strange issue in mapping JSON data to listview BaseAdapter which looks as below

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hsa.fo…..up.ha…..on, PID: 25879
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.hsa…….

 

So after banging my head with different types of Types like JSONArray, ArrayList, JSONObject and even custom model with getters and setters, but nothing helped then finally cracked it to show listView data.

JSON response format from server:

{
    results: [
    {
        id: "10",
        phone: "+91783XXXX345",
        name: "Mr Example",
        email: "[email protected]"
    },
    {
        id: "11",
        phone: "+9178XXXX66",
        name: "Mr Foo",
        email: "[email protected]"
    }],
    statusCode: "1",
    count: "2"
}

 

In listView’s BaseAdapter file we need to map data using LinkedTreeMap Key Value object to get row attribute value as below:

...
...

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view= LayoutInflater.from(c).inflate(R.layout.listview_manage_clients,viewGroup,false);
        }

        TextView mUserName = (TextView) view.findViewById(R.id.userName);
        TextView mUserPhone = (TextView) view.findViewById(R.id.userPhone);


        Object getrow = this.users.get(i);
        LinkedTreeMap<Object,Object> t = (LinkedTreeMap) getrow;
        String name = t.get("name").toString();

        mUserName.setText("Name is "+name);
        mUserPhone.setText("Phone is "+phone);

        return view;
    }
...
...

See Complete Application Tutorial Here Create Multiple Columns ListView from JSON Data using Retrofit2 in Android Example

 

this method resolved my problem of parsing JSON data into ListView BaseAdapter, maybe will help you as well 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *