Expandable Listview with JSON data

Hello guys  Today i am going to show you how to add JSON DATA in Exapandable Listview. There was   a lost of example of expandable lis...

Hello guys

 Today i am going to show you how to add JSON DATA in Exapandable Listview.

There was a lost of example of expandable listview but they were using static data. So here i posted json data in expandable listview.

Download demo from here......

DOWNLOAD


I am using this url for fetch data http://www.androidbegin.com/tutorial/jsonparsetutorial.txt

json data look like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
  worldpopulation: [
    {
      rank: 1,
      country: "China",
      population: "1,354,040,000",
      flag: "http://www.androidbegin.com/tutorial/flag/china.png"
    },
    {
      rank: 2,
      country: "India",
      population: "1,210,193,422",
      flag: "http://www.androidbegin.com/tutorial/flag/india.png"
    },
    {
      rank: 3,
      country: "United States",
      population: "315,761,000",
      flag: "http://www.androidbegin.com/tutorial/flag/unitedstates.png"
    },
    {
      rank: 4,
      country: "Indonesia",
      population: "237,641,326",
      flag: "http://www.androidbegin.com/tutorial/flag/indonesia.png"
    }
  ]
}

And  i am fetching header as country name and population and rank as child data.

see image here



First add this layout files.

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#f4f4f4" >

    <ExpandableListView
        android:id="@+id/lvExp"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>

</LinearLayout>
 

list_group.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp"
    android:background="#000000">


    <TextView
        android:id="@+id/lblListHeader"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textSize="17dp"
        android:text="group"
        android:textColor="#f9f93d" />

</LinearLayout>


list_item.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dip"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblListItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="17dip"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:text="dsfd"
        android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />

</LinearLayout>


Then move to java file copy and paste file in your project

JSONParser.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JSONParser {

    public JSONParser() {

    }

    public String makeServiceCall(String serviceUrl) {
        Boolean registered = false;
        StringBuffer response = new StringBuffer();
        URL url = null;

        HttpURLConnection conn = null;
        try {

            url = new URL(serviceUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setDoOutput(false);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            int status = conn.getResponseCode();
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            }
            registered = true;

            // Get Response
            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;

            while ((line = rd.readLine()) != null) {
                response.append(line);

            }
            rd.close();

        } catch (Exception e) {
            e.printStackTrace();
      /* ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
         response.append("Error");*/
        }
        Log.v("Response:", response.toString());
        return response.toString();

    }

}

ExpandableListAdapter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends Activity {

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;

    private ProgressDialog mprocessingdialog;
    private static String url = "http://www.androidbegin.com/tutorial/jsonparsetutorial.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mprocessingdialog = new ProgressDialog(this);

        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.lvExp);

        // preparing list data
        new DownloadJason().execute();


    }

    /*
     * Preparing the list data
     */

    private class DownloadJason extends AsyncTask<Void, Void, Void> {


        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

//            Showing Progress dialog

            mprocessingdialog.setTitle("Please Wait..");
            mprocessingdialog.setMessage("Loading");
            mprocessingdialog.setCancelable(false);
            mprocessingdialog.setIndeterminate(false);
            mprocessingdialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            JSONParser jp = new JSONParser();
            String jsonstr = jp.makeServiceCall(url);
            Log.d("Response = ", jsonstr);

            if (jsonstr != null) {
//            For Header title Arraylist
                listDataHeader = new ArrayList<String>();
//                Hashmap for child data key = header title and value = Arraylist (child data)
                listDataChild = new HashMap<String, List<String>>();

                try {

                    JSONObject jobj = new JSONObject(jsonstr);
                    JSONArray jarray = jobj.getJSONArray("worldpopulation");

                    for (int hk = 0; hk < jarray.length(); hk++) {
                        JSONObject d = jarray.getJSONObject(hk);

                        // Adding Header data
                        listDataHeader.add(d.getString("country"));

                        // Adding child data for lease offer
                        List<String> lease_offer = new ArrayList<String>();

                        lease_offer.add(d.getString("country") + "'s Rank is : "
                                + d.getString("rank"));
                        lease_offer.add("And Population is " + d.getString("population"));

                        // Header into Child data
                        listDataChild.put(listDataHeader.get(hk), lease_offer);

                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } else {
                Toast.makeText(getApplicationContext(),
                        "Please Check internet Connection", Toast.LENGTH_SHORT)
                        .show();

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            mprocessingdialog.dismiss();
//call constructor
            listAdapter = new ExpandableListAdapter(getApplicationContext(), listDataHeader, listDataChild);

            // setting list adapter
            expListView.setAdapter(listAdapter);

        }
    }

}


    Manifest file

   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hometech.expandabledemo">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


NOTE :- Don't forget to add INTERNET permission in manifest file 


Demo DOWNLOAD




COMMENTS

BLOGGER: 1
Loading...
Name

Alert Android Chat Expandable Expandable Listview Expandable Listview with Json Facebook GCM JSON Login Notification PDF SDK 4.0
false
ltr
item
Android Knowledge: Expandable Listview with JSON data
Expandable Listview with JSON data
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSsqIp2gskr04Ye53s-k5S9VmkSELx0OXxdaR8aDB61Gc-BdbJtzV7ooCygBAxhf4r3zIggld1lr60dRLsOpgmdPP_r3b_ceLXxct_L3OJ36g2GltPFWXFwrtfQnn8leP3rmf8grPI1A5M/s320/Expandable+listview.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjSsqIp2gskr04Ye53s-k5S9VmkSELx0OXxdaR8aDB61Gc-BdbJtzV7ooCygBAxhf4r3zIggld1lr60dRLsOpgmdPP_r3b_ceLXxct_L3OJ36g2GltPFWXFwrtfQnn8leP3rmf8grPI1A5M/s72-c/Expandable+listview.png
Android Knowledge
http://androidknowledgeblog.blogspot.com/2016/06/expandable-listview-with-json-data.html
http://androidknowledgeblog.blogspot.com/
http://androidknowledgeblog.blogspot.com/
http://androidknowledgeblog.blogspot.com/2016/06/expandable-listview-with-json-data.html
true
2625512956379495182
UTF-8
Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy