JSON解析器和列表视图出错

时间:2013-06-27 18:19:17

标签: android json listview logcat

我为我的网站制作了一个应用程序,它从我的网站brainstorm.web44.net获取了som信息 (这些帖子只是用于测试!)并将它们放在自定义列表视图中。

这是java代码:

public class MainActivity extends ListActivity {

    JSONArray titles;
    HttpClient client;
    final static String URL = "http://brainstorm.net.com/?json=1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        client = new DefaultHttpClient();

        String[] from = new String[] { "Title", "Description" };
        int[] to = new int[] { R.id.txtTitle, R.id.txtContent };

        List<HashMap<String, Object>> fillMaps;
        try {

            fillMaps = setContentAndTitle(new Read().execute("title").get(),
                    new Read().execute("content").get());
            SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
                    R.layout.list_item, from, to);
            setListAdapter(adapter);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

    private List<HashMap<String, Object>> setContentAndTitle(String[] titles,
            String[] descriptions) {
        // TODO Auto-generated method stub
        List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();

        for (int number = 0; number < titles.length; number++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("Title", titles[number]);
            map.put("Description", descriptions[number]);
            fillMaps.add(map);
        }
        return fillMaps;
    }

    public JSONArray Title() throws ClientProtocolException, IOException,
            JSONException {
        StringBuilder url = new StringBuilder(URL);
        HttpGet get = new HttpGet(url.toString());
        HttpResponse r = client.execute(get);
        int status = r.getStatusLine().getStatusCode();
        if (status == 200) {
            HttpEntity e = r.getEntity();
            String data = EntityUtils.toString(e);
            JSONArray brainstorm = new JSONArray(data);
            return brainstorm;
        } else {

            return null;
        }
    }

    public class Read extends AsyncTask<String, Integer, String[]> {

        @Override
        protected String[] doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            List<String> titlesArray = new ArrayList<String>();
            try {
                titles = Title();
                for (int i = 0; i < titles.length(); i++) {

                    JSONObject title = titles.getJSONObject(i);
                    String s = title.getString("title");
                    titlesArray.add(s);
                }
            } catch (JSONException 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();
            }

            String[] arr = toStringArray(titlesArray.toArray());
            return arr;
        }

        private String[] toStringArray(Object[] array) {
            // TODO Auto-generated method stub
            String[] arr = new String[array.length];
            for(int i=0;i<arr.length;i++){
            arr[i]=array[i].toString(); 
            }

            return null;
        }

    }

}

Logcat:

06-27 18:11:32.768: E/AndroidRuntime(1809): Caused by: java.lang.NullPointerException
06-27 18:11:32.768: E/AndroidRuntime(1809):     at com.tendariusprod.brainstorm.MainActivity.setContentAndTitle(MainActivity.java:64)
06-27 18:11:32.768: E/AndroidRuntime(1809):     at com.tendariusprod.brainstorm.MainActivity.onCreate(MainActivity.java:43)
杰森:

{
"status": "ok",
"count": 2,
"count_total": 2,
"pages": 1,
"posts": [
    {
        "id": 17,
        "type": "post",
        "slug": "json-parser",
        "url": "http://brainstorm.web44.net/?p=17",
        "status": "publish",
        "title": "JSON Parser",
        "title_plain": "JSON Parser",
        "content": "<p>JSON Parser!</p>\n",
        "excerpt": "<p>JSON Parser!</p>\n",
        "date": "2013-06-27 09:02:55",
        "modified": "2013-06-27 09:02:55",
        "categories": [],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "admin",
            "name": "admin",
            "first_name": "",
            "last_name": "",
            "nickname": "admin",
            "url": "",
            "description": ""
        },
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "open",
        "custom_fields": {
            "single_layout": [
                "0"
            ]
        }
    },
    {
        "id": 14,
        "type": "post",
        "slug": "supermoon-ready-to-be-seen",
        "url": "http://brainstorm.web44.net/?p=14",
        "status": "publish",
        "title": "Supermoon ready to be seen!",
        "title_plain": "Supermoon ready to be seen!",
        "content": "<p>You will see the moon in its all splendore tonight!</p>\n",
        "excerpt": "<p>You will see the moon in its all splendore tonight!</p>\n",
        "date": "2013-06-26 16:56:19",
        "modified": "2013-06-26 17:18:11",
        "categories": [],
        "tags": [],
        "author": {
            "id": 1,
            "slug": "admin",
            "name": "admin",
            "first_name": "",
            "last_name": "",
            "nickname": "admin",
            "url": "",
            "description": ""
        },
        "comments": [],
        "attachments": [],
        "comment_count": 0,
        "comment_status": "open",
        "custom_fields": {
            "single_layout": [
                "0"
            ]
        }
    }
]
}

编辑:这是asynctask的新代码:

  public class Read extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            try {
                StringBuilder url = new StringBuilder(URL);
                HttpGet get = new HttpGet(url.toString());
                HttpResponse r = client.execute(get);
                int status = r.getStatusLine().getStatusCode();
                if (status == 200) {
                    HttpEntity e = r.getEntity();
                    String data = EntityUtils.toString(e);
                    JSONObject o =new JSONObject(data);
                    titles = new JSONArray(o.getString("posts"));
                } else {
                    Toast t = Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG);
                    t.show();
                }
                for (int i = 0; i < titles.length(); i++) {

                    JSONObject title = titles.getJSONObject(i);
                    String s = title.getString("title");
                    String b = title.getString("content");
                    descArray.add(b);
                    titlesArray.add(s);
                }
            } catch (JSONException 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();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            List<HashMap<String, Object>> fillMaps = new ArrayList<HashMap<String, Object>>();

            String[] arr1 = toStringArray(titlesArray.toArray()), arr2 = toStringArray(descArray
                    .toArray());

            for (int number = 0; number < arr1.length; number++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("Title", arr1[number]);
                map.put("Description", arr2[number]);
                fillMaps.add(map);

                String[] from = new String[] { "Title", "Description" };
                int[] to = new int[] { R.id.txtTitle, R.id.txtContent };


                SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, fillMaps, R.layout.list_item, from, to);
                setListAdapter(adapter);

            }

        }

1 个答案:

答案 0 :(得分:1)

您可以使用单个asynctask进行解析并在listview中显示数据。我使用自定义列表视图来显示内容和标题。

 public class MainActivity extends ListActivity {

    JSONArray titles;
    HttpClient client;
    ProgressDialog pd;
    final static String URL = "http://brainstorm.web44.net/?json=1";
    ArrayList<String> title = new ArrayList<String>(); 
    ArrayList<String> content = new ArrayList<String>(); 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Loading...");
        client = new DefaultHttpClient();
         new Read().execute();

    }


    public class Read extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            pd.show();
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pd.dismiss();
           CustomAdapter cus = new CustomAdapter();
           setListAdapter(cus);
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(URL);
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                 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();
                 String result=sb.toString();
                 try {
                    JSONObject jsono = new JSONObject(result);
                    JSONArray jsonarray = new JSONArray(jsono.getString("posts"));
                    for(int i=0;i<jsonarray.length();i++)
                    {
                    JSONObject job1 = (JSONObject) jsonarray.get(i);    
                    String titl = job1.getString("title");
                    String con = job1.getString("content");
                    title.add(titl);
                    content.add(con) ;
                    Log.i("......", titl);
                    Log.i("......", con);
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

    }
 class CustomAdapter extends BaseAdapter
 {
     LayoutInflater mInflater;
     public CustomAdapter()
     {
     mInflater = LayoutInflater.from(MainActivity.this);  
     }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return title.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder; 

        if (convertView == null) { 
            convertView = mInflater.inflate(R.layout.list_item, 
                    parent, false);
            holder = new ViewHolder(); 
            holder.tv1 = (TextView) convertView.findViewById(R.id.textView1); 
            holder.tv2 = (TextView) convertView.findViewById(R.id.textView2); 

           convertView.setTag(holder); 
       } else { 
           holder = (ViewHolder) convertView.getTag(); 
       } 

       holder.tv1.setText(title.get(position)); 
       holder.tv2.setText(content.get(position)); 

       return convertView; 
    }

 }
 static class ViewHolder
 { 
     TextView tv1,tv2;

 }
}

list_itemt.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="22dp"
        android:text="TextView" />

</RelativeLayout>

快照

enter image description here