Get data from MYSQL and put it in android ListView

  • Replies:10
Hussein Hajjali
  • Forum posts: 1

Jul 23, 2013, 10:59:46 AM via Website

Dear All,
I created a sample android application get the data from the php page connected to mysql db in my localhost.
the data passed correctly and I see all the record in the app.
But I want to put this data in listview, because I want to show only the name when the user press in the name on listview open the details info about.
So please can anyone help me how I can put the record in ListView.

Database:
1CREATE TABLE IF NOT EXISTS `customer` (
2 `FirstName` varchar(20) DEFAULT NULL,
3 `LastName` varchar(20) DEFAULT NULL,
4 `Age` varchar(20) DEFAULT NULL,
5 `Mobile` varchar(20) DEFAULT NULL
6) ENGINE=InnoDB DEFAULT CHARSET=latin1;


PHP page:

1<?php
2 $con=mysql_connect("localhost","root","");
3
4 if(!$con)
5 die('could not connect: ' .mysql_error());
6
7 mysql_select_db("mydatabase",$con);
8
9 $result = mysql_query("SELECT * FROM CUSTOMER");
10
11 while($row=mysql_fetch_assoc($result)){
12 $output[]=$row;
13 }
14
15 print(json_encode($output));
16
17 mysql_close($con); ?>


The Java Android Code:

1package com.ray.testexternaldatabase;
2
3import java.io.BufferedReader;
4import java.io.InputStream;
5import java.io.InputStreamReader;
6
7import org.apache.http.HttpEntity;
8import org.apache.http.HttpResponse;
9import org.apache.http.client.HttpClient;
10import org.apache.http.client.methods.HttpPost;
11import org.apache.http.impl.client.DefaultHttpClient;
12import org.json.JSONArray;
13import org.json.JSONObject;
14
15import android.os.Bundle;
16import android.os.StrictMode;
17import android.app.Activity;
18import android.util.Log;
19import android.view.Menu;
20import android.widget.TextView;
21
22public class MainActivity extends Activity {
23
24 TextView nameView;
25 TextView ageView;
26 TextView jobView;
27 @Override
28 public void onCreate(Bundle savedInstanceState) {
29 super.onCreate(savedInstanceState);
30 setContentView(R.layout.activity_main);
31 StrictMode.enableDefaults(); //STRICT MODE ENABLED
32
33 nameView = (TextView) findViewById(R.id.nametxt);
34 ageView = (TextView) findViewById(R.id.agetxt);
35 jobView = (TextView) findViewById(R.id.jobtxt);
36
37 getData();
38 }
39
40 public void getData(){
41 String result = "";
42 InputStream isr = null;
43 try{
44 HttpClient httpclient = new DefaultHttpClient();
45 HttpPost httppost = new HttpPost(""); //YOUR PHP SCRIPT ADDRESS
46 HttpResponse response = httpclient.execute(httppost);
47 HttpEntity entity = response.getEntity();
48 isr = entity.getContent();
49 }
50 catch(Exception e){
51 Log.e("log_tag", "Error in http connection "+e.toString());
52 nameView.setText("Couldnt connect to database");
53 }
54 //convert response to string
55 try{
56 BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
57 StringBuilder sb = new StringBuilder();
58 String line = null;
59 while ((line = reader.readLine()) != null) {
60 sb.append(line + "\n");
61 }
62 isr.close();
63
64 result=sb.toString();
65 }
66 catch(Exception e){
67 Log.e("log_tag", "Error converting result "+e.toString());
68 }
69
70 //parse json data
71 try {
72 String n = "";
73 String a="";
74 String j="";
75 JSONArray jArray = new JSONArray(result);
76
77 for(int i=0; i<jArray.length();i++){
78 JSONObject json = jArray.getJSONObject(i);
79 n = n + "Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n";
80 a= a + "Age : "+json.getInt("Age")+"\n";
81 j= j + "Job : "+json.getString("Job")+"\n";
82 }
83
84 nameView.setText(n);
85 ageView.setText(a);
86 jobView.setText(j);
87
88 } catch (Exception e) {
89
90 Log.e("log_tag", "Error Parsing Data "+e.toString());
91 }
92
93 }

Reply
Ashish Tripathi
  • Forum posts: 211

Jul 24, 2013, 8:12:25 AM via Website

Hey,

Use Custom ListView with array adapter or base adapter. And use itemselected listener.


If not solve let me know.

Reply
Sou_Maya
  • Forum posts: 4

Aug 30, 2013, 5:04:02 PM via Website

If you find a solution
Please,Can you send it to me.I will be very grateful :)

Reply
Ashish Tripathi
  • Forum posts: 211

Aug 31, 2013, 7:45:56 AM via Website

can u share the URL from which u are getting the data. if possible share. As per by your code review it's good. Are you getting the response? check inputstrem on the android console.

Reply
Sou_Maya
  • Forum posts: 4

Aug 31, 2013, 3:05:52 PM via Website

I can't post an URL """"Message:To prevent spam in our forums, new users may not post links to external sites.""""

I took the code published by ""Hussein Hajjali"" and I modified
but there is no display or in the console (log.i ()) or in the interface

until now I have not found the solution :( and I need it a lot

Reply
Ashish Tripathi
  • Forum posts: 211

Sep 3, 2013, 12:37:42 PM via Website

Ok It means something going wrong with the request. Is it post request or get request. i will share sample code for better idea.

Reply
Sou_Maya
  • Forum posts: 4

Sep 3, 2013, 5:16:23 PM via Website

sincere thanks,,

it is post request .

Reply
Ammara Allauddin
  • Forum posts: 5

Sep 3, 2013, 7:24:16 PM via Website

thanks ......

Reply
Ashish Tripathi
  • Forum posts: 211

Sep 9, 2013, 8:12:27 AM via Website

Due to some busyness i can not reply.

So now it's a sample code which populate the list data coming from the server.

Activity Class

package com.example.parsing_data_demo;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;

import com.example.call_service.Call_Service_Url;
import com.example.parse_data.Authentication_parser;

public class MainActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
new call_url().execute("");



}


@Override
public 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;
}
class call_url extends AsyncTask<String, Void,String>{
ProgressDialog dialog;
@Override
protected void onPreExecute(){
dialog = ProgressDialog.show(MainActivity.this,"Wait..","Loading...");
}
@Override
protected void onPostExecute(String Result){

dialog.dismiss();
setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,Authentication_parser.list));

}
@Override
protected String doInBackground(String... params) {
try{
Call_Service_Url c = new Call_Service_Url();
c.Call_Url();
}
catch(Exception ex){
System.out.println("Main Activity Exception"+ex);
ex.printStackTrace();
}

// TODO Auto-generated method stub
return " ";
}
}
}


Calling Web Service

public class Call_Service_Url {
String data = "";
public void Call_Url(){
try{
DefaultHttpClient client = new DefaultHttpClient();
//
HttpGet request = new HttpGet("Your Service URL");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
//Here you can check whether the response is coming or not. it is the row result. if result is coming than u will parse the response (here is JSON format response)
Authentication_parser p = new Authentication_parser();
p.Parse_Data(data);


Parser the response

public class Authentication_parser {

public static ArrayList<String> list = new ArrayList<String>();
//Declare you xmlor json tag;
protected String a,b,c;

/**
* @param url
* @return
* @throws JSONException
*/
public JSONArray getJSONfromURL(String url) throws JSONException{
String str_response=url;

JSONArray json_Array=new JSONArray(str_response);
return json_Array; //<< retun jsonArray
}
/**
* @param response
*/
public void Parse_Data(String response){


try {
JSONArray jArray = getJSONfromURL(response);
for(int i=0;i<jArray.length();i++){
JSONObject jobj = jArray.getJSONObject(i);
if(jobj.has("return")){

//if your service is giving you the status regarding data is avaliable or not
}
if(jobj.has("parent")){
JSONArray my = jobj.getJSONArray("parent");
for(int j=0;j<my.length();j++){
JSONObject inObj = my.getJSONObject(j);
a = inObj.getString("a");
list.add(a);
}



}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
ex.printStackTrace();
}
}
}



}
catch(Exception ex){
System.out.println("Call Service URL Class Exception=="+ex);
ex.printStackTrace();
}
}

}

Check if it can help you. Any Issue Share

Reply
Sou_Maya
  • Forum posts: 4

Sep 9, 2013, 9:49:05 PM via Website

thank you :) , I will try it

Reply
Ramesh Soni
  • Forum posts: 1

Jul 27, 2015, 8:01:06 AM via Website

Ashish Tripathi

Due to some busyness i can not reply.

So now it's a sample code which populate the list data coming from the server.

Activity Class

package com.example.parsing_data_demo;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ArrayAdapter;

import com.example.call_service.Call_Service_Url;
import com.example.parse_data.Authentication_parser;

public class MainActivity extends ListActivity {

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

// setContentView(R.layout.activity_main);
new call_url().execute("");

}


@Override
public 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;
}
class call_url extends AsyncTask<String, Void,String>{
  ProgressDialog dialog;
  @Override
  protected void onPreExecute(){
      dialog =  ProgressDialog.show(MainActivity.this,"Wait..","Loading...");
  }
  @Override
  protected void onPostExecute(String Result){

      dialog.dismiss();
       setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,Authentication_parser.list));

  }
  @Override
  protected String doInBackground(String... params) {
      try{
      Call_Service_Url c = new Call_Service_Url();
      c.Call_Url();
      }
      catch(Exception ex){
          System.out.println("Main Activity Exception"+ex);
          ex.printStackTrace();
      }

      // TODO Auto-generated method stub
      return " ";
  }
}

}

Calling Web Service

public class Call_Service_Url {
String data = "";
public void Call_Url(){
try{
DefaultHttpClient client = new DefaultHttpClient();
//
HttpGet request = new HttpGet("Your Service URL");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
//Here you can check whether the response is coming or not. it is the row result. if result is coming than u will parse the response (here is JSON format response)
Authentication_parser p = new Authentication_parser();
p.Parse_Data(data);

Parser the response

public class Authentication_parser {

public static ArrayList list = new ArrayList();
//Declare you xmlor json tag;
protected String a,b,c;

/**
* @param url
* @return
* @throws JSONException
*/
public JSONArray getJSONfromURL(String url) throws JSONException{
String str_response=url;

     JSONArray json_Array=new JSONArray(str_response);
     return json_Array; //<< retun jsonArray

}
/**
* @param response
*/
public void Parse_Data(String response){

  try {
      JSONArray jArray = getJSONfromURL(response);
      for(int i=0;i<jArray.length();i++){
      JSONObject jobj = jArray.getJSONObject(i);
       if(jobj.has("return")){

      //if your service is giving you the status regarding data is avaliable or not
      }
       if(jobj.has("parent")){
      JSONArray my = jobj.getJSONArray("parent");
      for(int j=0;j<my.length();j++){
      JSONObject inObj = my.getJSONObject(j);
      a = inObj.getString("a");
      list.add(a);
        }

}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
ex.printStackTrace();
}
}
}

  }
  catch(Exception ex){
      System.out.println("Call Service URL Class Exception=="+ex);
      ex.printStackTrace();
  }
  }

  }

Check if it can help you. Any Issue Share

Sir giving an exception Could'nt connect to database
please give me a proper solution to solve the problem
at this time i'm running on the localhost of this code

Reply