从For循环调用异步Web服务

时间:2018-10-11 11:44:30

标签: android

当我从for循环调用Web服务以使用PHP将数据插入/更新到MySQL中时,只有最后一项才被插入/更新,因为(我认为)for循环比Web Service快完成,我如何延迟我的for循环或针对for循环中传回的每一项返回一个Web服务调用。

对于循环代码:

        for (int i = 0; i < lv.getCount(); i++) {

                view = lv.getAdapter().getView(i, lv.getChildAt(i), lv);

                if (view != null) {

        // Getting my views
            tvItem = (TextView) view.findViewById(R.id.tvItem);
            strItem = tvItem.getText().toString();

        //Call AsyncTask
                    accessWebService();

                }
            }

Web服务:

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

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0]);
        try {
            HttpResponse response = httpclient.execute(httppost);
            jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try {
            while ((rLine = rd.readLine()) != null) {
                answer.append(rLine);
            }
        }

        catch (IOException e) {

        }
        return answer;
    }

    @Override
    protected void onPostExecute(String result) {

        try{
            ld();
        }catch (Exception e){

        }
    }
}// end async task

public void accessWebService() {

    Webservice task = new Webservice();

    //Update MySQL Using PHP

}

1 个答案:

答案 0 :(得分:0)

当您要插入/更新for循环中的所有数据时,必须使用类似回调的接口。一旦实现此功能,它将等待完成该过程。一旦完成,它将调用成功或错误方法。基于此,您将插入/更新另一条记录。

interface DataCallback {

    fun onSuccess(result: Any)

    fun onError(error: Any)
}

public void getCountries(new DataCallback(){

    @Override
    public void onSuccess(Object result){
        // insert/update next record
    }

    @Override
    public void onError(Object error){
        // show error message
    }

});

这只是示例。您应该根据需要进行转换。谢谢。