将JSON输出解析为ListView

时间:2012-02-03 09:23:57

标签: android json android-listview

我从Android设备连接到服务器并查询数据库并在屏幕上显示结果。但是我想在ListView中显示我的结果。如何让我的代码显示在ListView中?目前它只是解析数据并在屏幕上显示。如何为ContactName的每个值赋予参考值?以下是我的代码:

   public class DbConnectActivity extends Activity {
/** Called when the activity is first created. */

   TextView txt;
@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. 
    LinearLayout rootLayout = new LinearLayout(getApplicationContext()); 
    txt = new TextView(getApplicationContext()); 
    rootLayout.addView(txt); 
    setContentView(rootLayout); 

    // Set the text and call the connect function. 
    txt.setText("Connecting...");
  //call the method  to run the data retreival
    txt.setText(getServerData(KEY_121));



}
public static final String KEY_121 = "http://10.0.2.2/dbconnect.php"; //i use my real ip 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("EngID","1"));

    //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);
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
            //return result;


    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }
    //parse json data
    try{
            JSONArray jArray = new JSONArray(result);
            for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    Log.i("log_tag","Name: "+json_data.getString("ContactName")
                           );
                    //Get an output to the screen
                    returnString += "\n\t" + jArray.getJSONObject(i);

            }
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return returnString;
}   

}

5 个答案:

答案 0 :(得分:4)

public class JsonExampleActivity extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, this.fetchTwitterPublicTimeline()));
    }

    public ArrayList<String> fetchTwitterPublicTimeline()
    {
        ArrayList<String> listItems = new ArrayList<String>();

        try {
            URL twitter = new URL("your url here");

            URLConnection tc = twitter.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    tc.getInputStream()));

            String line;
            while ((line = in.readLine()) != null) {
                  JSONObject ja = new JSONObject(line);
              /*
                //for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = ja.getJSONObject("_api_error");
                    listItems.add(jo.getString("name"));*/

                    JSONArray jobj=ja.getJSONArray("artists");
                    //JSONArray ja = new JSONArray(line);
                for (int i = 0; i < jobj.length(); i++) {
                    JSONObject jo = jobj.getJSONObject(i);
                    listItems.add(jo.getString("artist_name"));
                }
               // }
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return listItems;
    }
}

答案 1 :(得分:0)

我要做的最简单的事情是将JSONArray放在某个ArrayList中并在arrayadapter中使用它

答案 2 :(得分:0)

您可以将所有json对象添加到列表中,然后从那里加载列表,但是您已准备好返回单个字符串的方法。你可以使用以下内容:

使用

String[] tokens=returnString.split("\n\r");
ArrayAdapter adapter=new ArrayAdapter(this, android.R.layout.simple_list_item_1, tokens);
listView.setAdapter(adapter);

答案 3 :(得分:0)

了解自定义适配器的基础知识然后......

  

每当你想用ListView中的视图进行处理时   需要创建一个可以处理逻辑的自定义适配器   实现并在必要时将该信息传递给视图。

答案 4 :(得分:0)

我确保您在后台线程中提出请求(例如异步任务或意向服务),否则如果需要很长时间,您的应用可能会崩溃。

关于列表活动

http://www.vogella.de/articles/AndroidListView/article.html

本教程将向您展示如何创建自定义模型并使用自定义xml将其填充到列表视图中。