0

我对异步任务有一些问题...

我使用 asynctask 将一些 URL(*.aspx 和参数)发送到我的服务器并插入一些数据。我的问题是如何确保数据成功插入服务器。然后,如果它可以插入到我的服务器上,我将在手机上更新我的数据库以确保数据发送成功

这是我的网址:

    vURL = Routines.URL_SEND_SJ +"?sjnumber=SJ-" + Routines.getSJNumber(vContext) +
                                 "&orgid=" + Routines.getOrgId(vContext) +
                                 "&deviceid="  + Routines.getImei(vContext) +
                                 "&savedate=" + vDate +
                                 "&savetime=" + vTime +
                                 "&status=" + vStatusSJNumber +
                                 "&latitude=" + vLatitude + 
                                 "&longitude=" + vLongitude +
                                 "&phonetype=" + vPhoneType +
                                 "&km=" + vKM;

AsyncTask 类通过 ASPX 类发送 URL

公共类 ASPX {

public static String submitASPXText(String vURL){       
    String vASPXText="";
    HttpClient vHttpClient = new DefaultHttpClient();

    HttpGet vHttpGet = new HttpGet(vURL);
    try{
        ResponseHandler<String> responseHandler=new BasicResponseHandler();
        vASPXText = vHttpClient.execute(vHttpGet, responseHandler);
        vASPXText = vASPXText.replace("<span id=\"Label1\">~", "");
        vASPXText = vASPXText.replace("`</span>", Routines.SEND); 
    }catch (Exception e){
        e.printStackTrace();
    }

    return vASPXText;
}



private class LocationAsyncTask extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... vURL) {
        String vASPXText = ASPX.submitASPXText(vURL[0]);
        return vASPXText;
    }

    @Override
    protected void onPostExecute(String vASPXResult) {
        super.onPostExecute(vASPXResult);
        Toast.makeText(getApplicationContext(), "insert sucess", Toast.LENGTH_SHORT).show();
    }
}
4

1 回答 1

0

为什么不让服务器返回一条 JSON 消息,然后让您的应用查看该消息以查看数据是否已保存。例如如果插入成功返回...

{
    "returnCode": 0,
    "returnMessage": "Data saved!"
}

如果有错误返回

{
    "returnCode": 1,
    "returnMessage": "Database Error! Data was not saved!"
}

在 Android 上,您可以使用内置的JSONObject来读取 JSON 消息。例如 ...

JSONObject object = JSONObject(json);
int returnCode = object.getInt("returnCode");
if (returnCode == 0){
    //Data was saved
} else {
    //Data was saved
}
于 2012-06-09T00:37:16.917 回答