将数据发送到服务器。 in循环(存在于Sqlite数据库中。)

时间:2018-02-13 09:51:04

标签: android sqlite android-asynctask

我将我的数据发送到我的云服务器......这很好用。但我想发送SQlite数据库表中存在的所有数据。我在Map方法下使用Do while循环,但它只发送一行。不完整。

String url = "http://blhc.com:1980/Mob/SendDoc.aspx";

SendDoctors(Context paramContext)
{
    this.cont = paramContext;
}
@Override
protected String doInBackground(Void... voids) {

    //region Sending
    try{
        ds = new DataSource(cont);
        ds.open();
        final Cursor cursor = ds.send();
        if(cursor.moveToFirst())
        do {
            //region Sending Data
            StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
                    new Response.Listener<String>(){
                        @Override
                        public void onResponse(String response) {
                            Toast.makeText(cont,"Uploaded.." ,Toast.LENGTH_SHORT).show();

                            Log.v("jarvis" ,"Resposce" + response);
                        }
                    }
                    , new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(cont,"Error.." ,Toast.LENGTH_SHORT).show();
                    error.printStackTrace();
                }
            }){

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {

                    Map<String, String> param = new HashMap<String, String>();
                    param.put("CELL_NO", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_PHONE_NUM)));
                    param.put("M_DATE", M_DATE);
                    param.put("M_TIME", M_TIME);
                    param.put("EMP_ID", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_EMP_ID)));
                    param.put("DOC_ID", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_DOC_ID)));
                    param.put("SA", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_SA)));
                    param.put("NOTE", "NOTE");
                    param.put("CO_ID", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_CO_ID)));
                    param.put("LAT", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_LOC_LAT)));
                    param.put("LNG", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_LOC_LON)));
                    param.put("USER_ID", String.valueOf(LoginActivity.ID));
                    return param;
                }
            };
            MySingleton.getmInstance(cont).addToRequestQue(stringRequest);
            //endregion
        }while (cursor.moveToNext());
    }catch(Exception e){}
    //endregion

    return null;
}

错误

E/Volley: [191] NetworkDispatcher.run: Unhandled exception android.database.CursorIndexOutOfBoundsException: Index 6 requested, with a size of 6
          android.database.CursorIndexOutOfBoundsException: Index 6 requested, with a size of 6
              at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
              at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
              at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
              at com.example.zed.androidapplication.SendDoctors$3.getParams(SendDoctors.java:84)
              at com.android.volley.Request.getBody(Request.java:468)
              at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:253)
              at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:227)
              at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
              at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97)
              at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
W/System.err: com.android.volley.VolleyError: android.database.CursorIndexOutOfBoundsException: Index 6 requested, with a size of 6
W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:143)
W/System.err: Caused by: android.database.CursorIndexOutOfBoundsException: Index 6 requested, with a size of 6
W/System.err:     at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
W/System.err:     at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
W/System.err:     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
W/System.err:     at com.example.zed.androidapplication.SendDoctors$3.getParams(SendDoctors.java:84)
W/System.err:     at com.android.volley.Request.getBody(Request.java:468)
W/System.err:     at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:253)
W/System.err:     at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:227)
W/System.err:     at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
W/System.err:     at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97)
W/System.err:     at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)

应用循环。但它显示了一些错误......我超出了限制。

有一件事我必须清除thar在我的网络服务器上Api采用变量而不是数组..现在我知道我清楚我的意思了吗?

注意:我正在使用volley lib将数据发送到服务器。

先谢谢。真的很感谢你的帮助。

3 个答案:

答案 0 :(得分:0)

以下代码是您从Sqlite获取getData并每次调用volley并命中API的参考:

 private void UploadSavedData() {

    String selectQuery = "SELECT  * FROM " + Constants.TABLE_NAME_COUNT;
    db = databaseHelper.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        Log.e("DATA_CHECK","DATA_CHECK");
        do {
            countEditQuantity(cursor.getString(2),cursor.getString(3)); //calling webservices here
            Log.e("DATASQLA",""+cursor.getString(1));



        } while (cursor.moveToNext());

    }else{

    }

}


 public void countEditQuantity(final String skuData, final String newQty) {
   String url = Constants.EDIT_TAKE_INVENTORY_URL"+dcId+"&sku="+""+skuData+"&new_qty="+""+newQt;
    Log.e("URL",""+url);

    StringRequest eventoReq = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.e("RESPONSE", response.toString());

                    if (progressCount <= 1) {
                        if(databaseHelper.deleteTableCount()){
                            mProgress.dismiss();
                            utils.showtoast("All Product Quantity Updated");
                            progressCount = 0;
                            getSyncTime();
                        }
                    } else {
                        progressCount--;
                    }
                    try {
                        JSONArray j = new JSONArray(response);

                        // Parse a json
                        for (int i = 0; i < j.length(); i++) {
                            try {
                                JSONObject obj = j.getJSONObject(0);
                                String code = String.valueOf(obj.get("code"));
                                Log.e("CODE", "" + code);

                                if(code.equals("1")){

                                }
                                if(code.equals("0")){

                                 utils.showtoast(""+obj.get("message"));

                                }
                                if(code.equals("-2")){
                                utils.showtoast(""+obj.get("message"));


                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Error: ", "" + error.getMessage());
            utils.showtoast("Please try again...");


        }
    });
    eventoReq.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    // Añade la peticion a la cola
    AppController.getInstance(this).addToRequestQueue(eventoReq);

}

答案 1 :(得分:0)

在循环内请求服务器不是一个好的选择。你的循环可以执行1000次或更多次。尝试使用数组或发布数据列表的单个请求。

使用JsonArrayRequest作为您的请求。我接受JSONArray作为参数。来自Volley源代码:

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONArray} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
                        Listener<JSONArray> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
            errorListener);
}
  

@param jsonRequest用{@link JSONArray}发布请求。允许空并且

此构造函数使用JSONArray可用于发布数据。使用您的数据制作JSONArray并发送请求。

修改

像这样创建JSONArray

JSONObject json1= new JSONObject();
json1.put("key1","value1");
json1.put("key2","value2");

JSONObject json2= new JSONObject();
json2.put("key1","value1");
json2.put("key2","value2");

JSONArray jsonArray = new JSONArray();
jsonArray.put(json1);
jsonArray.put(json2);

发送请求

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, url, jsonArray, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                return headers;
            }
        };

同时检查此answer

答案 2 :(得分:0)

我解决了我的问题。谢谢大家。 我发布了我的上述代码的答案。它工作正常。

    //region Sending
    try{
        ds = new DataSource(cont);
        ds.open();
        final Cursor cursor = ds.send();
        if(cursor.moveToFirst())
        do {

            //region Sending Variables
            final String CELL_NO = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_PHONE_NUM));
            final String M_DATE = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_DATE));
            final String M_TIME =cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_TIME));
            final String EMP_ID = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_EMP_ID));
            final String UserID = String.valueOf(LoginActivity.ID) ;
            final String DOC_ID = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_DOC_ID));
            final String SA= cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_SA));
            final String NOTE = " - ";
            final String CO_ID = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_CO_ID));
            final String LAT =cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_LOC_LAT));
            final String LNG=cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_LOC_LON));
            //endregion

            //region Sending Data
            Log.v("jarvis","Line = 1");
            StringRequest stringRequest = new StringRequest(Request.Method.POST,url,
                    new Response.Listener<String>(){
                        @Override
                        public void onResponse(String response) {
                            ds.updateStatus(DOC_ID,M_DATE,M_TIME,EMP_ID); //true
                            Toast.makeText(cont,"Uploaded And Saved.." ,Toast.LENGTH_SHORT).show();
                            Log.v("jarvis","Line = 2");
                        }
                    }
                    , new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v("jarvis","Line = 3");
                    ds.updateFalse(DOC_ID,M_DATE,M_TIME,EMP_ID); //true
                    Toast.makeText(cont,"Error.." ,Toast.LENGTH_SHORT).show();
                    error.printStackTrace();
                }
            }){

                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Log.v("jarvis","Line = 4");

                    Map<String, String> param = new HashMap<String, String>();
                    param.put("CELL_NO", CELL_NO);
                    param.put("M_DATE", M_DATE);
                    param.put("M_TIME", M_TIME);
                    param.put("EMP_ID", EMP_ID);
                    param.put("DOC_ID", DOC_ID);
                    param.put("SA", SA);
                    param.put("NOTE", NOTE);
                    param.put("CO_ID", CO_ID );
                    param.put("LAT", LAT);
                    param.put("LNG",LNG);
                    param.put("USER_ID",UserID);
                    return param;
                }
            };
            Log.v("jarvis","Line = 5");
            MySingleton.getmInstance(cont).addToRequestQue(stringRequest);
            //endregion
            Log.v("jarvis","Line = 6");

        }while (cursor.moveToNext());
    }catch(Exception e){}
    //endregion