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();
}
}
});
}
Related
When displaying a context, a failure occurs. What could be the problem?
No results were found for your request
If results are found, displays if there is no context menu, that no results were found, but it gives an error and application failure
public void run(final View view) throws IOException{
Log.d(TAG, "run: up and running...");
if (frag_id==0 || frag_id==1) { //if home fragment & search fragment
Log.d(TAG, "getIntentData: frag id not 2");
if (search_term == null) {
urlImage = "https://api.pexels.com/v1/curated";
} else {
int randPage;
do {
randPage = new Random().nextInt(15);
}while(randPage==0);
urlImage = "https://api.pexels.com/v1/search?query=" + search_term.toLowerCase() + "&per_page=15&page=" + randPage;
}
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.header("Authorization", StaticUtils.API_KEY)
.url(urlImage)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
call.cancel();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
final String myResponse = response.body() != null ? response.body().string() : null;
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d(TAG, "run: integrated successfully: ");
if (!StaticUtils.imagesListTemp.isEmpty()){
StaticUtils.imagesListTemp.clear();
}
try {
JSONObject json = new JSONObject(myResponse);
JSONArray jsonArray = json.getJSONArray("photos");
if (jsonArray.length()>0){
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int imageId = jsonObject.getInt("id");
String srcName = jsonObject.getString("photographer");
String srcUrl = jsonObject.getString("photographer_url");
String dimen = jsonObject.getString("width")+"x"+jsonObject.getString("height");
JSONObject srcObject = jsonObject.getJSONObject("src"); //getting the image sources of different dimens
String imgSrcOrg = srcObject.getString("original");
String imgSrcLarg = srcObject.getString("large");
String imgSrcMid = srcObject.getString("medium");
String imgSrcSml = srcObject.getString("small");
String imgSrcPort = srcObject.getString("portrait");
String imgSrcLand = srcObject.getString("landscape");
String imgSrcTiny = srcObject.getString("tiny");
ImageDifferentSize imageArray = new ImageDifferentSize(imgSrcOrg,imgSrcLarg,imgSrcMid,imgSrcSml,imgSrcPort,imgSrcLand,imgSrcTiny);
StaticUtils.imagesListTemp.add(new ImagesItem(imageId, srcName, dimen, srcUrl,imageArray));
ImagesFragment.adapter.notifyDataSetChanged();
}
}else{
//replace with snackBar
Toast.makeText(getApplicationContext(), "This is my Toast message!",
Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "run: List size: "+StaticUtils.imagesListTemp.size());
boolean isAddSucceed = StaticUtils.imagesList.addAll(StaticUtils.imagesListTemp);
Log.d(TAG, "onCreate: Copy operation succeed:"+isAddSucceed+", Final arrayList size: "+StaticUtils.imagesList.size());
} catch (JSONException e) {
Log.d(TAG, "onResponse: Json Parsing data error.");
e.printStackTrace();
}
}
When displaying a context, a failure occurs. What could be the problem?
No results were found for your request
If results are found, displays if there is no context menu, that no results were found, but it gives an error and application failure
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.
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);
}
I have this code created with Volley and JSON:
public List<String> result = new ArrayList<String>();
public List<String> mostraDati(){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, DatiNet.MostraDati, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
System.out.println("fin qui ci siamo");
JSONArray utenti = response.getJSONArray("utenti");
List<String> resTemp = new ArrayList<String>();
for (int i = 0; i < utenti.length(); i++) {
JSONObject student = utenti.getJSONObject(i);
String nome = student.getString("nome");
String cognome = student.getString("cognome");
String numero = student.getString("numero");
String email = student.getString("email");
resTemp.add(nome + " " + cognome + " " + email);
}
result = resTemp;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
System.out.println(result.toString());
return result;
}
It works well but the return is always null "[]". How to solve the problem?
I think the problem is to port the value out of the method of jsonObjectRequest.
You have to change your code to add one arrayList value to another arrayList.
Change
result = resTemp;
to
result.addAll(resTemp);
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,.