【问题标题】:Looping upload only uploads the first item循环上传仅上传第一项
【发布时间】:2014-02-22 03:52:51
【问题描述】:

我在后台运行了一个 for 循环,它正在将一个数组在线上传到我的数据库。但是,它只在第一次通过时上传,我不知道为什么。

我可以按照代码循环遍历 params.add 和上传,但是当我查看我的数据库时,每次只添加一个额外的项目。我的成功 int 也每次都设置为 0,但第一个。

我查看了类似的问题,并尝试解决此问题,但我找不到任何东西。对此我将不胜感激。

这是相关代码(我称之为“new SavePotholeDetails().execute();”):

protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(SensorActivity.this);
        pDialog.setMessage("Loading pothole details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Saving product
     * */
    protected String doInBackground(String... args) {
        // TODO: Get data from sensorData
        for (int i = 0; i < sensorData.size(); i++) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair(TAG_TIME, Long.toString(sensorData.get(i).getTimestamp())));
            params.add(new BasicNameValuePair(TAG_ACCEL_X, Double.toString(sensorData.get(i).getX())));
            params.add(new BasicNameValuePair(TAG_ACCEL_Y, Double.toString(sensorData.get(i).getY())));
            params.add(new BasicNameValuePair(TAG_ACCEL_Z, Double.toString(sensorData.get(i).getZ())));
            params.add(new BasicNameValuePair(TAG_CLIENT_ID, "Epidilius")); //TODO: Make a client ID variable
            params.add(new BasicNameValuePair(TAG_GPS_X, Double.toString(sensorData.get(i).getLat())));
            params.add(new BasicNameValuePair(TAG_GPS_Y, Double.toString(sensorData.get(i).getLng())));

            // sending modified data through http request
            // Notice that update product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(
                    url_update_pothole, "POST", params);

            // check json success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully updated
                    Intent intent = getIntent();
                    // send result code 100 to notify about product update
                    setResult(100, intent);
                    finish();
                } else {
                    // failed to update product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product updated
        pDialog.dismiss();
    }

编辑:

这是 JSONParser 类:

public class JSONParser {

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

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // 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();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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, "UTF-8"), 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;

}
}

【问题讨论】:

  • 我的猜测:sensorData.size()==1
  • 专业提示:使用 foreach 而不是 for。它应该更快。

标签: java android upload


【解决方案1】:

如果您只是在运行一个简单的循环并且在执行 AsyncTask 时没有阻塞循环,那么它们只是被一次全部触发。我还看到您正在通过 jsonParser 对象发送 Web 请求,但我不知道那是什么。如果此对象在 AsyncRequest 实例之间共享(例如,如果所有这些内容都在单个 Activity 范围内)或者如果实现阻塞以便一次只能发出一个请求,那么在循环的第一次迭代之后的所有内容将会失败,因为您的 HTTP 客户端正忙。

如果不发布您的 AsyncTask 代码,我将无能为力。您可能想更多地考虑如何执行循环。您可以做一些事情,循环等待每个 AsyncTask 实例回调(从 onPostExecute 方法)以表明它已完成。或者,您可以在单个 AsyncTask 实例中执行循环(可能是更轻量级的解决方案,因为只创建了一个线程)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多