I have android application that use connection between android and mysql database using php. after fetching the mysql database i need to display the result in android listview. but the problem is that the listview only display the first item in the table, but the result return form fetching the table in php show the hole data.
how to fix this problem can anyone help me ??
logCat
04-1205: 40: 32.901: D/AllUsers: (1254): {
"message": "DISPLAYED Success",
"userlist": [
{
"id": "2",
"user": "user2"
},
{
"id": "3",
"user": "michel"
},
{
"id": "4",
"user": "georges"
},
{
"id": "5",
"user": "testtest1"
}
],
"success": 1
}
the list view just show the first item:
- "id": "2", - "user": "user2"
- "id": "2", - "user": "user2"
display_user.php
<?php
/*
* Following code will list all the emp
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all emp from emp table
$result = mysql_query("SELECT *FROM users") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// emp node
$response["userlist"] = array();
while ($row = mysql_fetch_array($result)) {
$response["success"] = 1;
// temp user array
$userlist = array();
$userlist["id"] = $row["id"];
$userlist["user"] = $row["user"];
// push single Employee into final response array
array_push($response["userlist"], $userlist);
}
// success
$response["message"] = "DISPLAYED Success";
// echoing JSON response
echo json_encode($response);
} else {
// no emp found
$response["success"] = 0;
$response["message"] = "No User found";
// echo no users JSON
echo json_encode($response);
}
?>
JSONParser.java
package com.devleb.loginDemo;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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.i("TagCovertS", "["+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;
}
}
UserListActivity.java
package com.devleb.loginDemo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
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.app.ListActivity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class UserListActivity extends ListActivity {
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> usersList;
private static String url_display_user = "http://10.0.3.2/android_connect/display_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_ID = "id";
private static final String TAG_USERS = "userlist";
private static final String TAG_USER = "user";
//private static final String TAG_NAME = "name";
// employees JSONArray
JSONArray users = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_list);
usersList = new ArrayList<HashMap<String, String>>();
new getUserList().execute();
// getListView
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// String id = ((TextView) view.findViewById(R.id.uid)).getText()
// .toString();
// Intent in = new Intent(getBaseContext(), StatusList.class);
// in.putExtra(TAG_ID, uid);
// startActivity(in);
}
});
}
class getUserList extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
UserListActivity.this.setProgressBarIndeterminateVisibility(true);
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Building Parameters
List<NameValuePair> parametres = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url_display_user,
"GET", parametres);
// Check your log cat for JSON reponse
Log.d("All Users: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
users = json.getJSONArray(TAG_USERS);
// looping through All Users
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_USER, user);
// adding HashList to ArrayList
usersList.add(map);
return json.getString(TAG_MESSAGE);
}
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog after getting all products
if (result != null) {
UserListActivity.this
.setProgressBarIndeterminateVisibility(false);
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
UserListActivity.this, usersList,
R.layout.list_item, new String[] { TAG_ID,
TAG_USER }, new int[] { R.id.uid,
R.id.name });
// updating listview
setListAdapter(adapter);
}
});
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG)
.show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user_list, menu);
return true;
}
}
activity_user_list.xml
<?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"
android:orientation="vertical"
android:background="@drawable/background_1">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_item.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="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/uid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:paddingTop="6dip"
android:textColor="#FFFFFF"
android:textSize="17dip"
android:textStyle="bold" />
</LinearLayout>
your problem is bellow code:
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_USER, user);
// adding HashList to ArrayList
usersList.add(map);
return json.getString(TAG_MESSAGE);
}
you return
json.getString(TAG_MESSAGE);
in for
statement so for
just loop for first position so you get fist line of your json, put out return from for statement
your code must be:
for (int i = 0; i < users.length(); i++) {
JSONObject c = users.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_USER, user);
// adding HashList to ArrayList
usersList.add(map);
}
return json.getString(TAG_MESSAGE); <--- move this line after for statement
0 comments:
Post a Comment