初学Android程序员的AsyncTask / Android Threading

时间:2012-05-25 14:52:36

标签: android multithreading json android-listview android-asynctask

我正在开发一个Android应用程序。它必须从基于json的互联网读取一些提要。好吧,我已经想到了这一部分。但是当我测试我的应用程序时,应用程序会卡在正在下载Feed的部分。 UI被卡住了几秒钟。

我已经发现我需要在android中使用AsyncTask类来在后台运行连接。我在这个主题上读了这么多,我几乎可以梦想这个理论。现在把它付诸实践,它给了我一些问题。

该应用程序现在有一堆类,但是处理下载feed并将已检索数据放入listView的类(活动)。该课程名为KVONieuws(荷兰语为KVO - NEWS),来源:

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

感谢任何能帮助我的人!

1 个答案:

答案 0 :(得分:2)

在onCreate方法中调用new MyRssReadTask().execute(); ...

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");
        }
    }