0

我正在开发一个安卓应用程序。它必须从基于 json 的互联网上读取一些提要。好吧,我现在已经弄清楚了那部分。但是当我测试我的应用程序时,应用程序会卡在它正在下载提要的部分。UI 卡住了几秒钟。

我已经弄清楚我需要使用 android 中的 AsyncTask 类来在后台运行连接。我已经阅读了很多关于这个主题的文章,我几乎可以梦想这个理论。现在把它付诸实践,它给我带来了一点问题。

该应用程序现在有一堆类,但处理提要下载并将检索到的数据放入 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 中的位置的想法。 ..

感谢任何会帮助我的人!

4

1 回答 1

2

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

看到这个链接

  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");
        }
    }
于 2012-05-25T14:55:13.927 回答