首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ListView来自AsyncTask和JSONParser

ListView来自AsyncTask和JSONParser
EN

Stack Overflow用户
提问于 2014-10-19 22:02:00
回答 2查看 1.5K关注 0票数 0

我要从我的服务器上从json那里获取消息。

此外,我有一个菜单按钮,刷新我的列表视图。

我不知道我哪里错了!

JSON文件 (http://10.0.2.2:8020/test/index.php)

代码语言:javascript
复制
{
"news":
[
    {"id":"1","title":"Number one","description":"This is First Message","created_at":"2014-04-04"},
    {"id":"2","title":"Number two","description":"This is Second Message","created_at":"2014-04-04"},
    {"id":"3","title":"Number three","description":"This is Third Message","created_at":"2014-04-04"}
]
}

JSONParser.java

代码语言:javascript
复制
package com.example.myapp.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {}

public JSONObject getJSONFromUrl(String url)
{
    /**
     * Making Http Request
     */
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }
    catch(UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch(ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    /**
     * JSON retreive value 
     */
    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();
        json = sb.toString();
    }
    catch(Exception e)
    { e.printStackTrace(); }
    /**
     * Parse the String to JSON OBJECT 
     */
    try
    {   jObj = new JSONObject(json);  }
    catch (JSONException e)
    {   e.printStackTrace();    }
    /**
     * Return JSON Object
     */
    return jObj;    
}
}

RefreshNews.java

代码语言:javascript
复制
package com.example.myapp.library;

import com.example.myapp.adapter.NewsListAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;

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

private String url;
private ListView listView;
private Activity context;
/////////////////////////
private JSONParser jsonParser;
private JSONObject jObj;
private NewsListAdapter myAdapter;
private ProgressDialog pDialog;
//////////////////////////////////
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_CREATED_AT = "created_at";
////////////////////////////////////////////////////////////
private String[] title;
private String[] description;
private String[] created_at;


/**
 * Constructor
 **/
public RefreshNews(Activity context, ListView listView, String url)
{
    this.context = context;
    this.listView = listView;
    this.url = url;
}

@Override
protected void onPreExecute() {
    pDialog = new ProgressDialog(context);
    pDialog.setCancelable(false);
    pDialog.setMessage("Loading ...");
    pDialog.show();
    super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {
    jsonParser = new JSONParser();
    jObj = jsonParser.getJSONFromUrl(url);
    try 
    {
        JSONArray News = jObj.getJSONArray(TAG_NEWS);
        for(int i=0; i<News.length(); i++)
        {
            JSONObject temp = News.getJSONObject(i);
            title[i] = temp.getString(TAG_TITLE);
            description[i] = temp.getString(TAG_DESCRIPTION);
            created_at[i] = temp.getString(TAG_CREATED_AT);
        }

    } 
    catch (JSONException e) 
    {
            Toast.makeText(context, "Error in doInBackground ...", 5000).show();
    }
    return null;
}

@Override
protected void onPostExecute(Void result) {
    myAdapter = new NewsListAdapter(context, title, description, created_at);
    listView.setAdapter(myAdapter);
    pDialog.dismiss();
    super.onPostExecute(result);
}

}

MainActivity.java

代码语言:javascript
复制
package com.example.myapp;

import com.example.myapp.library.RefreshNews;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

public class MainActivity extends Activity {

private static final String url = "http://10.0.2.2:8020/test/index.php";

ListView list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list = (ListView) findViewById(R.id.listView1);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.action_refresh)
    {
        RefreshNews refreshNews = new RefreshNews(MainActivity.this, list, url);
        refreshNews.execute();
    }
    return super.onOptionsItemSelected(item);
}

}

Manifest.xml

代码语言:javascript
复制
<uses-permission android:name="android.permission.INTERNET"/>

任何建议都将不胜感激..。

LogCat:

代码语言:javascript
复制
10-19 04:34:15.215: W/System.err(13788): org.json.JSONException: Expected ':' after n at character 4 of {n  "news":n    [n      {"id":"1","title":"Number one","description":"This is First Message","created_at":"2014-04-04"},n       {"id":"2","title":"Number two","description":"This is Second Message","created_at":"2014-04-04"},n      {"id":"3","title":"Number three","description":"This is Third Message","created_at":"2014-04-04"}n  ]n}nn

更新:

我的JSON似乎错了。我编辑了我的JSONParser类:

代码语言:javascript
复制
sb.append(line + "n");   ---->    sb.append(line + "\n");

但是错误已经发生了!

有什么建议吗?!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-24 08:25:30

我找到了一个解决问题的教程。这是它的链接

票数 0
EN

Stack Overflow用户

发布于 2014-10-20 09:55:57

例外是:

代码语言:javascript
复制
10-19 04:34:15.215: W/System.err(13788): org.json.JSONException: Expected ':' after n at character 4 of {n  "news":n    [n      {"id":"1","title":"Number one","description":"This is First Message","created_at":"2014-04-04"},n       {"id":"2","title":"Number two","description":"This is Second Message","created_at":"2014-04-04"},n      {"id":"3","title":"Number three","description":"This is Third Message","created_at":"2014-04-04"}n  ]n}nn

(请下次扫描LogCat中的相关部分。不是所有的事。再加上这个问题)

您的JSON看起来不错,但是您的错误显示有'n‘字符粉碎了JSON。你的网站正在返回这个不正确的信息。我猜这是“\n”吧?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26455896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档