0

我正在開發一個android應用程序。它必須從基於json的互聯網上閱讀一些內容。那麼我現在已經明白了這一點。但是,當我測試我的應用程序時,該應用程序卡在下載Feed的部分。用戶界面卡住了幾秒鐘。AsyncTask/Android線程開始android程序員

我已經搞清楚了,我需要使用Android中的AsyncTask類來在後臺運行連接。我在這個主題上閱讀了很多,我幾乎可以夢想這個理論。現在把它付諸實踐,它給了我一點問題。

該應用程序現在有一大堆類,但處理下載Feed的類(活動)並將retreived數據放入listView中。該類稱爲KVONieuws(荷蘭的志願 - 新聞)這裏的源:

package com.appsoweb.kvodeventer; 

import java.util.ArrayList; 
import java.util.HashMap; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import com.appsoweb.kvodeventer.JSONfunctions; 
import com.appsoweb.kvodeventer.KVONieuws; 
import com.appsoweb.kvodeventer.R; 

import android.app.ListActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.Toast; 
import android.widget.AdapterView.OnItemClickListener; 

public class KVONieuws extends ListActivity { 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.listplaceholder); 

     ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); 

     JSONObject json = JSONfunctions.getJSONfromURL("http://crossalertdeventer.nl/api/news.json"); 

     try{ 

      JSONArray earthquakes = json.getJSONArray("items"); 

      for(int i=0;i<earthquakes.length();i++){       
       HashMap<String, String> map = new HashMap<String, String>();  
       JSONObject e = earthquakes.getJSONObject(i); 

       map.put("id", String.valueOf(i)); 
       map.put("name", "Titel:" + e.getString("title")); 
       map.put("image", "Image: " + e.getString("image")); 
       mylist.add(map);    
      }  
     }catch(JSONException e)  { 
      Log.e("log_tag", "Parsing error "+e.toString()); 
     } 


     ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.singlelistitem, 
         new String[] { "name", "image" }, 
         new int[] { R.id.item_title, R.id.item_subtitle }); 

     setListAdapter(adapter); 

     final ListView lv = getListView(); 
     lv.setTextFilterEnabled(true); 
     lv.setOnItemClickListener(new OnItemClickListener() { 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {    
       @SuppressWarnings("unchecked") 
       HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);     
       Toast.makeText(KVONieuws.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

      } 
     }); 
    } 
} 

現在我已經創建了一個名爲JSONfunctions.java這裏另一個類來處理故事的JSON部分:

package com.appsoweb.kvodeventer; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

public class JSONfunctions { 

    public static JSONObject getJSONfromURL(String url){ 
     InputStream is = null; 
     String result = ""; 
     JSONObject jArray = null; 

     //http post 
     try{ 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost(url); 
       httppost.setHeader("User-Agent", "9fb01091b51527555d1d3fc87709918f"); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       is = entity.getContent(); 

     }catch(Exception e){ 
       Log.e("log_tag", "Error in http connection "+e.toString()); 
     } 

     //convert response to string 
     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(); 
       result=sb.toString(); 
     }catch(Exception e){ 
       Log.e("log_tag", "Error converting result "+e.toString()); 
     } 

     try{ 

      jArray = new JSONObject(result);    
     }catch(JSONException e){ 
       Log.e("log_tag", "Error parsing data "+e.toString()); 
     } 

     return jArray; 
    } 
} 

現在我已經嘗試了很多這樣的代碼來使(重部分)作爲背景中的線程運行,並且我理解它的理論,但我無法完成它的工作。我不知道爲什麼....

有沒有人可以簡單地調整我的代碼或指示實現內部類的地方也許擴展AsyncTask類,並給出一個想法在哪裏放置什麼代碼在後臺運行的方法和onpostexecute ...

感謝任何人會幫助我!

回答

2

呼叫new MyRssReadTask().execute();在onCreate方法...

See this Link

class MyRssReadTask extends AsyncTask<Void, Void, JSONObject> { 
     ProgressDialog waitingDialog; 
     @Override 
     protected void onPreExecute() { 
      waitingDialog = new ProgressDialog(KVONieuws.this); 
      waitingDialog.setMessage("Loading..."); 
      waitingDialog.show(); 
      super.onPreExecute(); 
     } 

     @Override 
     protected Void doInBackground(Void... unused) { 

      JSONObject json = JSONfunctions.getJSONfromURL("http://crossalertdeventer.nl/api/news.json"); 

      return json; 
     } 

     @Override 
     protected void onPostExecute(JSONObject objJson) { 
      super.onPostExecute(result); 
      if(waitingDialog.isshowing()){ 
      waitingDialog.dismiss();} 

      //do stuff here 
      JSONArray earthquakes = objJson.getJSONArray("items"); 
     } 
    } 
+0

非常感謝!我現在都在工作! –