简体   繁体   English

Android AsyncTask:如何处理返回类型

[英]Android AsyncTask: How to handle the return type

I am working on an Android application that executes an http POST request , and the tutorial I followed was resulting in an android.os.NetworkOnMainThreadException 我正在执行HTTP POST请求的Android应用程序上工作,而我遵循的教程导致android.os.NetworkOnMainThreadException

The original code was something like this. 原始代码是这样的。

public class JSONParser {

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

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        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();
        Log.e("JSON", json);
    } 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;

}
}

And this class was invoked with this line. 并在此行中调用了该类。

JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);

After changing this to an AsyncTask class, the code looks like this. 将其更改为AsyncTask类后,代码如下所示。

class JSONParser extends AsyncTask<String, Void, JSONObject>{

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

// variables passed in:
String url;
List<NameValuePair> params;

// constructor
public JSONParser(String url, List<NameValuePair> params) {
    this.url = url;
    this.params = params;
}

@Override
protected JSONObject doInBackground(String... args) {
    // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

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


        } catch (UnsupportedEncodingException 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();
            Log.e("JSON", json);
        } 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;
}

@Override
protected void onPostExecute(JSONObject jObj) {
    return;
}       
}

My question is, how do I return a JSONObject from this new AsyncTask class?I can see that jObj is being returned in doInBackground() , but I am not sure where it is being returned to. 我的问题是,我怎么返回JSONObject从这个新的AsyncTask类?我可以看到jObj在返回doInBackground()但我不知道在那里它被送回。

What do I need to modify or how do I need to call my new JSONParser class so that it is returning a JSONObject ? 我需要修改什么或如何调用新的JSONParser类,以便它返回JSONObject

Have a look at this code, it may give you an insight as to how to deal with the parsing of JSON objects. 看一下这段代码,它可能使您了解如何处理JSON对象的解析。 I am just posting the onPostExecute function for now because you seemed to have all the rest figured correctly. 我现在仅发布onPostExecute函数,因为您似乎已经正确地计算了所有其余部分。

As for your doubt as to where the data object from the doInBackground is returned, it is automatically sent to the onPostExecute where you can further on parse it. 关于您对从doInBackground返回的数据对象的疑问,它会自动发送到onPostExecute,您可以在其中进一步解析它。

            @Override
    protected void onPostExecute(JSONObject result)
    {
        try
        {   
            JSONObject data = result.getJSONObject("data");
                      // whatever your JSON tag may be, in this case its data.

            if (data.isNull("data"))
            {
                      // action to handle null JSON object.
            }               
            else
            {
                JSONArray jarray = data.getJSONArray("data");   
                int len=jarray.length();
                for (int i = 0; i < jarray.length(); i++)
                {
                JSONObject obj = (JSONObject) jarray.get(i);

             String instanceName = obj.getString("instanceName");   
                        //extract data by whatever tag names you require, in this case instanceName.    
           } 
         }
} 
        catch (JSONException je)
        {
            je.printStackTrace();
            Log.d(TAG, "Error: " + je.getMessage());
        }       
    }
}

I can see that jObj is being returned in doInBackground() but I am not sure where it is being returned to. 我可以看到在doInBackground()中返回了jObj,但不确定将其返回到何处。

The result of doinBackground() is received as a parameter in onPostExecute(). doinBackground()的结果在onPostExecute()中作为参数接收。 You are returning a json object in doinBackground() which is a parameter to onPostExecute(). 您正在doinBackground()中返回一个json对象,它是onPostExecute()的参数。

@Override
protected void onPostExecute(JSONObject jObj) {
return;
} 

Usage 用法

new JSONParser().execute("url);
class JSONParser extends AsyncTask<String, Void, JSONObject>{

   //string parameter to doInBackground()
   //JSONObject - result returned in doInBackground() received as a param in onPostExecute()
} 

You can also pass paramters to the constructor of your asynctask 您还可以将参数传递给asynctask的构造函数

 new JSONParser("url",params).execute(); 

In your asynctask; 在您的asynctask中;

String url;
List<NameValuePair> params;

// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}

from your doInBackground Method 从您的doInBackground方法

@Override
protected JSONObject doInBackground(String... args) {

 return jObj;

} }

your return your JsonObject to 您将您的JsonObject返回

@Override
protected void onPostExecute(JSONObject jObj) {

    // Here you get your return JsonObject
}  

An Async Task has 3 attribures 异步任务具有3个属性

Params, the type of the parameters sent to the task upon execution.

Progress, the type of the progress units published during the background computation.

Result, the type of the result of the background computation.

The point you need to understand is that you are creating a object of Async Task Class While calling new JSONParser(loginURL, params); 您需要了解的一点是,您正在调用new JSONParser(loginURL, params);创建异步任务类的对象new JSONParser(loginURL, params);

The solution is that create a public result variable in your Async class and the call execute() on the object of class and then access the public object from the object. 解决方案是在Async类中创建一个公共结果变量,并在该类的对象上调用execute() ,然后从该对象访问该公共对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM