与AsyncTask的和安卓的InputStream问题 [英] Android issues with ASyncTask and InputStream

查看:99
本文介绍了与AsyncTask的和安卓的InputStream问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找出这一点对我自己的相当长一段时间。通过试验/错误,以及研究,但我似乎无法得到它想通了。我是pretty的与异步和网络连接和stuch不好,所以它可能是一些简单的,我俯瞰。反正...我会贴一些相关的code的例子和说明。

I've been trying to figure this out on my own for quite a while.. by trial/error as well as research, but I just can't seem to get it figured out. I'm pretty bad with Async and network connections and stuch, so it might be something simple that I'm over looking. Anyway... I'll paste some relevant code samples and explanations.

我的问题的背景知识。我正在为我的应用程序中的烂番茄API,并且是用GSON其数据的解析。我最初的目标2.3,这工作得很好。然后,我决定对ICS的支持,当然还有跑进在UI线程上没有任何网络操作。 - 所以我开始钻研的AsyncTask

Quick background of my problem. I'm working with the Rotten Tomatoes API for my app, and am using GSON for the parsing of their data. I was initially targeting 2.3, and this worked fine. Then I decided to have support for ICS, and of course ran into the "no network operation on the UI thread" - so I started to delve into AsyncTask.

下面是我的InputStream方式:​​

Here is my InputStream method:

private InputStream retrieveStream(String url) {

    DefaultHttpClient client = new DefaultHttpClient();

    HttpGet getRequest = new HttpGet(url);

    try {

        HttpResponse getResponse = client.execute(getRequest);
        final int statusCode = getResponse.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            Log.w(getClass().getSimpleName(),
                    "Error " + statusCode + " for URL " + url);
            return null;
        }

        HttpEntity getResponseEntity = getResponse.getEntity();
        return getResponseEntity.getContent();
    }
    catch (IOException e) {
        getRequest.abort();
        Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }

    return null;
}

这是工作的罚款在我的主要活动,而现在正试图'转换'它时,到AsyncTask的是给我的问题。我一直在呼吁这样的:

Which was working fine in my main activity, and now is giving me issues when trying to 'convert' it into AsyncTask. I've been calling it like this:

InputStream source = retrieveStream( url parameter );

然后我试图移动的方法到我的AsyncTask类,并调用它是这样的:

Then I tried moving that method into my AsyncTask class, and calling it like this:

private PerformMovieSearch performSearch = new PerformMovieSearch(this);
InputStream source = performSearch.retrieveStream(movieQueryUrl);

但是,这并不削减它,仍然得到错误有关UI上进行网络操作。我需要搞清楚的是如何从AsyncTask的我想称之为'retrieveStream。目前,该类看起来是这样的:

But that doesn't cut it, still get the error about performing network actions on the UI. What I need to figure out is how to call 'retrieveStream' from the AsyncTask I guess. Currently that class looks like this:

package net.neonlotus.ucritic;

[imports]

public class PerformMovieSearch extends AsyncTask<String, Void, String> {

private final Context context;
private ProgressDialog progressDialog;


public PerformMovieSearch(Context context){
    this.context = context;
}


@Override
protected String doInBackground(String... urls) {
    retrieveStream(urls[0]);

    return null;

}

@Override
protected void onPreExecute() {
    progressDialog= ProgressDialog.show(context, "Please Wait","Searching movies", true);

}


@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    progressDialog.dismiss();

    MyActivity.mListAdapter.notifyDataSetChanged();
}

public InputStream retrieveStream(String url) {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse getResponse = client.execute(getRequest);
        final int statusCode = getResponse.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            Log.w(getClass().getSimpleName(),
                    "Error " + statusCode + " for URL " + url);
            return null;
        }

        HttpEntity getResponseEntity = getResponse.getEntity();
        return getResponseEntity.getContent();
    } catch (IOException e) {
        getRequest.abort();
        Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }

    return null;
}

}

在doinbackground是需要改变什么......但我似乎无法找到一个直接的方式来获取正常工作。我用的是执行

The "doinbackground" is what needs to be changed... but I can't seem to find a straight way to get that working properly. I was executing using

new PerformMovieSearch(this).execute(movieQueryUrl);

我知道这是一个很大的东西,可能会混乱......但如果​​有人知道如何从根本上做retrieveStream方法以异步方式,这将是巨大的。就像我说的,我已经尝试了很多事情,做过大量的研究,只是不能拿出任何有用。

I know that is a lot of stuff, potentially confusing... but if anybody knows how to essentially do the retrieveStream method asynchronously, that would be great. Like I said, Ive tried many things, did plenty of research, just could not come up with anything useful.

推荐答案

关键是,你不明白的AsyncTask是如何工作的!

the point is, you didn't understand how asynctask works!

您必须阅读的引导进程和线程:的http://开发商.android.com /引导/组件/过程和 - threads.html

You MUST read the guide Processes and Threads: http://developer.android.com/guide/components/processes-and-threads.html

不过没关系,让我来试试帮你。

But ok, let me try help you.

在doInBackground您正确调用方法retrieveStream,但你什么都不做与流。所以,你必须处理的数据流,然后返回。至于你说你期待的JSON,我假设你将获得一个字符串,所以你retrieveStream的code应该是这样的:

On doInBackground you are correctly calling the method retrieveStream, but you are doing nothing with the stream. So, you have to process the stream and then, return it. As you said you are expecting an JSON, I'm assuming you will receive a String, so the code of your retrieveStream should like this:

public String retrieveStream(String url) {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);

    try {
        HttpResponse getResponse = client.execute(getRequest);
        final int statusCode = getResponse.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            Log.w(getClass().getSimpleName(),
                    "Error " + statusCode + " for URL " + url);
            return null;
        }

        HttpEntity getResponseEntity = getResponse.getEntity();
        String jsonString = EntityUtils.toString(getResponseEntity);
        return jsonString;
    } catch (IOException e) {
        getRequest.abort();
        Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }

    return null;
}

你看,我改变返回类型为String。也许,你应该将名称更改为retrieveMoviesJSON或类似这样的东西。

Look that I changed the return type to String. And maybe, you should change the name to retrieveMoviesJSON or something like this.

和你需要改变你的AsyncTask的东西是这样的:

And you should change your AsyncTask to something like this:

class PerformMovieSearch AsyncTask<String, Void, ArrayList<Movie>>() {

            @Override
            protected void onPreExecute() {
                progressDialog= ProgressDialog.show(context, "Please Wait","Searching movies", true);
            }

            @Override
            protected ArrayList<Movie> doInBackground(String... params) {
                String moviesJson = retrieveStream[params[0]];
                JSONObject moviesJson = new JSONObject(moviesJson);
                ArrayList<Movie> movies = new ArrayList<Movie>();
                /*
                 * Do your code to process the JSON and create an ArrayList of films.
                 * It's just a suggestion how to store the data.
                 */
                return movies;
            }

            protected void onPostExecute(ArrayList<Movie> result) {
                progressDialog.dismiss();
                //create a method to set an ArrayList in your adapter and set it here.
                MyActivity.mListAdapter.setMovies(result);
                MyActivity.mListAdapter.notifyDataSetChanged();
            }
        }

你可以为你做同样的方式调用。

And you can call as the same way you were doing.

是不是清楚了吗?需要更多的解释?

Is it clear? Need more explanation?

[] S 内托

这篇关于与AsyncTask的和安卓的InputStream问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆