Create Dynamic ListView using JSON Parsing + PHP MySQL db data coming from server

How to fetch,show and set multiple MySQL database data rows inside android custom ListView directly from online.

Android dynamic custom listview means listview created by PHP MySQL database table rows + columns data which is coming directly online from server. On the server we have created a table with multiple values which we have converting into JSON data using PHP scripting code. Now From android application we just making a online web call using GetHttpResponse extends AsyncTask class. So here is the complete step by step tutorial for Create Dynamic ListView using JSON Parsing + PHP MySQL db data coming from server.

android-project-download-code-button

List of Android programming files inside this project :

  1. MainActivity.java .
  2. ListAdapter.java .
  3. cources.java .

List of Android layout files inside this project :

  1. activity_main.xml .
  2. list_adapter_view.xml .

List of PHP scripting files inside this project which is converting MySQL data into JSON for parse :

  1. courses.php
  2. dbconfig.php

How to Create Dynamic ListView using JSON Parsing + PHP MySQL db data coming from server.

Code for MainActivity.java file.

 package com.dynamiclistviewusingjsonparsing_android_examples.com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;


public class MainActivity extends Activity {

 ListView listCollege;
 ProgressBar proCollageList;
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
 super.onCreate(savedInstanceState);
 requestWindowFeature(Window.FEATURE_NO_TITLE);
 setContentView(R.layout.activity_main);

 listCollege = (ListView)findViewById(R.id.listCollege);
 proCollageList = (ProgressBar)findViewById(R.id.proCollageList);
 
 new GetHttpResponse(this).execute();
 }

 private class GetHttpResponse extends AsyncTask<Void, Void, Void> 
 {
 private Context context;
 String result;
 List<cources> collegeList;
 public GetHttpResponse(Context context)
 {
 this.context = context;
 }

 @Override
 protected void onPreExecute() 
 {
 super.onPreExecute();
 }

 @Override
 protected Void doInBackground(Void... arg0) 
 {
 HttpService httpService = new HttpService("http://androidblog.esy.es/test/courses.php");
 try 
 {
 httpService.ExecutePostRequest();

 if(httpService.getResponseCode() == 200)
 {
 result = httpService.getResponse();
 Log.d("Result", result);
 if(result != null)
 {
 JSONArray jsonArray = null;
 try {
 jsonArray = new JSONArray(result);

 JSONObject object;
 JSONArray array;
 cources college;
 collegeList = new ArrayList<cources>();
 for(int i=0; i<jsonArray.length(); i++)
 {
 college = new cources();
 object = jsonArray.getJSONObject(i);

 college.cources_name = object.getString("cource_name");
 college.cources_description = object.getString("cources_description");

 collegeList.add(college);
 }
 }
 catch (JSONException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 }
 else
 {
 Toast.makeText(context, httpService.getErrorMessage(), Toast.LENGTH_SHORT).show();
 }
 } 
 catch (Exception e) 
 {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 return null;
 }

 @Override
 protected void onPostExecute(Void result) 
 
 {
 proCollageList.setVisibility(View.GONE);
 listCollege.setVisibility(View.VISIBLE);
 if(collegeList != null)
 {
 ListAdapter adapter = new ListAdapter(collegeList, context);
 listCollege.setAdapter(adapter);
 }
 }
 }

 public class HttpService 
 {
 private ArrayList <NameValuePair> params;
 private ArrayList <NameValuePair> headers;

 private String url;
 private int responseCode;
 private String message;
 private String response;

 public String getResponse() 
 {
 return response;
 }

 public String getErrorMessage() 
 {
 return message;
 }

 public int getResponseCode() 
 {
 return responseCode;
 }

 public HttpService(String url)
 {
 this.url = url;
 params = new ArrayList<NameValuePair>();
 headers = new ArrayList<NameValuePair>();
 }

 public void AddParam(String name, String value)
 {
 params.add(new BasicNameValuePair(name, value));
 }

 public void AddHeader(String name, String value)
 {
 headers.add(new BasicNameValuePair(name, value));
 }

 public void ExecuteGetRequest() throws Exception
 {
 String combinedParams = "";
 if(!params.isEmpty())
 {
 combinedParams += "?";
 for(NameValuePair p : params)
 {
 String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
 if(combinedParams.length() > 1)
 {
 combinedParams += "&" + paramString;
 }
 else
 {
 combinedParams += paramString;
 }
 }
 }

 HttpGet request = new HttpGet(url + combinedParams);
 for(NameValuePair h : headers)
 {
 request.addHeader(h.getName(), h.getValue());
 }

 executeRequest(request, url);
 }

 public void ExecutePostRequest() throws Exception
 {
 HttpPost request = new HttpPost(url);
 for(NameValuePair h : headers)
 {
 request.addHeader(h.getName(), h.getValue());
 }

 if(!params.isEmpty())
 {
 request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
 }

 executeRequest(request, url);
 }

 private void executeRequest(HttpUriRequest request, String url)
 {
 HttpParams httpParameters = new BasicHttpParams();
 int timeoutConnection = 10000;
 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
 int timeoutSocket = 10000;
 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
 
 HttpClient client = new DefaultHttpClient(httpParameters);
 HttpResponse httpResponse;
 try
 {
 httpResponse = client.execute(request);
 responseCode = httpResponse.getStatusLine().getStatusCode();
 message = httpResponse.getStatusLine().getReasonPhrase();

 HttpEntity entity = httpResponse.getEntity();
 if (entity != null) 
 {
 InputStream instream = entity.getContent();
 response = convertStreamToString(instream);
 instream.close();
 }
 } 
 catch (ClientProtocolException e) 
 {
 client.getConnectionManager().shutdown();
 e.printStackTrace();
 } 
 catch (IOException e) 
 {
 client.getConnectionManager().shutdown();
 e.printStackTrace();
 }
 }

 private String convertStreamToString(InputStream is)
 {
 BufferedReader reader = new BufferedReader(new InputStreamReader(is));
 StringBuilder sb = new StringBuilder();

 String line = null;
 try 
 {
 while ((line = reader.readLine()) != null) 
 {
 sb.append(line + "\n");
 }
 } 
 catch (IOException e) 
 {
 e.printStackTrace();
 }
 finally 
 {
 try 
 {
 is.close();
 } 
 catch (IOException e) 
 {
 e.printStackTrace();
 }
 }
 return sb.toString();
 }
 }



}

Code for ListAdapter.java file.

package com.dynamiclistviewusingjsonparsing_android_examples.com;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListAdapter extends BaseAdapter
{
 Context context;
 List<cources> valueList;
 public ListAdapter(List<cources> listValue, Context context) 
 {
 this.context = context;
 this.valueList = listValue;
 }

 @Override
 public int getCount() 
 {
 return this.valueList.size();
 }

 @Override
 public Object getItem(int position) 
 {
 return this.valueList.get(position);
 }

 @Override
 public long getItemId(int position) 
 {
 return position;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) 
 {
 ViewItem viewItem = null;
 if(convertView == null)
 {
 viewItem = new ViewItem();
 LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
 //LayoutInflater layoutInfiater = LayoutInflater.from(context);
 convertView = layoutInfiater.inflate(R.layout.list_adapter_view, null);

 viewItem.txtTitle = (TextView)convertView.findViewById(R.id.adapter_text_title);
 viewItem.txtDescription = (TextView)convertView.findViewById(R.id.adapter_text_description);
 convertView.setTag(viewItem);
 }
 else
 {
 viewItem = (ViewItem) convertView.getTag();
 }

 viewItem.txtTitle.setText(valueList.get(position).cources_name);
 viewItem.txtDescription.setText(valueList.get(position).cources_description);
 
 return convertView;
 }
}

class ViewItem
{
 TextView txtTitle;
 TextView txtDescription;
}



Code for cources.java file.

 package com.dynamiclistviewusingjsonparsing_android_examples.com;

public class cources
{
 public String cources_name;
 public String cources_description;
 
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.dynamiclistviewusingjsonparsing_android_examples.com.MainActivity"
 android:background="#ffffff" >

 
 <TextView
 android:id="@+id/cources_title"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="COURSES"
 android:textColor="#429ed7"
 android:textSize="25sp"
 android:textStyle="bold" />
 
 <ListView
 android:id="@+id/listCollege"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:visibility="gone"
 android:layout_marginTop="35dp" >
 </ListView>
 
 <ProgressBar
 android:id="@+id/proCollageList"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerInParent="true"
 android:visibility="visible"
 />

 <ImageView
 android:id="@+id/borderImg"
 android:layout_width="fill_parent"
 android:layout_height="1dp"
 android:layout_alignLeft="@+id/cources_title"
 android:layout_below="@+id/cources_title"
 android:background="#429ed7" />
 
</RelativeLayout>

Code for list_adapter_view.xml file.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:background="#ffffff"
 >
 
 <TextView 
 android:id="@+id/adapter_text_title"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textColor="#429ed7"
 android:textSize="18sp"
 />
 
 <TextView 
 android:id="@+id/adapter_text_description"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:textColor="#020202"/>

 
</LinearLayout>

PHP Files :

Code for courses.php file.

 <?php
include 'dbconfig.php';

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM cources";
$result = $conn->query($sql);

if ($result->num_rows >0) {
 // output data of each row
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 
 }
 
} else {
 echo "0 results";
}
 echo $json;
$conn->close();
?>

Code for dbconfig.php file.

 <?php

//This script is designed by Android-Examples.com
//Define your host here.
$servername = "mysql.hostinger.in";
//Define your database username here.
$username = "u288012116_new";
//Define your database password here.
$password = "1234567890";
//Define your database name here.
$dbname = "u288012116_new";

?>

Screenshots:

Create Dynamic ListView using JSON Parsing

 

Create Dynamic ListView using JSON Parsing

Click here to download Create Dynamic ListView using JSON Parsing + PHP MySQL db data coming from server whole project with MySQL db file included.

60 Comments

  1. Nice tutorial, help me a lot.
    Best and simple way 🙂
    Thanks

  2. Welcome Sharon ..

  3. Great tutorial!

  4. Thank you for this. I have a question that I can’t find anywhere online. . You created a table on mysql and convert the table to JSON using php script, when I load a new row in the table, will it show in my app?

  5. I am facing the above problem.

  6. RANJAN download the whole project and upload the server code on server and run the app.

  7. Nice tutorial, its all help me to solve coding problem

  8. really good tutorial..
    I have one question sir , how to add button in that code and retrieve records on click button. is it possible in that code?

  9. Thanks for the awesome tutorial…………………..
    Please sir tell me one thing
    “i want to view details of selected item like any news app”
    Thanks in advance because i know you will teach me……….

  10. Great tutorial Sir
    But i want to know how to go details of listview item . If i click on any item then get image, title and descriptions from server
    Please sir help me

  11. thank you very much sir
    i m just going on this..

  12. Hey Sir,

    i like your Projects, but i cant start this one cuz there is no build.grandle. How i can get your Project working ? Thx Sir

  13. Sir, i told you i go your App working, but i have a big problem, the app do not accept the latters: ß, ä,ü,ä if i put a text like mißt the app do not show the message, how can i fix this?

    thank you!!!!!

  14. Hey JUNED MUGHAL,

    Why you delete my Post. I hope i get a Answer. If i use words with ä,ö,ü,ß your App do not Show messages. If i remove the letters: ä,ö,ü,ß then it shows me the messages, can you tell me how i can fix that and it shows normaly ö,ä,ü,´ß ?

    WOULD BE VERY NICE IF YOU CAN HELP ME MATE! THANK YOU 🙂

  15. Hey Sir, i got all working. I have a Idea but i can’t Handly it how to get it to work.
    If in the Listview nothing to Show, is it Possible to make a Text in Listview “Nothing to Show” ? this would be verry cool and if you can teach me how to do it this will be cooler 🙂

    • Yes Steve Just apply listviewadapter == null condition then in the scope print the toast message that noting to show.

      • Thx for your Replay.

        I am correct? i think no, cuz it´s not working for me -.- ^^

        @Override
        protected void onPostExecute(Void result)
        {
        proCollageList.setVisibility(View.GONE);
        listCollege.setVisibility(View.VISIBLE);
        if(collegeList != null)
        {
        ListAdapter adapter = new ListAdapter(collegeList, context);
        listCollege.setAdapter(adapter);
        } else {
        ListAdapter adapter = new ListAdapter(collegeList, context);
        if(adapter == null){
        Toast.makeText(profile2.this, “Nothing to Show…”, Toast.LENGTH_LONG).show();
        }
        }
        }
        }

        • Steve dont put another if inside your code just use :
          @Override
          protected void onPostExecute(Void result)
          {
          proCollageList.setVisibility(View.GONE);
          listCollege.setVisibility(View.VISIBLE);
          if(collegeList != null)
          {
          ListAdapter adapter = new ListAdapter(collegeList, context);
          listCollege.setAdapter(adapter);
          } else {
          Toast.makeText(profile2.this, “Nothing to Show…”, Toast.LENGTH_LONG).show();
          }
          }
          }

          • Ok, i see i was corectly only the mistake “if”. Nice man, thx for the Tipp, have a nice day 🙂

            btw awesome tut you have here 🙂

          • Hey Sir,

            Its not working, still no message popup, i delete ervything on my database but nothing appears.

            Any idea ?

  16. Sir
    Pls am try to retrieve from my database all the records from six columns,i followed this code but it seems the progressbar keeps on loading and nothing else is showing.can u please help me understand this part of the code:
    params = new ArrayList();
    headers = new ArrayList();
    i was wondering the problem might come from this part.Thank u

    • Debrah just create all the variable in which you want to store the retrieved data in cources.java then just follow all of my code.

  17. Sir,
    Please am trying to retrieve data from four columns from my database using this same code but the progress bar keeps on loading with nothing showing.Can u please help me understand this part of the code ;
    private ArrayList params;
    private ArrayList headers;
    why this arraylist were created because i am thinking maybe the problem might be from here.Thank u.

  18. DEBRAH this is used to parse json data like a parsing class. You should read the same example with full tutorial on my new android blog : https://androidjson.com/fetch-show-multiple-json-dynamic-listview/

  19. Thanks so much sir,it worked buh am trying an app that i want to retrieve record based on the Customer Id that i want to input from my app ,can u please help me out.

  20. Thank you so much… You have save me… I passed one week to resolve this problem not succes… But when I see your tutorial everything gone better.. Thank u so much..

  21. hi sir, I want to retrieve data by id, means I have an Id and I want to retrieve data by particular id .not all data in database.

  22. i have some errors in database table….output shown in URL only…it is not showed on mobile screen…if any one have database table details please mail me or comment below…mail id : [email protected]

  23. Mughal, thanks for your reply…i am learning android and still in starting level…i didn’t get any error…. can u tell me your database table(course) and structure(fields)…

    • Yes sure, Table course has 3 columns, First one is id, Second is course_name, Third is cources_description. Now here id column is the primary key. Now in Type field set id as INT, course_name as VARCHAR, cources_description as VARCHAR. Length/Values should be 255 for every column.

  24. still it is not showing no errors and we didn’t get output…..can u please text me your mail id….

  25. Nguyen Phong Phu

    ListAdapter adapter=new ListAdapter(collegeList,context);
    error : this is abstract can not instantiated

  26. Nguyen Phong Phu

    Error:(318, 39) error: ListAdapter is abstract; cannot be instantiated
    In MainActivity.java
    please help me solve this problem

  27. I have followed your code but changed slightly according to my database.

    Result was blank page 🙁

  28. will it work on api23?

Leave a Reply

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