从AsyncTask的JSON并网运行? [英] JSON and network operation from an Asynctask?

查看:89
本文介绍了从AsyncTask的JSON并网运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到一个很好的JSON解析器,我想用它在我的项目。将会有很多的JSON请求,所以我希望能够重用code。这里的JSON解析器:

I found an excellent JSON parser online, and I want to use it in my project. There will be lots of JSON requests, so I'd like to be able to reuse code. Here's the JSON parser:

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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 JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) { 
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

在我的主要活动,我需要一种方法来检索的JSONObject解析器的回报。然而,它需要在后台线程中进行。

In my main activity, I need a way to retrieve the JSONObject that the parser returns. However, it needs to be done in a background thread.

我无法弄清楚如何从AsyncTask的返回一个对象。我在想,也许包裹分析器类中的AsyncTask,并有它的时候,它的完成返回,但给出了同样的难题。

I can't figure out how to return an object from an Asynctask. I was thinking about maybe wrapping the parser class in an Asynctask, and having it return when it's finished, but that gives the same conundrum.

有人能帮忙吗?

推荐答案

可以使您已写入到的AsyncTask 其中 doInBackground()方法返回一个的JSONObject 。在的AsyncTask 的土地,从 doInBackground()(被称为在后台线程的方式)传递给<返回的值code> onPostExecute()这就是所谓的主线程上。您可以使用 onPostExecute()来通知你的活动的操作完成,并直接通过自定义传递对象回调接口定义,或只具有活动呼叫 AsyncTask.get()当操作完成后获得支持你解析后的JSON。因此,例如,我们可以用下面的扩展类:

You can make the class you've already written into an AsyncTask where the doInBackground() method returns a JSONObject. In AsyncTask land, the value returned from doInBackground() (the method called on a background thread) is passed to onPostExecute() which is called on the main thread. You can use onPostExecute() to notify your Activity that the operation is finished and either pass the object directly through a custom callback interface you define, or by just having the Activity call AsyncTask.get() when the operation is complete to get back your parsed JSON. So, for example we can extend your class with the following:

public class JSONParser extends AsyncTask<String, Void, JSONObject> {
    public interface MyCallbackInterface {
        public void onRequestCompleted(JSONObject result);
    }

    private MyCallbackInterface mCallback;

    public JSONParser(MyCallbackInterface callback) {
        mCallback = callback;
    }

    public JSONObject getJSONFromUrl(String url) { /* Existing Method */ }

    @Override
    protected JSONObject doInBackground(String... params) {
        String url = params[0];            
        return getJSONFromUrl(url);
    }

    @Override
    protected onPostExecute(JSONObject result) {
        //In here, call back to Activity or other listener that things are done
        mCallback.onRequestCompleted(result);
    }
}

和使用从活动中,像这样:

And use this from an Activity like so:

public class MyActivity extends Activity implements MyCallbackInterface {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...existing code...

        JSONParser parser = new JSONParser(this);
        parser.execute("http://my.remote.url");
    }

    @Override
    public void onRequestComplete(JSONObject result) {
        //Hooray, here's my JSONObject for the Activity to use!
    }
}

此外,作为一个侧面说明,您可以替换以下所有code。在您的分析方法:

Also, as a side note, you can replace all the following code in your parsing method:

is = httpEntity.getContent();           

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();
    json = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

通过这样的:

json = EntityUtils.toString(httpEntity);

希望帮助!

这篇关于从AsyncTask的JSON并网运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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