Android JSON解析器和listview出错
我为我的网站制作了一个应用程序,它从我的网站brainstorm.web44.net获取som信息 (这些帖子只是为了测试!)并将它们放在自定义列表视图中 以下是java代码:Android JSON解析器和listview出错,android,json,listview,logcat,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";
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;
}
}
}
Json:
{
"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"
]
}
}
]
}
{
“状态”:“确定”,
“计数”:2,
“总计数”:2,
"页":一,,
“员额”:[
{
“id”:17,
“类型”:“职位”,
“slug”:“json解析器”,
“url”:”http://brainstorm.web44.net/?p=17",
“状态”:“发布”,
“标题”:“JSON解析器”,
“title_plain”:“JSON解析器”,
“内容”:“JSON解析器!\n”,
“摘录”:“JSON解析器!\n”,
“日期”:“2013-06-27 09:02:55”,
“修改”:“2013-06-27 09:02:55”,
“类别”:[],
“标签”:[],
“作者”:{
“id”:1,
“slug”:“admin”,
“名称”:“管理员”,
“名字”:“,
“姓氏”:“,
“昵称”:“管理员”,
“url”:“,
“说明”:”
},
“评论”:[…],
“附件”:[],
“注释计数”:0,
“评论状态”:“打开”,
“自定义字段”:{
“单_布局”:[
"0"
]
}
},
{
“id”:14,
“类型”:“职位”,
“鼻涕虫”:“超级月亮准备被看见”,
“url”:”http://brainstorm.web44.net/?p=14",
“状态”:“发布”,
“标题”:“超级月亮准备好被看到了!”,
“title_plain”:“超级月亮准备好被看到了!”,
“内容”:“今晚你将看到满月!\n”,
“节选”:“今晚你将看到满月!\n”,
“日期”:“2013-06-26 16:56:19”,
“修改”:“2013-06-26 17:18:11”,
“类别”:[],
“标签”:[],
“作者”:{
“id”:1,
“slug”:“admin”,
“名称”:“管理员”,
“名字”:“,
“姓氏”:“,
“昵称”:“管理员”,
“url”:“,
“说明”:”
},
“评论”:[…],
“附件”:[],
“注释计数”:0,
“评论状态”:“打开”,
“自定义字段”:{
“单_布局”:[
"0"
]
}
}
]
}
编辑:这是异步任务的新代码:
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);
}
}
公共类读取扩展异步任务{
@凌驾
受保护的Void doInBackground(Void…arg0){
//TODO自动生成的方法存根
试一试{
StringBuilder url=新的StringBuilder(url);
HttpGet=newhttpget(url.toString());
HttpResponse r=client.execute(get);
int status=r.getStatusLine().getStatusCode();
如果(状态==200){
HttpEntity e=r.getEntity();
字符串数据=EntityUtils.toString(e);
JSONObject o=新的JSONObject(数据);
titles=新的JSONArray(o.getString(“posts”);
}否则{
Toast t=Toast.makeText(MainActivity.this,“Error”,Toast.LENGTH\u LONG);
t、 show();
}
对于(int i=0;i
您可以使用单个异步任务进行解析,并在listview中显示数据。我使用自定义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;
}
}
public类MainActivity扩展了ListActivity{
JSONArray标题;
HttpClient;
进展性帕金森病;
最终静态字符串URL=”http://brainstorm.web44.net/?json=1";
ArrayList title=新的ArrayList();
ArrayList内容=新建ArrayList();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
pd=新建进度对话框(MainActivity.this);
pd.setMessage(“加载…”);
client=新的DefaultHttpClient();
新建Read().execute();
}
公共类读取扩展异步任务{
@凌驾
受保护的void onPreExecute(){
//TODO自动生成的方法存根
pd.show();
super.onPreExecute();
}
@凌驾
受保护的void onPostExecute(void结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
pd.d
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;
}
}
<?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>