Android Show Multiple JSON PHP MySQL Data in Custom ListView

Our in this tutorial we would going to fetch all the MySQL database data with the use of PHP script in JSON encoded form. After retrieving parsed data in our application we would set that data into multiple ListView items. First one is for Subject Name and second is Subject Full form. The both items were managed and style separately so app developer could edit them as their own requirement. So read the full tutorial for Show Multiple JSON PHP MySQL Data in Custom ListView.

Also read :

Tutorial Contents in this project Show Multiple JSON PHP MySQL Data inside Custom ListView :

  1. Watch the live demo video.
  2. Create Database with Table on your Local or Online Server.
  3. Create PHP Script to convert PHP MySQL data into JSON data.
  4. Test the PHP Script and see JSON data on Web Browser.
  5. Start a new Android Application development project.
  6. Import org.apache.http.legacy library in your project.
  7. Add internet permission in your project.
  8. Start Coding.

List of JAVA Files in this project :

  • MainActivity.java
  • HttpServiceClass.java
  • ListAdapter.java
  • Subject.java

List of Layout files in this project :

  • activity_main.xml
  • listview_items.xml

List of PHP Files in this project :

  • DatabaseConfig.php
  • SubjectFullForm.php

1. Watch the live demo video Show Multiple JSON :

2. Create Database with Table on your Local or Online Server :

Create a database on your PhpMyAdmin server, Inside that database create a new table with three columns ID, SubjectName, SubjectFullForm . Below is the screenshot of my table after inserting records.

3. Create PHP Script to convert PHP MySQL data into JSON data to Show Multiple JSON :

Code for DatabaseConfig.php file.

<?php

//Define your host here.
$HostName = "localhost";

//Define your database username here.
$HostUser = "id632449_androidjson";

//Define your database password here.
$HostPass = "kdfjdfdskljomew9ry3873";

//Define your database name here.
$DatabaseName = "id632449_androidjson";

?>

Code for SubjectFullForm.php file.

 <?php
include 'DatabaseConfig.php';

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

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

$sql = "SELECT * FROM SubjectFullFormTable";

$result = $conn->query($sql);

if ($result->num_rows >0) {
 
 
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 
 }
 
} else {
 echo "No Results Found.";
}
 echo $json;
$conn->close();
?>

 4. Test the PHP Script and see JSON data on Web Browser :

5. Start a new Android Application development project.

6. Import org.apache.http.legacy library in your project :

1. Open Your Project’s build.gradle(Module:app) file .

2. Add useLibrary ‘org.apache.http.legacy’ in android scope .


7. Add internet permission in your project :

Open your Project’s AndroidManifest.xml file and add internet permission inside it.

<uses-permission android:name="android.permission.INTERNET" />

 Start Coding:

Code for MainActivity.java file.

package com.androidjson.customlistviewjson_androidjsoncom;
import java.util.ArrayList;
import java.util.List;
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.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;


public class MainActivity extends Activity {

    ListView SubjectFullFormListView;
    ProgressBar progressBar;
    String HttpURL = "https://androidjsonblog.000webhostapp.com/SubjectFullForm.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);

        SubjectFullFormListView = (ListView) findViewById(R.id.SubjectFullFormListView);

        progressBar = (ProgressBar) findViewById(R.id.ProgressBar1);

        new ParseJSonDataClass(this).execute();
    }

    private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> {
        public Context context;
        String FinalJSonResult;
        List<Subject> SubjectFullFormList;

        public ParseJSonDataClass(Context context) {

            this.context = context;
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            HttpServiceClass httpServiceClass = new HttpServiceClass(HttpURL);

            try {
                httpServiceClass.ExecutePostRequest();

                if (httpServiceClass.getResponseCode() == 200) {

                    FinalJSonResult = httpServiceClass.getResponse();

                    if (FinalJSonResult != null) {

                        JSONArray jsonArray = null;
                        try {

                            jsonArray = new JSONArray(FinalJSonResult);
                            JSONObject jsonObject;
                            Subject subject;

                            SubjectFullFormList = new ArrayList<Subject>();

                            for (int i = 0; i < jsonArray.length(); i++) {

                                subject = new Subject();

                                jsonObject = jsonArray.getJSONObject(i);

                                subject.Subject_Name = jsonObject.getString("SubjectName");

                                subject.Subject_Full_Form = jsonObject.getString("SubjectFullForm");

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

                    Toast.makeText(context, httpServiceClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)

        {
            progressBar.setVisibility(View.GONE);

            SubjectFullFormListView.setVisibility(View.VISIBLE);

            if (SubjectFullFormList != null) {

                ListAdapter adapter = new ListAdapter(SubjectFullFormList, context);

                SubjectFullFormListView.setAdapter(adapter);
            }
        }
    }

}

Code for HttpServiceClass.java file.

package com.androidjson.customlistviewjson_androidjsoncom;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

/**
 * Created by Juned on 1/30/2017.
 */

public class HttpServiceClass {
    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 HttpServiceClass(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.androidjson.customlistviewjson_androidjsoncom;

/**
 * Created by Juned on 1/30/2017.
 */

import java.util.List;
import android.app.Activity;
import android.content.Context;
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<Subject> subject_list;

    public ListAdapter(List<Subject> listValue, Context context)
    {
        this.context = context;
        this.subject_list = listValue;
    }

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

    @Override
    public Object getItem(int position)
    {
        return this.subject_list.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);

            convertView = layoutInfiater.inflate(R.layout.listview_items, null);

            viewItem.SubNameTextView = (TextView)convertView.findViewById(R.id.SubjectNameTextView);

            viewItem.SubFullFormTextView = (TextView)convertView.findViewById(R.id.SubjectFullFormTextView);
            convertView.setTag(viewItem);
        }
        else
        {
            viewItem = (ViewItem) convertView.getTag();
        }

        viewItem.SubNameTextView.setText(subject_list.get(position).Subject_Name);

        viewItem.SubFullFormTextView.setText(subject_list.get(position).Subject_Full_Form);

        return convertView;
    }
}

class ViewItem
{
    TextView SubNameTextView;
    TextView SubFullFormTextView;
}

Code for Subject.java file.

package com.androidjson.customlistviewjson_androidjsoncom;

/**
 * Created by Juned on 1/30/2017.
 */

public class Subject {

    public String Subject_Name;
    public String Subject_Full_Form;
}

Code for activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidjson.customlistviewjson_androidjsoncom.MainActivity"
    android:layout_margin="10dp">

    <TextView
        android:id="@+id/SubjectFullFormPageTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subjects Full Form List"
        android:textColor="#429ed7"
        android:textSize="25sp"
        android:textStyle="bold" />

    <ListView
        android:id="@+id/SubjectFullFormListView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:visibility="gone"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/borderView">
    </ListView>

    <ProgressBar
        android:id="@+id/ProgressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="visible"
        />

    <ImageView
        android:id="@+id/borderView"
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:background="#429ed7"
        android:layout_marginTop="11dp"
        android:layout_below="@+id/SubjectFullFormPageTitle"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

Code for listview_items.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:id="@+id/SubjectNameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#429ed7"
        android:textSize="22dp"

        />

    <TextView
        android:id="@+id/SubjectFullFormTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#020202"
        android:textSize="20dp"
        android:layout_marginBottom="5dp"/>

</LinearLayout>

Code for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidjson.customlistviewjson_androidjsoncom">

    <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>

Screenshot:

Show Multiple JSON

Download Code

2 Comments

  1. Hi can you make a custom listview with images in it

Leave a Reply to Admin Cancel reply

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