Android JSON Parsing Custom ListView From MySQL Database Tutorial

JSON is the backbone of every dynamic android application because using JSON data we can send and receive data from online MySQL database server using PHP language. So in this tutorial we would going to store Fruit names online in MySQL database table and retrieve them inside android application in ListView using org.apache.http.legacy library. So here is the complete step by step tutorial for Android JSON Parsing Custom ListView From MySQL Database.

Contents in this project Android JSON Parsing Custom ListView From MySQL Database Tutorial :

1. Create a Database on your online or local MySQL PhpMyAdmin hosting server.

2. Create a Table named as Fruits_Name_Table inside the MySQL database with 2 columns id and Fruit_Name . Now set the id as primary key.

3. Now insert some records in this table manually. For example my table is for fruit names so i am inserting some common fruit names inside the MySQL table. Below is the screenshot of Table after inserting some records.

4. This step is very important. Now we would going to create 2 PHP files named as DBConfig.php and ShowFruitsName.php . Now we would upload them on online hosting web space using any File manager.

DBConfig.php : This file contain all the useful and recommended server configuration. Make any changes in this file according to your sever or MySQL database configuration.

ShowFruitsName.php : This file would fetch all the records from MySQL database table and show encode them in JSON format.

Code for DBConfig.php file.

<?php

//Define your Database Host here.
$HostName = "localhost";

//Define your database User Name here.
$HostUser = "id3846509_android_user";

//Define your Database Password here.
$HostPass = "123456";

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

?>

Code for ShowFruitsName.php file.

<?php
include 'DBConfig.php';

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

if ($conn->connect_error) {

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

$sql = "SELECT * FROM Fruits_Name_Table";

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

if ($result->num_rows >0) {

while($row[] = $result->fetch_assoc()) {

$TableItems = $row;

$FinalJSON = json_encode($TableItems);


}

} else {
echo "No Results Found in Table.";
}
echo $FinalJSON;
$conn->close();
?>

5. Import org.apache.http.legacy library inside your build.gradle(Module : App) file in android block.

6. Paste the useLibrary ‘org.apache.http.legacy’ code in android block like i did in below screenshot.

Here you go now the org.apache.http.legacy library would successfully installed in your Android Studio project.

7. Start Coding For App  :

Java Files in this project :

  1. MainActivity.java
  2. ListViewAdapter.java
  3. HttpWebServices.java
  4. FruitNames.java

Layout Files in this project :

  1. activity_main.xml
  2. listview_items.xml

Other Files :

  1. AndroidManifest.xml

Code for MainActivity.java file.

package com.android_examples.json_listview_android_examplescom;
import android.support.v7.app.AppCompatActivity;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import org.json.JSONArray;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import org.json.JSONObject;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    ListView FruitsNameListView;

    ProgressBar progressBar;

    String HttpServerURL = "https://androidjson27.000webhostapp.com/ShowFruitsName.php";

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

        setContentView(R.layout.activity_main);

        FruitsNameListView = (ListView)findViewById(R.id.listview1);

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

        new GetServerResponseFunction(MainActivity.this).execute();

        FruitsNameListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                // TODO Auto-generated method stub


                FruitNames ListViewClickItem = (FruitNames) parent.getItemAtPosition(position);

                Toast.makeText(MainActivity.this, ListViewClickItem.getFruit_Name(), Toast.LENGTH_SHORT).show();

            }
        });
    }

    public class GetServerResponseFunction extends AsyncTask<Void, Void, Void>
    {
        public Context context;

        String DataHolder;

        List<FruitNames> fruitNamesList;

        public GetServerResponseFunction(Context context)
        {
            this.context = context;
        }

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

        @Override
        protected Void doInBackground(Void... arg0)
        {
            HttpWebServices httpWebServices = new HttpWebServices(HttpServerURL);
            try
            {
                httpWebServices.ExecutePostRequest();

                if(httpWebServices.getResponseCode() == 200)
                {
                    DataHolder = httpWebServices.getResponse();

                    if(DataHolder != null)
                    {
                        JSONArray jsonArray = null;

                        try {
                            jsonArray = new JSONArray(DataHolder);

                            JSONObject jsonObject;

                            FruitNames fruitNames;

                            fruitNamesList = new ArrayList<FruitNames>();

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

                                jsonObject = jsonArray.getJSONObject(i);

                                fruitNames.Fruit_Name = jsonObject.getString("Fruit_Name");

                                fruitNamesList.add(fruitNames);
                            }
                        }
                        catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                else
                {
                    Toast.makeText(context, httpWebServices.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);

            FruitsNameListView.setVisibility(View.VISIBLE);

            if(fruitNamesList != null)
            {
                ListViewAdapter adapter = new ListViewAdapter(fruitNamesList, context);

                FruitsNameListView.setAdapter(adapter);
            }
        }
    }

}

Code for ListViewAdapter.java file.

package com.android_examples.json_listview_android_examplescom;

/**
 * Created by Juned on 12/3/2017.
 */

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

public class ListViewAdapter extends BaseAdapter {

    Context ContextObj;
    List<FruitNames> TempList;

    public ListViewAdapter(List<FruitNames> listValue, Context context)
    {
        this.ContextObj = context;

        this.TempList = listValue;
    }

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

    @Override
    public Object getItem(int position)
    {
        return this.TempList.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.ContextObj.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

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

            viewItem.FruitNameTextView = (TextView)convertView.findViewById(R.id.textView1);

            convertView.setTag(viewItem);
        }
        else
        {
            viewItem = (ViewItem) convertView.getTag();
        }

        viewItem.FruitNameTextView.setText(TempList.get(position).Fruit_Name);

        return convertView;
    }
}

class ViewItem
{
    TextView FruitNameTextView;

}

Code for HttpWebServices.java file.

package com.android_examples.json_listview_android_examplescom;

/**
 * Created by Juned on 12/3/2017.
 */

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;

public class HttpWebServices {public int responseCode;

    public String message;

    public String response;

    public ArrayList<NameValuePair> ArrayListParams;

    public ArrayList <NameValuePair> headers;

    public String UrlHolder;

    public String getResponse()
    {
        return response;
    }

    public String getErrorMessage()
    {
        return message;
    }

    public int getResponseCode()
    {
        return responseCode;
    }

    public HttpWebServices(String url)
    {
        HttpWebServices.this.UrlHolder = url;

        ArrayListParams = new ArrayList<NameValuePair>();

        headers = new ArrayList<NameValuePair>();
    }

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

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

    public void ExecuteGetRequest() throws Exception
    {
        String MixParams = "";

        if(!ArrayListParams.isEmpty())
        {
            MixParams += "?";

            for(NameValuePair p : ArrayListParams)
            {
                String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");

                if(MixParams.length() > 1)
                {
                    MixParams  +=  "&" + paramString;
                }
                else
                {
                    MixParams += paramString;
                }
            }
        }

        HttpGet httpGet = new HttpGet(UrlHolder + MixParams);

        for(NameValuePair h : headers)
        {
            httpGet.addHeader(h.getName(), h.getValue());
        }

        executeRequest(httpGet, UrlHolder);
    }

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

        if(!ArrayListParams.isEmpty())
        {
            httpPost.setEntity(new UrlEncodedFormEntity(ArrayListParams, HTTP.UTF_8));
        }

        executeRequest(httpPost, UrlHolder);
    }

    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpParams httpParameters = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);

        HttpConnectionParams.setSoTimeout(httpParameters, 10000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);

        HttpResponse httpResponse;
        try
        {
            httpResponse = httpClient.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();
            if (entity != null)
            {
                InputStream inputStream = entity.getContent();

                response = convertStreamToString(inputStream);

                inputStream.close();
            }
        }
        catch (ClientProtocolException e)
        {
            httpClient.getConnectionManager().shutdown();
            e.printStackTrace();
        }
        catch (IOException e)
        {
            httpClient.getConnectionManager().shutdown();
            e.printStackTrace();
        }
    }

    private String convertStreamToString(InputStream is)
    {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));

        StringBuilder stringBuilder = new StringBuilder();

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

}

Code for FruitNames.java file.

package com.android_examples.json_listview_android_examplescom;

/**
 * Created by Juned on 12/3/2017.
 */

public class FruitNames {

    public String Fruit_Name ;

    public String getFruit_Name() {

        return Fruit_Name;

    }

}

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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.android_examples.json_listview_android_examplescom.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listview1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

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

</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:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView1"
        android:text="Default Item Text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:padding="7dp"
        android:textSize="22dp"
        />

</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.android_examples.json_listview_android_examplescom">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

Screenshots :

JSON Parsing Custom ListView

Leave a Reply

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