JSON, PHP, MySQL with AsyncTask ProgressDialog

Here is the implementation detail.
In MySQL create database LOGIN. In database create table REGIS. This table consists of three columns. First is ID, which is auto_increment and primary_key and having data type INT. Second column is Username, which has data type VARCHAR(20). Three colomn is Password, which has data type VARCHAR(20).

Next step :

connect.php

<?php

   $conn = mysql_connect("localhost","username","password");
  $db = mysql_select_db("login");

?>

select.php

<?php
include_once("connect.php");
$sqlString = "select * from REGIS order by ID  ";
$rs = mysql_query($sqlString);

if($rs){
   while($objRs = mysql_fetch_assoc($rs)){
      $output[] = $objRs;
   }
   echo json_encode($output);
}

mysql_close();

?>

class.java

package com.login.app;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity {
	TextView text_1,text_2 ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		new task().execute();
	}

class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(Login.this);
    InputStream is = null ;
    String result = "";
    protected void onPreExecute() {
       progressDialog.setMessage("Download data...");
       progressDialog.show();
       progressDialog.setOnCancelListener(new OnCancelListener() {
	@Override
		public void onCancel(DialogInterface arg0) {
		task.this.cancel(true);
	   }
	});
     }
       @Override
	protected Void doInBackground(String... params) {
	  String url_select = "http://yourwebsite/select.php";

	  HttpClient httpClient = new DefaultHttpClient();
	  HttpPost httpPost = new HttpPost(url_select);

          ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

	    try {
		httpPost.setEntity(new UrlEncodedFormEntity(param));

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

		//read content
		is =  httpEntity.getContent();					

		} catch (Exception e) {

		Log.e("log_tag", "Error in http connection "+e.toString());
		}
	try {
	    BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = "";
		while((line=br.readLine())!=null)
		{
		   sb.append(line+"\n");
		}
			is.close();
			result=sb.toString();				

				} catch (Exception e) {
					// TODO: handle exception
					Log.e("log_tag", "Error converting result "+e.toString());
				}

			return null;

		}
	protected void onPostExecute(Void v) {

		// ambil data dari Json database
		try {
			JSONArray Jarray = new JSONArray(result);
			for(int i=0;i<Jarray.length();i++)
			{
			JSONObject Jasonobject = null;
			text_1 = (TextView)findViewById(R.id.txt1);
			Jasonobject = Jarray.getJSONObject(i);

			//get an output on the screen
			String id = Jasonobject.getString("id");
			String name = Jasonobject.getString("username");
			String password = Jasonobject.getString("password");
		    text_1.append(id+"\t\t"+name+"\t\t"+password+"\t\t"+"\n");

			}
			this.progressDialog.dismiss();

		} catch (Exception e) {
			// TODO: handle exception
			Log.e("log_tag", "Error parsing data "+e.toString());
		}
	}
    }
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
        <TextView
            android:id="@+id/txt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

</LinearLayout>
About these ads

12 thoughts on “JSON, PHP, MySQL with AsyncTask ProgressDialog

  1. HI,nice post i loved it,but i have a problem while using the above code.

    i wan to display all results of the json object in to a listview using the simpleadapter,
    i did correct but i am not getting the resluts in listview in my emulator ,please help.
    Thanks in advance

  2. I’m getting an error in the log cat>>>>

    Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray

    it's the error of trycatch block, can you please give me a solution for this?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s