2014-10-19 62 views
0

我將從我的服務器上從json獲取新聞。來自AsyncTask和JSONParser的ListView

另外我有一個菜單按鈕,刷新我的列表視圖。

我不知道我在哪裏錯了!

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

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

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

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

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

任何建議,將不勝感激......

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:

看來,我的JSON是錯誤的。我已經編輯我的JSONParser類:

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

但錯誤已經發生呢!

有什麼建議?

+0

您收到的錯誤是什麼? – ucsunil 2014-10-19 22:10:04

+0

我重定向到日食... 在調試窗口: 線程[<11>的AsyncTask#1](暫停(例外的RuntimeException)) ThreadPoolExecutor.runWorker(ThreadPoolExecuter $工人)線:1098 ThreadPoolExecuter $ Worker.run()行: 573 主題。運行()行:856 – 2014-10-19 22:27:25

+1

你能否粘貼你收到的錯誤的完整堆棧跟蹤? – ucsunil 2014-10-20 00:35:26

回答

0

我找到了解決我的問題的教程。 以下是它的link

1

唯一的例外是:

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'?

+0

Tanks for your answer(並編輯我的問題)。如何掃描LogCat中的相關部分?我不知道哪一節顯示我的問題! – 2014-10-20 11:00:34

+0

另外,我該如何解決這個JSON錯誤?我必須編輯我的JSON文件或我的Java代碼? – 2014-10-20 11:03:47

+1

只要搜索「例外」一詞。你有一個PHP服務器返回JSON。這可能是罪魁禍首。我建議將此添加到您的問題。 – RvdK 2014-10-20 11:06:00