0

の形式でサーバーにデータを送信したいJSON。まず、うまく機能しましたが、問題にAsyncTask直面したため、いくつかのネットワーク操作を行うために使用するクラスを変更する必要がありました。解決策は を使用することです。しかし、コンストラクタが未定義であるという問題が発生しました。では、このクラスで何を変更すればよいでしょうか。android.os.NetworkOnMainThreadExceptionAsyncTaskUrlEncodedFormEntity(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;
}

}

4

3 に答える 3

0

いつでも ArrayList をパラメーターとしてコンストラクターに渡し、それを JSONParser 内のフィールドとして格納できます。

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

また、プライベート フィールドを追加します。

private ArrayList <NameValuePair> list = null;

これで、AsyncTask で好きなようにリストを操作できます。

于 2013-08-17T20:43:05.420 に答える
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」配列の最初の項目を取得します。

于 2013-08-17T19:19:25.683 に答える