填充列表视图

时间:2011-09-29 16:28:57

标签: android mysql listview

我正在开发一个最后一年的项目,我陷入了困境。我必须从我的数据库(MySQL数据库)中检索医生的名字,并在列表视图中显示它。我能够与服务器建立连接并检索值,但是当我尝试在列表视图中显示值时,应用程序崩溃了!

我尝试了 [Hello,Views,List View] [4] 中给出的相同示例。

适用于预定义的数组,如

private String lv_arr[]={"Android","iPhone","BlackBerry","AndroidPeople"};

但是对于从数据库检索的字符串数组,它显示运行时异常。有什么方法可以实现这个目标吗?

package com.proj;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.widget.*;
import android.app.ListActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class proj extends ListActivity {
    /** Called when the activity is first created. */

    public int n=0;
    public int t=0;
    public int i=0;

    public String name[]=new String[30];
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Create a crude view - this should really be set via the layout resources
        // but since its an example saves declaring them in the XML.
        TextView txt=(TextView)findViewById(R.id.tv);;
        //Call the method to run the data retrieval
        getServerData(KEY_121);
        setListAdapter(new ArrayAdapter(this,
                       android.R.layout.simple_list_item_1, name));
    }

    public static final String KEY_121 = "http://10.0.2.2/doc.php"; //I use my real IP address here.

    private String getServerData(String returnString) {
        InputStream is = null;

        String result = "";
        //The year data to send.
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("year","1970"));

        //HTTP post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(KEY_121);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }
        catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

        //Convert response to string
        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();
            result=sb.toString();
        }
        catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
        }
        //Parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);
            for(i=0;i<jArray.length();i++)
            {
                JSONObject json_data = jArray.getJSONObject(i);
                n=jArray.length();
                name[i]=json_data.getString("name");

                //Get an output to the screen
                returnString += "\n\t" + jArray.getJSONObject(i);
            }
        }
        catch(JSONException e)
        {
            Log.e("log_tag", "Error parsing data "+e.toString());
            e.printStackTrace();
        }
        return returnString;
    }
}

2 个答案:

答案 0 :(得分:2)

您正在使用

<强> 1)。

android:id="@+id/list"
ListView中的

,但如果您通过ListActivity扩展活动,则必须使用

android:id = "@android:id/list"

<强> 2)。

您在此处返回String[],而不是String

private String[] getServerData(String returnString) {
    .......
    JSONArray jArray = new JSONArray(result);
    name = new String[jArray.length()];
    for(i=0;i<jArray.length();i++)
    {
        JSONObject json_data = jArray.getJSONObject(i);
        name[i]=json_data.getString("name");
    }
    return name;
}

在ArrayAdapter中,这样做:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getServerData(KEY_121));
setListAdapter(adapter);

答案 1 :(得分:0)

public String name[];

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a crude view - this should really be set via the layout resources
    // but since its an example saves declaring them in the XML.
    TextView txt=(TextView)findViewById(R.id.tv);;
        ...
        ...

    try {
        JSONArray jArray = new JSONArray(result);
        name[]=new String[jArray.length()];
        for(i=0;i<jArray.length();i++)
        {
            JSONObject json_data = jArray.getJSONObject(i);
            n=jArray.length();
            name[i]=json_data.getString("name");

            //Get an output to the screen
            returnString += "\n\t" + jArray.getJSONObject(i);
        }
    }
    catch(JSONException e)
    {
        Log.e("log_tag", "Error parsing data "+e.toString());
        e.printStackTrace();
    }

似乎初始化大小为30的name[]可能太小了。