使用 AsyncTask 填充 ListView

发布于 2024-11-06 12:35:22 字数 4687 浏览 2 评论 0 原文

这可能不是很优雅,但我想做的是连接到 Web 服务,获取 JSON,解析它,从中创建一个对象,将该对象添加到 ArrayList,然后使用该 ArrayList 来填充我的列表视图。

我正在尝试使用 AsyncTask 来完成所有这一切。

摘要: doInBackgroud 接受一个 url 字符串,使用它连接到 Web 服务。我以字符串形式获取 JSON 数据,解析它,从数据中构造一个新对象,并将其添加到 ArrayList。然后在 onPostExecute 中,我尝试使用利用我的 ArrayList 的 ArrayAdapter 设置列表适配器。

这就是我所得到的:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

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

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class AllOffersListActivity extends ListActivity {

    private static final String CONSUMER_KEY = "bla";
    private static final String CONSUMER_SECRET = "bla";


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        new CreateArrayListTask().execute("http://example.com/sample.json");




    }

    private class CreateArrayListTask extends AsyncTask<String, Void, ArrayList<Offer>> {
        private final ProgressDialog dialog = new ProgressDialog(AllOffersListActivity.this);

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Fetching offers...");
            this.dialog.show();

        }
        @Override
        protected ArrayList<Offer> doInBackGround(String...urls) {
            ArrayList<Offer> offerList = new ArrayList<Offer>();

            for(String url: urls) {
                OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
                consumer.setTokenWithSecret("", "");

                try {

                    URL url1 = new URL(url);
                    HttpURLConnection request = (HttpURLConnection) url1.openConnection();

                    // sign the request
                    consumer.sign(request);

                    // send the request
                    request.connect();


                    String JSONString = convertStreamToString(request.getInputStream());

                    JSONObject jObject = new JSONObject(JSONString);

                    JSONObject offerObject = jObject.getJSONObject("offer");

                    String titleValue = offerObject.getString("title");
                    //System.out.println(titleValue);

                    String descriptionValue = offerObject.getString("description");
                    //System.out.println(attributeValue);
                    JSONObject businessObject = offerObject.getJSONObject("business");
                    String nameValue = businessObject.getString("name");

                    Offer myOffer = new Offer(titleValue, descriptionValue, nameValue);

                    offerList.add(myOffer);

                } catch (Exception e) {
                    e.printStackTrace();

                } 
            }
            return offerList; 

        }

        @Override
        protected void onPostExecute(ArrayList<Offer> offerList) {
            if(this.dialog.isShowing())
                this.dialog.dismiss();
            setListAdapter(new ArrayAdapter<Offer>(AllOffersListActivity.this, android.R.layout.simple_list_item_1, offerList));        
        }
    }

    private String convertStreamToString(InputStream inputStream) throws IOException {
        if(inputStream != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];

            try {

                Reader reader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8"));

                int n;
                while((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);

                }
            } finally {
                inputStream.close();
            }
            return writer.toString();
        } else {
            return "";
        }

    }

}

我看到两个错误。一个是在我的私有 Async 类上: “类型 AllOffersListActivity.CreateArrayListTask 必须实现继承的抽象方法 AsyncTask>.doInBackground(String...)”

其次,在我的 doInBackGround 覆盖上,我得到: The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask 必须重写或实现超类型方法

我在这里缺少什么?

This is probably not very elegant, but what I'm trying to do is connect to a web service, fetch the JSON, parse it, create an object out of it, add that object to an ArrayList and then use that ArrayList to populate my ListView.

I'm trying to do all of this with AsyncTask.

SUMMARY: doInBackgroud takes a String of a url, uses it to connect to a web service. I get the JSON data as a string, parse it, construct a new object out of the data, and add it to ArrayList. Then in onPostExecute I'm trying to set the listadapter using an ArrayAdapter that utilizes my ArrayList.

Here's what I have:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

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

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class AllOffersListActivity extends ListActivity {

    private static final String CONSUMER_KEY = "bla";
    private static final String CONSUMER_SECRET = "bla";


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        new CreateArrayListTask().execute("http://example.com/sample.json");




    }

    private class CreateArrayListTask extends AsyncTask<String, Void, ArrayList<Offer>> {
        private final ProgressDialog dialog = new ProgressDialog(AllOffersListActivity.this);

        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Fetching offers...");
            this.dialog.show();

        }
        @Override
        protected ArrayList<Offer> doInBackGround(String...urls) {
            ArrayList<Offer> offerList = new ArrayList<Offer>();

            for(String url: urls) {
                OAuthConsumer consumer = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
                consumer.setTokenWithSecret("", "");

                try {

                    URL url1 = new URL(url);
                    HttpURLConnection request = (HttpURLConnection) url1.openConnection();

                    // sign the request
                    consumer.sign(request);

                    // send the request
                    request.connect();


                    String JSONString = convertStreamToString(request.getInputStream());

                    JSONObject jObject = new JSONObject(JSONString);

                    JSONObject offerObject = jObject.getJSONObject("offer");

                    String titleValue = offerObject.getString("title");
                    //System.out.println(titleValue);

                    String descriptionValue = offerObject.getString("description");
                    //System.out.println(attributeValue);
                    JSONObject businessObject = offerObject.getJSONObject("business");
                    String nameValue = businessObject.getString("name");

                    Offer myOffer = new Offer(titleValue, descriptionValue, nameValue);

                    offerList.add(myOffer);

                } catch (Exception e) {
                    e.printStackTrace();

                } 
            }
            return offerList; 

        }

        @Override
        protected void onPostExecute(ArrayList<Offer> offerList) {
            if(this.dialog.isShowing())
                this.dialog.dismiss();
            setListAdapter(new ArrayAdapter<Offer>(AllOffersListActivity.this, android.R.layout.simple_list_item_1, offerList));        
        }
    }

    private String convertStreamToString(InputStream inputStream) throws IOException {
        if(inputStream != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];

            try {

                Reader reader = new BufferedReader( new InputStreamReader(inputStream, "UTF-8"));

                int n;
                while((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);

                }
            } finally {
                inputStream.close();
            }
            return writer.toString();
        } else {
            return "";
        }

    }

}

I'm seeing two errors. One is on my private Async class: "The type AllOffersListActivity.CreateArrayListTask must implement the inherited abstract method AsyncTask<String,Void,ArrayList<Offer>>.doInBackground(String...)"

Secondly, on my doInBackGround Override, I'm getting: The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask must override or implement a supertype method

What am I missing here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

国粹 2024-11-13 12:35:22

这只是一个小错字;应该是doInBackground而不是doInBackGround

It's just a small typo; should be doInBackground instead of doInBackGround.

亚希 2024-11-13 12:35:22

@LuxuryMode您在 doInBackGround 上犯了错误,

正确的拼写是 doInBackground

asynctask 必须实现 doInBackground 方法,因此它无法识别此方法,因为方法名称错误,因此会出现错误

 The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask must 
override or implement a supertype method

@LuxuryMode you have done mistake on doInBackGround

the correct spelling is doInBackground

asynctask must have to implement doInBackground method so it is not recognize this method because of wrong Name of method so it gives you error

 The method doInBackGround(String...) of type AllOffersListActivity.CreateArrayListTask must 
override or implement a supertype method
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文