Pages

Monday, 18 May 2015

Android JSON Parsing tutorial Using PHP and MySql Database and Display it on ListView

Today i am going to show tutorial how to parse JSON data to android and display it on ListView.
Here first of all we need to have php file that fetch data from MySql Database. 
PHP file will convert that data into JSON format.

json.php

<?php
$host = ""; // host of MySQL server
$user = ""; // MySQL user
$pwd = ""; // MySQL user's password
$db = ""; // database name

// Create connection
$con = mysqli_connect($host, $user, $pwd, $db);

// Check connection
if(mysqli_connect_errno($con)) {
    die("Failed to connect to MySQL: " . mysqli_connect_error());
}

// query the application data
$sql = "SELECT * FROM updates ORDER By id desc";
$result = mysqli_query($con, $sql);

// an array to save the application data
$rows = array();

// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $rows[] = $row;
}

// close the database connection
mysqli_close($con);

// echo the application data in json format
echo '{"updates":' ,json_encode($rows),'}';


Now we need one layout file for android app.

activity_main.xml

 <RelativeLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#e8e8e8"  
  >

<ListView android:id="@+id/toplist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#e8e8e8"
        android:layout_marginLeft="7dp"
        android:layout_marginTop="5dp"
       android:layout_marginRight="7dp"
  />

 </RelativeLayout>


We need another xml file for elements for listview. Create another xml file inside res/layout folder, name it listview_item.xml

listview_item.xml

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

    <TextView
        android:id="@+id/listitem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#f9c045"
        android:textSize="13sp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        />
</RelativeLayout>


for fetching the data we need to write one class file for GET and POST method to access JSON objects from Server.

JSONGet.java

package com.im.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONStudentParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONStudentParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}


Now its time for main coding that is java file that will fetch the data and display it on ListView.

MainActivity.java

package com.im.json;

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.im.json.JSONGet;

public class Result extends Activity  {
  ListView list;

  ArrayList<HashMap<String, String>> reslist = new ArrayList<HashMap<String, String>>();
  
  private static String url = "http://localhost:8080/json.php";  //change to your server url
  
  private static final String TAG_RESULT = "updates";
  private static final String TAG_NAME = "mark";  //JSON tag name
  
  
  JSONArray android = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main.xml);
        getActionBar().setDisplayHomeAsUpEnabled(true);  // for up navigation
        reslist = new ArrayList<HashMap<String, String>>();
      
       
new parsedata().execute()
    }

    private class parsedata extends AsyncTask<String, String, JSONObject> {
       private ProgressDialog pDialog;
       
      
      @Override
        protected void onPreExecute() {
            super.onPreExecute();
             
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
      }
      @Override
        protected JSONObject doInBackground(String... args) {
       
        JSONStudentParser jParser1 = new JSONStudentParser();
      
        
        
        List<NameValuePair> params = new ArrayList<NameValuePair>();
 params.add(new BasicNameValuePair("no_parameter","")); //here we do not want want to                                                            fetch data on such condition hence parameter will be blank.
       JSONObject json = jParser1.getJSONFromUrl(url, params);
        
        return json;
      }
       @Override
         protected void onPostExecute(JSONObject json) {
         pDialog.dismiss();
         try {
  
            android = json.getJSONArray(TAG_RESULT);
            for(int i = 0; i < android.length(); i++){
            JSONObject c = android.getJSONObject(i);
  
            String name = c.getString(TAG_NAME);
            
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(TAG_NAME, name);
            
            reslist.add(map);
            list=(ListView)findViewById(R.id.toplist);
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, reslist,
                R.layout.listview_item,
                new String[] { TAG_NAME }, new int[] {R.id.listitem});
                list.setAdapter(adapter);
                list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                       
                    }
                });
            }
            
             } catch (JSONException e) {
          e.printStackTrace();
        }
       }
    }
    
    
    
}


Enjoy :)

Share because share knowledge, get knowledge.

Comment if you find any error and ask if me you stuck.


No comments:

Post a Comment