簡體   English   中英

Android AsyncTask:如何處理返回類型

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

我正在執行HTTP POST請求的Android應用程序上工作,而我遵循的教程導致android.os.NetworkOnMainThreadException

原始代碼是這樣的。

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;

}
}

並在此行中調用了該類。

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

將其更改為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;
}       
}

我的問題是,我怎么返回JSONObject從這個新的AsyncTask類?我可以看到jObj在返回doInBackground()但我不知道在那里它被送回。

我需要修改什么或如何調用新的JSONParser類,以便它返回JSONObject

看一下這段代碼,它可能使您了解如何處理JSON對象的解析。 我現在僅發布onPostExecute函數,因為您似乎已經正確地計算了所有其余部分。

關於您對從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());
        }       
    }
}

我可以看到在doInBackground()中返回了jObj,但不確定將其返回到何處。

doinBackground()的結果在onPostExecute()中作為參數接收。 您正在doinBackground()中返回一個json對象,它是onPostExecute()的參數。

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

用法

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()
} 

您還可以將參數傳遞給asynctask的構造函數

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

在您的asynctask中;

String url;
List<NameValuePair> params;

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

從您的doInBackground方法

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

 return jObj;

}

您將您的JsonObject返回

@Override
protected void onPostExecute(JSONObject jObj) {

    // Here you get your return JsonObject
}  

異步任務具有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.

您需要了解的一點是,您正在調用new JSONParser(loginURL, params);創建異步任務類的對象new JSONParser(loginURL, params);

解決方案是在Async類中創建一個公共結果變量,並在該類的對象上調用execute() ,然后從該對象訪問該公共對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM