android 开发,从mysql价值数据到list view,只展示第一行...

文章标签: android,android-listview
2014-11-5 13:15:48     人阅读    

Eclipse中 logcat错误日志显示如下

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


现在这个listView只显示了第一行的数据,如下
- "id": "2", - "user": "user2"

 

我的php文件的加载和展示代码如下
display_user.php
<?php

 

/
/*
 
 * Following code will list all the emp
 
 */

 

/
// response 返回的json字符串数组
$
$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
i
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);
}
}
?>

下面是我android 工程中的java代码,应该是这里的代码有问题


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



    }
}
}

 

下面是我的listVIew的代码,只要是扎实json 数组的视图
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> 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>();

        new getUserList().execute();

        // getListView
        Listiew 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 {



        /**
 
         * 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 parametres = new ArrayList();
 
            // 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 map = new HashMap();



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



        /**
             完成后台任务后弹出 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);



          // 在变量中存储每一个json值
 
          String id = c.getString(TAG_ID);
 
          String user = c.getString(TAG_USER);



          // 创建一个新的HashMap 
 
          HashMap map = new HashMap();



          // 添加每一个子节点到HashMap key
 
          map.put(TAG_ID, id);
 
          map.put(TAG_USER, user);



          //  把HashList  放到 ArrayList 中
 
          usersList.add(map);



          return json.getString(TAG_MESSAGE);
 
    }

你返回了 json.getString(TAG_MESSAGE),只是循环渠道了json中的第一条数据

你需要按照下面的方式修改代码

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 map = new HashMap();



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


原文地址:http://www.itmmd.com/201411/126.html
该文章由 萌萌的IT人 整理发布,转载须标明出处。

android listview使用lv.setadapter() 方法报空指针异常   上一篇
下一篇  android开发中如何使用 alertDialog从listView中删除数据?
精彩回复
我要追加问题,请求站长解决!
姓名:       

《程序员app》专门为程序员量身定做!