让AsyncTask将List <namevaluepair>作为参数</namevaluepair>

时间:2013-08-17 19:11:03

标签: android parameters arraylist android-asynctask

我想以JSON的形式将数据发送到我的服务器。首先,它工作得很好,但现在我必须更改类以使用AsyncTask进行一些网络操作,因为我遇到了android.os.NetworkOnMainThreadException问题,解决方案是使用AsyncTask。但是,我遇到了一个问题,即构造函数UrlEncodedFormEntity(List<NameValuePair>[])未定义。那么,我应该在这堂课中改变什么?

我的代码:

public class JSONParser extends AsyncTask<List<NameValuePair>, Void, String> {
private static String registerURL = "http://sit-edu4.sit.kmutt.ac.th/csc498/53270327/Boss/sftrip/index.php/register";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

protected String doInBackground(List<NameValuePair>... params) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(registerURL);
    // Making HTTP request
    try {
        // defaultHttpClient

        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } else {
            Log.e("Log", "Failed to download result..");
        }

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

    try {
        if (is != null) {
        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);
        } else {
            Log.e("Log", "Something wrong with IS");
        }
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    return json;
}

}

3 个答案:

答案 0 :(得分:0)

这样做:

public class JSONParser extends AsyncTask<NameValuePair, Void, String> {

     protected String doInBackground(NameValuePair... params) {

     }
}

(NameValuePair ... params)实际上意味着方法doInBackground可以有一个未指定数量的参数,因此您可以将一个数组传递给它。

new JSONParser().execute(new NameValuePair[] { .... your namevaluepairs ... });

此外,您可以考虑更改此行:

httpPost.setEntity(new UrlEncodedFormEntity(params));

到此:

httpPost.setEntity(new UrlEncodedFormEntity(params[0]));

这将获得NameValuePair ArrayLists的“params”数组的第一项。

答案 1 :(得分:0)

您始终可以将ArrayList作为参数传递给构造函数,并将其存储为JSONParser中的字段:

public JSONParser(List <NameValuePair> list) { this.list = list; }

还要添加私有字段:

private ArrayList <NameValuePair> list = null;

现在,您可以在AsyncTask中随意操作列表。

答案 2 :(得分:0)

public static String getHttpResponse(String url, List<NameValuePair> nameValuePairs) {

        HttpClient httpClient = new DefaultHttpClient();
        HttpProtocolParams.setUseExpectContinue(httpClient.getParams(),true);

        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity entity;
        try {
            entity = new UrlEncodedFormEntity(nameValuePairs);
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);

            HttpEntity resEntity = response.getEntity();
            String res =  EntityUtils.toString(resEntity);
            return res;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }