Android List View using JSON parsing php mysql
Download : Code
MainActivity.java
package com.magic.mysqlphpjson;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;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.os.AsyncTask;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;public class MainActivity extends Activity {private String jsonResult;private String url = "http://192.168.0.2/employee_details.php";private ListView listView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listView = (ListView) findViewById(R.id.listView1);accessWebService();}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}// Async Task to access the webprivate class JsonReadTask extends AsyncTask<String, Void, String> {@Overrideprotected String doInBackground(String... params) {HttpClient httpclient = new DefaultHttpClient();HttpPost httppost = new HttpPost(params[0]);try {HttpResponse response = httpclient.execute(httppost);jsonResult = inputStreamToString(response.getEntity().getContent()).toString();}catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}private StringBuilder inputStreamToString(InputStream is) {String rLine = "";StringBuilder answer = new StringBuilder();BufferedReader rd = new BufferedReader(new InputStreamReader(is));try {while ((rLine = rd.readLine()) != null) {answer.append(rLine);}}catch (IOException e) {// e.printStackTrace();Toast.makeText(getApplicationContext(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();}return answer;}@Overrideprotected void onPostExecute(String result) {ListDrwaer();}}// end async taskpublic void accessWebService() {JsonReadTask task = new JsonReadTask();// passes values for the urls string arraytask.execute(new String[] { url });}// build hash set for list viewpublic void ListDrwaer() {List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();try {JSONObject jsonResponse = new JSONObject(jsonResult);JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");for (int i = 0; i < jsonMainNode.length(); i++) {JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);String name = jsonChildNode.optString("employee name");String number = jsonChildNode.optString("employee no");String outPut = name + "-" + number;employeeList.add(createEmployee("employees", outPut));}} catch (JSONException e) {Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show();}SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,android.R.layout.simple_list_item_1,new String[] { "employees" }, new int[] { android.R.id.text1 });listView.setAdapter(simpleAdapter);Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();}private HashMap<String, String> createEmployee(String name, String number) {HashMap<String, String> employeeNameNo = new HashMap<String, String>();employeeNameNo.put(name, number);return employeeNameNo;}}
activity_main.xml
<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=".MainActivity" ><ListViewandroid:id="@+id/listView1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginTop="14dp" ></ListView></RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.axel.mysqlphpjson"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="17" /><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.axel.mysqlphpjson.MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>
employee_details.php
<?php$host="localhost"; //replace with database hostname$username="root"; //replace with database username$password=""; //replace with database password$db_name="androidmysql"; //replace with database name$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");mysql_select_db("$db_name")or die("cannot select DB");$sql = "select * from emp_info";$result = mysql_query($sql);$json = array();if(mysql_num_rows($result)){while($row=mysql_fetch_assoc($result)){$json['emp_info'][]=$row;}}mysql_close($con);echo json_encode($json);?>
Data Base
Database: `androidmysql`
CREATE TABLE IF NOT EXISTS `emp_info` (`employee name` varchar(50) NOT NULL,`employee no` int(11) NOT NULL AUTO_INCREMENT,PRIMARY KEY (`employee no`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=101 ;---- Dumping data for table `emp_info`--INSERT INTO `emp_info` (`employee name`, `employee no`) VALUES('Vikas_Gutte', 9),('Gutte', 10),('Vikas', 11),('VikasGutte', 12),('GutteVikas', 100);