gpt4 book ai didi

php - 从mysql获取数据到android中的 ListView 只显示表中的第一项如何修复?

转载 作者:行者123 更新时间:2023-11-29 13:03:32 25 4
gpt4 key购买 nike

我有一个android应用程序,它使用php来使用android和mysql数据库之间的连接。获取 mysql 数据库后,我需要在 android listview 中显示结果。但问题是listview只显示表中的第一项,但是php中取表的结果返回形式显示了洞数据。

如何解决这个问题有人可以帮助我吗?

日志猫

   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
}

ListView 仅显示第一项:
-“id”:“2”, -“用户”:“用户2”

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>

最佳答案

您的问题是以下代码:

  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);
}

您在for语句中返回json.getString(TAG_MESSAGE);,因此for只需循环第一个位置,这样您就可以得到第一行json,输出for语句的return

您的代码必须是:

  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

关于php - 从mysql获取数据到android中的 ListView 只显示表中的第一项如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23026620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com