开发者

populate custom multiline listview in android using a hashmap

开发者 https://www.devze.com 2023-03-20 23:42 出处:网络
Hi i am trying to populate a custom listview using arrays from a http client here is a the code could someone please give me a hint of what I am doing wrong

Hi i am trying to populate a custom listview using arrays from a http client here is a the code could someone please give me a hint of what I am doing wrong

    package com.capefield.msemakweli;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.SimpleAdapter;


public class viewComms extends ListActivity {

    public String names[];
    public String commsFromDb[];


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.comment_list);

        //create http client to gather comments
        try{
        HttpClient getComment = new DefaultHttpClient();
        HttpGet pullComm = new HttpGet();
        pullComm.setURI(new URI("http://msemakweli.olalashe.com/getComments.php"));
        HttpResponse comments = getComment.execute(pullComm);
        if (comments.getStatusLine().getStatusCode() == 200) {
            HttpEntity entit = comments.getEntity();
            if (entit !=null){
                InputStream commStream = entit.getContent();
                JSONArray commentAR = new JSONArray(
                        convertStreamToString(commStream));
                if (commentAR.length()==0){

                }else{
                    names = new String[commentAR.length()];
                    commsFromDb = new String [commentAR.length()];

                    for (int i = 0; i < commentAR.length(); i++) {
                        JSONObject OComm = commentAR.getJSONObject(i);
                        names[i] = OComm.getString("name");
                        commsFromDb[i] = OComm.getString("comment");
                    }
                    ArrayList<HashMap<String, String>> commList = new ArrayList<HashMap<String, String>>();
                    for (int j=0; j<commentAR.length(); j++){
                        HashMap<String, String> objComm = new HashMap<String, String>();
                        objComm.put("name", names[j]);
                        objComm.put("suggestiom,",开发者_开发百科 commsFromDb[j]);
                        commList.add(objComm);

                        SimpleAdapter adapter =new SimpleAdapter(
                                this,
                                commList,
                                R.layout.comment_row,
                                new String[]{"name","suggestiom,"},
                                new int[]{R.id.CommName, R.id.CommText}
                                );
                        setListAdapter(adapter);
                    }










                }

            }

        }



        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException 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();
        }finally{

        }


    }

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the
         * BufferedReader.readLine() method. We iterate until the BufferedReader
         * return null which means there's no more data to read. Each line will
         * appended to a StringBuilder and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }



}

and here is the stack trace i get when i run the activity

07-17 10:29:14.713: WARN/System.err(4936): org.json.JSONException: No value for comment
07-17 10:29:14.723: WARN/System.err(4936):     at org.json.JSONObject.get(JSONObject.java:354)
07-17 10:29:14.733: WARN/System.err(4936):     at org.json.JSONObject.getString(JSONObject.java:510)
07-17 10:29:14.733: WARN/System.err(4936):     at com.capefield.msemakweli.viewComms.onCreate(viewComms.java:58)
07-17 10:29:14.733: WARN/System.err(4936):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-17 10:29:14.733: WARN/System.err(4936):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
07-17 10:29:14.733: WARN/System.err(4936):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-17 10:29:14.743: WARN/System.err(4936):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-17 10:29:14.743: WARN/System.err(4936):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-17 10:29:14.743: WARN/System.err(4936):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-17 10:29:14.743: WARN/System.err(4936):     at android.os.Looper.loop(Looper.java:123)
07-17 10:29:14.743: WARN/System.err(4936):     at android.app.ActivityThread.main(ActivityThread.java:4627)
07-17 10:29:14.743: WARN/System.err(4936):     at java.lang.reflect.Method.invokeNative(Native Method)
07-17 10:29:14.743: WARN/System.err(4936):     at java.lang.reflect.Method.invoke(Method.java:521)
07-17 10:29:14.753: WARN/System.err(4936):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-17 10:29:14.753: WARN/System.err(4936):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-17 10:29:14.753: WARN/System.err(4936):     at dalvik.system.NativeStart.main(Native Method)

here is comment_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <ListView 
    android:id="@+id/android:list" 
    android:layout_height="wrap_content" 
    android:layout_width="match_parent"></ListView>

</LinearLayout>

thankyou


  ArrayList<HashMap<String, String>> commList = new ArrayList<HashMap<String, String>>();
                for (int j=0; j<commentAR.length(); j++){
                    HashMap<String, String> objComm = new HashMap<String, String>();
                    objComm.put("name", names[j]);
                    objComm.put("suggestiom,", commsFromDb[j]);
                    commList.add(objComm);
                }

There is no reason to use an entire HashMap instance just to map one key to one value. Use BasicNameValuePair, or String[] instead.

Your entire convertStringToStream() method can be replaced with BasicResponseHandler -- 2 lines of code, instantiate and handle the response. Actually, you can cut out even more of your code with BasicResponseHandler..

http://developer.android.com/reference/org/apache/http/impl/client/BasicResponseHandler.html

Although, if your code is crashing, this may more may not fix it (shotgun debugging is the term). If you include a stack trace we can tell you what is causing the failure. Check show->view->android->logcat

0

精彩评论

暂无评论...
验证码 换一张
取 消