0

I send my Data to my cloud server... which works fine. but i want to send all data which is present in SQlite db Table. i use Do while loop under Map method but it only send only one line. not whole.

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;
}

ERROR

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)

apply the Loop. But it Shows me some error...That I exceeded the limit.

one thing i have to clear thar On my web Server An Api take Variables not the array.. Now I thoink i clear my point?

Note: I am using volley lib to send data to server.

Thanks In advance. Really appreciate you help.

6
  • first prepare your whole local data map object and then you will call the volley request. Commented Feb 13, 2018 at 9:56
  • try to loop doInBackground Commented Feb 13, 2018 at 9:59
  • Request to server inside a loop is not a good idea. What happens if your Cursor have 1000 row or more? it will send request lot of request to server. Try with a single request and send all data in array or list. Commented Feb 13, 2018 at 10:17
  • @AbuYousuf how can i do this? Commented Feb 13, 2018 at 10:24
  • @AbuYousuf Bro plz take a look. my prob is i cannot send my data in Array. I have to send in Variable because of the receiving End. Commented Feb 14, 2018 at 13:10

3 Answers 3

0

Request to server inside a loop is not a good choice. Your loop can execute 1000 or more time. Try single request with array or list of post data.

Use JsonArrayRequest for your request.It accepts JSONArray as parameter. From Volley Source Code:

/**
 * 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 A {@link JSONArray} to post with the request. Null is allowed and

This constructor takes JSONArray which you can use to post your data. Make a JSONArray with your data and send request.

Edit:

Create your JSONArray like this:

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);

Send Request with

        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;
            }
        };

Also check this answer

Sign up to request clarification or add additional context in comments.

3 Comments

It gives me errors. and Seriously i didint get your answer . can you please tell me with respective code. ?
if you don't put your errors here how someone will help you what is the problem actually. Anyway i have updated my answer
I think i am getting your answer..But can you tell me where i write the code or make json array . i have to make the json from SQLITE Database.
0

Below Code is the reference for you to getData from Sqlite and call volley and hit API every time :

 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);

}

4 Comments

What i'm doing here is I'm getting Data from Sqlite DataBase At Same time i'm passing value as an argument bymethod and calling API , within 2-3 seconds it will update all data to server.
You are sending data by url. But I use variable on web server which receive data on them post by me from Android application.
You are sending data by url. But I use variable on web server which receive data on them post by me from Android application.
Are you using API , POST request ?@MuhammadZeeshan
0

I resolve my Problem. Thanks all Of you. I post my answer of my Above code. and it works fine.

    //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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.