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.