How to make progress bar running on for loop - android

I have this method to get data from server using volley and store it into sqlite database using ormlite. I'm doing this on splash screen. so now I want to show some progressbar when this process happen, the progress bar already appear and now I want to set the progress of progress bar inside the for loop. But I dont know why my progress bar keep on 0% until the process finish. when I look at the log the progress keep update but maybe because it inside a loop the progress not appear. How can I make the progress appear in my progressdialog?? below is my code
private void fetchMOffice() {
mOfficeAdapter = new TableMOfficeAdapter(this);
List<TableMOffice> listOffice = mOfficeAdapter.getAllDatabyLup();
progressBar = new ProgressDialog(SplashScreenActivity.this);
progressBar.setCancelable(true);
progressBar.setMessage("Downloading File...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
showDialog();
for (int i=0; i<listOffice.size(); i++) {
TableMOffice item = listOffice.get(i);
lupMOffice = item.getLup();
// locationIdArray.add(item.getKode_office());
break;
}
Log.e(TAG, "lup fetchMOffice: " +lupMOffice );
StringRequest strReq = new StringRequest(Request.Method.POST,
ConnectionManager.MASTER_M_OFFICE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
dbAdapter = new TableMOfficeAdapter(SplashScreenActivity.this);
// dbAdapter.deleteAll();
// SQLiteStatement insert = mDb.compileStatement(sql);
// check for error flag
if (obj.getBoolean("error") == false) {
jsonArray = obj.getJSONArray("m_office");
for ( i = 0; i < jsonArray.length(); i++) {
JSONObject versionObj = null;
versionObj = (JSONObject) jsonArray.get(i);
int id = versionObj.getInt("id");
String office = versionObj.getString("office");
String kode_office = versionObj.getString("kode_office");
String channel = versionObj.getString("channel");
String jenis = versionObj.getString("jenis");
String alamat = versionObj.getString("alamat");
String kota = versionObj.getString("kota");
String propinsi = versionObj.getString("propinsi");
String pic = versionObj.getString("pic");
String pic_phone = versionObj.getString("pic_phone");
String map_lat = versionObj.getString("map_lat");
String map_lng = versionObj.getString("map_lng");
String upd = versionObj.getString("upd");
String lup = versionObj.getString("lup");
String ket = versionObj.getString("ket");
String region = versionObj.getString("region");
String rek = versionObj.getString("rek");
String bank = versionObj.getString("bank");
String rental = versionObj.getString("rental");
Log.e("isitabeloffice", Integer.toString(id));
ctx = getApplicationContext();
dbAdapter.delete(SplashScreenActivity.this,id);
//dbAdapter.delete(ctx,id);
dbAdapter.insertData(new TableMOffice(), id, office, kode_office, channel,
jenis, alamat, kota, propinsi, pic, pic_phone, map_lat, map_lng,
upd, lup, ket, region, rek, bank, rental);
progress = (i+1)*100/jsonArray.length();
progressBar.setProgress(progress);
}
} else {
}
} catch (Exception e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
//Toast.makeText(SplashScreenActivity.this, "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
hideDialog();
//Toast.makeText(SplashScreenActivity.this, "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
Log.e(TAG, "params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}

Related

Does not display incoming data with response

I am writing an application for android and using the volley library. I need to write the received data into TextResult. How to do it?
private void jsonParse() {
String url = "https://api.apixu.com/v1/current.json?key=...&q=Paris";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject location = jsonArray.getJSONObject(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
Json response example
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Use this piece of code.
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response.getJSONObject("location");
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray location = jsonObject.getJSONArray(i);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
{"location":{"name":"Paris","region":"Ile-de-France","country":"France"}}
Its not a JSONArray its a JSONObject.
First get the location from JSONObject.
String location_value=response.get("location");
JSONObject location=new JSONObject(location_value);
String name = location.getString("name");
String region = location.getString("region");
String country = location.getString("country");
TextResult.append(name + ", " + region + ", " + country + "\n\n");

Handle response of multiple request from Volley Library

I am sending multiple request through for loop.
On response I get success or failure message, and I need to show this message in a AlertDialog.
My Problem is: when I am sending 10 request then I am getting 10 response hence 10 times dialogue is showing with response.
I want to show only one dialogue when all response will have come,and that dialogue should contain response according to their each and every request.
How can I do it.
code which I tried:
if (globalInstance.isNetworkAvailable(AddBookingList.this)) {
int si = checkedItems.size();
if (checkedItems.size() > 0) {
for (int i = 0; i < si; i++) {
int appid = checkedItems.get(i).getAppid();
int bookingId = checkedItems.get(i).getBookingid();
List<Contacts> con = db.getadvertisment(bookingId);
List<AddImages> img = db.getImagesbybookingId(bookingId);
String postXml = createxmlForPost(con, img);
sendDataToServer(postXml,appid, bookingId, si);
}
}
}
private void sendDataToServer(final String postXml, final int appid, final int bookingId, final int si) {
final ProgressDialog progressDialog = new ProgressDialog(this, R.style.AppCompatAlertDialogStyle);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
try {
final RequestQueue queue = Volley.newRequestQueue(this);
JSONObject obj = new JSONObject();
obj.put("xmlData", postXml);
int socketTimeout = 30000;//30 seconds
final StringRequest postRequest = new StringRequest(Request.Method.POST, Constants.Rootpath + "PostBooking",
new Response.Listener<String>() {
#Override
public void onResponse(String st) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
JSONArray response = new JSONArray(st);
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
int status = jsonObject.getInt("Status");
String msg = jsonObject.getString("Msg");
String serverbooking_id = jsonObject.getString("BookingId");
if (status == 1) {
checkedItems.clear();
if (response.length() > 1) {
String newserverbooking_id = response.getJSONObject(0).getString("BookingId") + "\n" + response.getJSONObject(1).getString("BookingId");
db.updateBookingDetailsbyAppId(newserverbooking_id, appid, status);
} else {
db.updateBookingDetailsbyAppId(serverbooking_id, appid, status);
}
showDatainList();
globalInstance.showSuceessMessage(true, "Success!!! Your BookingID is: " + serverbooking_id, AddBookingList.this);
try {
List<Contacts> contacts = db.getAllBookingDetails();
for (int h = 0; h < contacts.size(); h++) {
locallySaveImagesinPhone(bookingId, contacts.get(h).get_serverbookingId());
}
} catch (IOException e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
globalInstance.showFailureMessage(false, "Booking Failed." + msg, AddBookingList.this);
checkedItems.clear();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
String msg = error.getMessage();
globalInstance.showFailureMessage(false, "Booking Failed.Please Try Again!!!", AddBookingList.this);
}
}
) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>();
params.put("xmldata", postXml);
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
queue.add(postRequest);
} catch (JSONException e1) {
e1.printStackTrace();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
As i understand your problem is calling globalInstance.showSuceessMessage() or globalInstance.showFailureMessage every time you get the response.
what i think might work is:
Instead of these two methods, define an Arraylist<String> and based on the
success or failure of the response add messages to it like "Success!!! Your BookingID is: " + serverbooking_id and "Booking Failed." + msg.
Define a method like showMessages() which has a dialogue containing the messages u added to arraylist before. then call it after where you called thesendDataToServer method which is in the if (checkedItems.size() > 0) block.

What prevent me from get this json data

I'm trying to get this array of images in this json bellow and display it in GridView but i don't know why i can't reach that >>>
{
id: 241,
title: "title",
image: "1469370455.jpg",
description: " descriotion ",
images: [
"1469370455.jpg",
"1469370458.jpg",
"1469370481.jpg",
"1469370484.jpg"
]}
and this is my full AyncTask.
private class AysncImages extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
// pDialog = new ProgressDialog(getActivity());
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
// pDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
Log.i(TAG, "array: "+ jsonObj);
GridItem item = new GridItem();
for (int i = 0; i < arrayObj.length(); i++) {
String images = arrayObj.getString(i);
Log.i(TAG, "parseResult: " + jsonObj);
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
// Getting JSON Array node
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// if (result == 1) {
mGridAdapter.setGridData(mGridData);
//} else {
// Toast.makeText(getActivity(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
// }
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
In my log i can't reach jsonObj or arrayObj I just can reach jsonStr what I'm missing ?
My Log for jsonStr
the json string you get is [{id:abc,...}]
but a JsonObject should start with {id:abc,...}
maybe you try to remove the '[' and ']' at the end of string in order to get the object
as start with '[' should be an array

I need to send Data from Sqlite Database to Server

Below is the Code that I have tried,
What I have done,
First of all I am getting the count of pending data then I have made a for loop till the data count and in for Loop I am getting the data from SQlite and Making it's JSON and then making a webservice call everything goes well but the loop is not executed in correct manner, It is not executing the web service call every time!
Hence only the last data only gets uploaded
Now I want one by one every pending data get uploaded
private int checkForSendingDeviation() {
RDB = new SohamRadarDatabase(this);
CountDevPenTable = (int) RDB.getDeviatePendingCount();
return CountDevPenTable;
}
checkForSendingDeviation()
for (int mainloop = 0; mainloop < CountDevPenTable; mainloop++) {
checkIncrement = checkIncrement + 1;
DoGetAndUploadData();
}
private void DoGetAndUploadData() throws JSONException, UnsupportedEncodingException {
RDB.getWritableDatabase();
String table = TABLE_DEVIATION_DEATIALS;
String[] columns = {DEVIAT_ID, DEVIAT_H_ID, DEVIAT_L_ID, DEVIAT_REASON, DEVIAT_TPDATE, DEVIATION_MKTID, DEVIATION_ISUPLOADED};
String selection = DEVIATION_DATETIME + " = ?";
String[] selectionArgs = {""};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = "1";
Cursor c = RDB.query(table, columns, selection, selectionArgs, null, null, null, limit);
while (c.moveToNext()) {
JDEVIATE_ID = c.getInt(c.getColumnIndex(DEVIAT_ID));
JDEVIATE_H_ID = c.getInt(c.getColumnIndex(DEVIAT_H_ID));
JDEVIATE_L_ID = c.getInt(c.getColumnIndex(DEVIAT_L_ID));
JDEVIAT_REASON = c.getString(c.getColumnIndex(DEVIAT_REASON));
JDEVIATE_MKT_ID = c.getInt(c.getColumnIndex(DEVIATION_MKTID));
JDEVIAT_DATE = c.getString(c.getColumnIndex(DEVIAT_TPDATE));
}
rootObjecteviation = new JSONObject();
JSONObject jsonParams = new JSONObject();
jsonParams.put(DEVIAT_ID, JDEVIATE_ID);
jsonParams.put(DEVIAT_H_ID, JDEVIATE_H_ID);
jsonParams.put(DEVIAT_L_ID, JDEVIATE_L_ID);
jsonParams.put(DEVIAT_TPDATE, "/Date(1483295400000+0530)/");
jsonParams.put(DEVIATION_MKTID, JDEVIATE_MKT_ID);
jsonParams.put(DEVIAT_REASON, JDEVIAT_REASON);
rootObjecteviation.put("Deviation", jsonParams);
entity = new StringEntity(rootObjecteviation.toString());
HttpEntity params = entity;
client.post(this, URLDeviation.trim(), params, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String resonseStr = new String(responseBody);
Log.d("Inside Success", String.valueOf(statusCode));
gson = new Gson();
response = gson.fromJson(resonseStr, Response.class);
Log.d("response", response.toString());
String Message = response.getFillDeviationResult().get(0).getMessage();
int DevId = response.getFillDeviationResult().get(0).getDeviationID();
Log.d("Submitted DevId", String.valueOf(DevId));
Log.d("Chech Loop", String.valueOf(checkIncrement));
if (Message.equals("Success")) {
updateRowDeviation(DevId);
updateCountI = updateCountI + 1;
tvDeviationPendingCount.setText("Deviation Count is " + updateCountI + "/" + CountDevPenTable);
} else if (Message.equals("All Ready Submited Deviation")) {
updateRowDeviation(DevId);
updateCountI = updateCountI + 1;
tvDeviationPendingCount.setText("Deviation Count is " + updateCountI + "/" + CountDevPenTable);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// Hide Progress Dialog
progressDialog.dismiss();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}
update your code like below you are adding only last bunch of data to JsonObject .
rootObjecteviation = new JSONObject();
while (c.moveToNext()) {
JDEVIATE_ID = c.getInt(c.getColumnIndex(DEVIAT_ID));
JDEVIATE_H_ID = c.getInt(c.getColumnIndex(DEVIAT_H_ID));
JDEVIATE_L_ID = c.getInt(c.getColumnIndex(DEVIAT_L_ID));
JDEVIAT_REASON = c.getString(c.getColumnIndex(DEVIAT_REASON));
JDEVIATE_MKT_ID = c.getInt(c.getColumnIndex(DEVIATION_MKTID));
JDEVIAT_DATE = c.getString(c.getColumnIndex(DEVIAT_TPDATE));
JSONObject jsonParams = new JSONObject();
jsonParams.put(DEVIAT_ID, JDEVIATE_ID);
jsonParams.put(DEVIAT_H_ID, JDEVIATE_H_ID);
jsonParams.put(DEVIAT_L_ID, JDEVIATE_L_ID);
jsonParams.put(DEVIAT_TPDATE, "/Date(1483295400000+0530)/");
jsonParams.put(DEVIATION_MKTID, JDEVIATE_MKT_ID);
jsonParams.put(DEVIAT_REASON, JDEVIAT_REASON);
rootObjecteviation.put("Deviation", jsonParams);
}
Main reason is you are merging with same JSONObject with next one.
So you will get only last added data.
so use this.
rootObjecteviation = new JSONObject();
while (c.moveToNext())
{
JSONObject jsonParams = new JSONObject();
jsonParams.put(DEVIAT_ID, c.getInt(c.getColumnIndex(DEVIAT_ID)));
jsonParams.put(DEVIAT_H_ID, c.getInt(c.getColumnIndex(DEVIAT_H_ID)));
jsonParams.put(DEVIAT_L_ID, c.getInt(c.getColumnIndex(DEVIAT_L_ID)));
jsonParams.put(DEVIAT_TPDATE, "/Date(1483295400000+0530)/");
jsonParams.put(DEVIATION_MKTID, c.getInt(c.getColumnIndex(DEVIATION_MKTID)));
jsonParams.put(DEVIAT_REASON, c.getString(c.getColumnIndex(DEVIAT_REASON)));
rootObjecteviation.put("Deviation", jsonParams);
}
I have solved it by below code,
private void DoGetAndUploadDeviationData() throws JSONException, UnsupportedEncodingException {
RDB.getWritableDatabase();
String table = TABLE_DEVIATION_DEATIALS;
String[] columns = {DEVIAT_ID, DEVIAT_H_ID, DEVIAT_L_ID, DEVIAT_REASON, DEVIAT_TPDATE, DEVIATION_MKTID, DEVIATION_ISUPLOADED};
String selection = DEVIATION_DATETIME + " = ?";
String[] selectionArgs = {""};
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
Cursor c = RDB.query(table, columns, selection, selectionArgs, null, null, null, null);
rootObjecteviation = new JSONObject();
while (c.moveToNext())
{
JSONObject jsonParams = new JSONObject();
jsonParams.put(DEVIAT_ID, c.getInt(c.getColumnIndex(DEVIAT_ID)));
jsonParams.put(DEVIAT_H_ID, c.getInt(c.getColumnIndex(DEVIAT_H_ID)));
jsonParams.put(DEVIAT_L_ID, c.getInt(c.getColumnIndex(DEVIAT_L_ID)));
jsonParams.put(DEVIAT_TPDATE, "/Date(1483295400000+0530)/");
jsonParams.put(DEVIATION_MKTID, c.getInt(c.getColumnIndex(DEVIATION_MKTID)));
jsonParams.put(DEVIAT_REASON, c.getString(c.getColumnIndex(DEVIAT_REASON)));
rootObjecteviation.put("Deviation", jsonParams);
entityDeviation = new StringEntity(rootObjecteviation.toString());
callWebServiceDeviation(entityDeviation);
}
}
private void callWebServiceDeviation(HttpEntity params) {
client.post(this, URLDeviation.trim(), params, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String resonseStr = new String(responseBody);
Log.d("Inside Success", String.valueOf(statusCode));
gson = new Gson();
response = gson.fromJson(resonseStr, Response.class);
Log.d("response", response.toString());
String Message = response.getFillDeviationResult().get(0).getMessage();
int DevId = response.getFillDeviationResult().get(0).getDeviationID();
Log.d("Submitted DevId", String.valueOf(DevId));
Log.d("Chech Loop", String.valueOf(checkIncrement));
if (Message.equals("Success")) {
updateRowDeviation(DevId);
updateCountI = updateCountI + 1;
tvDeviationPendingCount.setText("Deviation Count is " + updateCountI + "/" + CountDevPenTable);
} else if (Message.equals("All Ready Submited Deviation")) {
updateRowDeviation(DevId);
updateCountI = updateCountI + 1;
tvDeviationPendingCount.setText("Deviation Count is " + updateCountI + "/" + CountDevPenTable);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// Hide Progress Dialog
progressDialog.dismiss();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
}

Adding an array in params.put to volley request in android

I'm using Volley to interact with an API. I need to send a post request (with parameters) to a service that returns a JSON Array.
My Api code is having a function like:
public function Add($tripData) {
$response = "Unsuccessful";
if (isset($tripData)) {
//print_r($tripData);
$tripsModel = new TasksModel();
$tripsModel->user_id = $tripData["user_id"];
$tripsModel->date = $tripData["date"];
$tripsModel->latitude = $tripData["latitude"];
$tripsModel->longitude = $tripData["longitude"];
$tripsModel->location = $tripData["location"];
$tripsModel->notes = $tripData["notes"];
$tripsModel->trip = $tripData["trip"];
$tripsModel->city = $tripData["city"];
$method = new CommonMethods();
$response = $method->save("locationdetails", $tripsModel);
}
echo json_encode($response);
}
I just need to put params.put("data", data) to be in following kind of array:
$taskData["user_id"]=2;
$tripData["date"]="2015-06-02 16:01";
$tripData["latitude"]="41.213181";
$tripData["longitude"]="-124.004631";
$tripData["location"]="Redwood National";
$tripData["notes"]="hello";
$tripData["trip"]=3;
$tripData["city"]="California";
so that it could be used as:
$obj = new Myclass;
$var = $obj->Add($tripData);
I have checked the service already but could not post it from android code using hashmap.
private void insertTripData(final String[] tripData) {
// TODO Auto-generated method stub
// Tag used to cancel the request
String tag_string_req = "req_login";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("inserttrip",
"inserttrip Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
// Launch main activity
Toast.makeText(getApplicationContext(),
"user data inserted", Toast.LENGTH_LONG)
.show();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
// String errorMsg =
// "Please check your network connection";
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("insertTripError",
"Data Error: " + error.getMessage());
String errorMsg = "Please check your network connection";
Toast.makeText(getApplicationContext(), errorMsg,
Toast.LENGTH_LONG).show();
}
}) {
#Override
protected HashMap<String, String> getParams() {
// Posting parameters to login url
JSONObject jsonObject = new JSONObject();
for (int i = 0; i <= tripData.length; i++) {
tripData[i] = "questionId_" + i + "_" + "ans_" + i;
try {
jsonObject.put("params_" + i, tripData[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String data= jsonObject.toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("tag", "trip");
params.put("action", "add");
params.put("data", data);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
You said, getting "ArrayIndexOutOfBound" error in your logcat.
May be problem with your getParams() method.
Change the for loop this:
for (int i = 0; i <= tripData.length; i++)
To:
for (int i = 0; i < tripData.length; i++)
Check now and if you get any other problem, please show your logcat here,.

Categories

Resources