简体   繁体   English

来自AsyncTask和JSONParser的ListView

[英]ListView from AsyncTask and JSONParser

I'm going to fetch news from json on my server. 我将从服务器上的json获取新闻。

Also I have a menu button that refresh my listview. 另外,我还有一个菜单按钮可以刷新我的列表视图。

I don't know where I'm wrong !!! 我不知道我在哪里错!

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

{
"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 JSONParser.java

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 RefreshNews.java

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 MainActivity.java

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 的Manifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Any suggestion would be appreciated ... 任何建议将不胜感激...

LogCat: logcat的:

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

UPDATE: 更新:

It seems that my JSON is wrong. 看来我的JSON错误。 I've edited my JSONParser class: 我已经编辑了JSONParser类:

sb.append(line + "n");   ---->    sb.append(line + "\n");

But error has been occurring yet! 但是错误已经发生了!

Is there any suggestion(s) ?! 有什么建议吗?

The exception is: 例外是:

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

(Please next time, scan for the relevant section in the LogCat. Not everything. And add that to the question) (请下次,扫描LogCat中的相关部分。不是所有内容。然后将其添加到问题中)

Your JSON looks OK, but you error shows there are ' n ' characters shattered troughout the JSON. 您的JSON看起来不错,但错误显示整个JSON中有' n '个字符破碎了。 Your website is returning this incorrecty. 您的网站返回了此错误消息。 I guess these are ' \\n '? 我猜这些是' \\n '?

I've found a tutorial that solved my problem. 我找到了可以解决我的问题的教程。 Here is its link 这是它的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM