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.
Related
I apply cache but it works only one time when I click on first item it shows data after that when I click on another it shows same data how t fix it any guidelines
Here is my code
String URL = "http://facekart.azanic.com/Data_show_all_.php";
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Fetcing, please wait...");
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("result");//getting array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Itemssetget it = new Itemssetget();
it.setName(jsonObject1.getString("name"));
it.setPhonenumber_seller(jsonObject1.getString("phonenumber_seller"));
it.setPrice(jsonObject1.getString("price"));
it.setDiscountprice(jsonObject1.getString("discountprice"));
it.setUnits(jsonObject1.getString("units"));
it.setStock(jsonObject1.getString("stock"));
it.setId(jsonObject1.getString("key_auto"));
it.setImageurl("http://facekart.azanic.com/images/" + jsonObject1.getString("imageurl"));
if (it.getStock().toString().equals("In stock")) {
items_random.add(it);
}
}
if (!items_random.isEmpty() && getActivity() != null) {
myAdapter = new homebuyer_fruits_adapter(getActivity(), items_random, homebuyer.phone_number_shop);
myAdapter.notifyDataSetChanged();
Random_list.addHeaderView(random_v);
Random_list.setAdapter(myAdapter);
Random_list.setSmoothScrollbarEnabled(true);
loadingdataprogress.stopShimmerAnimation();
loadingdataprogress.setVisibility(View.INVISIBLE);
// Toast.makeText(getContext(),"ADDED",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getContext(), "Some error occurred -> " + volleyError, Toast.LENGTH_LONG).show();
;
}
}) {
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new String(jsonString), cacheEntry);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(String s) {
super.deliverResponse(s);
}
#Override
public void deliverError(VolleyError error) {
super.deliverError(error);
}
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("s_number", homebuyer.phone_number_shop);
parameters.put("trig", "all");
return parameters;
}
};
RequestQueue rQueue = Volley.newRequestQueue(getContext());
rQueue.add(request);
Thanks in advance if any one help me in this I want every item click it shows data but first time it get from service second time it use from cache r any other method you can also suggest me How I smooth my app
I don't want to loading again and again
I have implemented search function to get details of clients but when i select the searched item it gives me an error of
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
so on
This is my code i am using Json to search my clients details and storing in array but when i search the data and select it i get the above error. Please help me out .Thank You
public void RunSearchClientService() {
//progressDialog.show();
JsonObjectRequest postRequest = new JsonObjectRequest
(Request.Method.POST, Network.API_URL + "clients/search", api_parameter, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject result = ((JSONObject) response.get("data"));
JSONArray clients = (JSONArray) result.get("clients");
JSONArray invoice_lines = (JSONArray) result.get("invoice_lines");
Integer invoice_number = helper_string.optInt(result, "invoice_number");
logoImage = helper_string.optString(result, "logo");
if (invoice_number > 0) {
edit_invoice_number.setText(String.format("%04d", invoice_number));
toolbar.setTitle(String.format("INV-%04d", invoice_number));
}
array_list_clients.clear();
array_clients = new String[clients.length()];
Integer selected_client_index = 0;
if (clients.length() > 0) {
for (int i = 0; i < clients.length(); i++) {
JSONObject obj = clients.getJSONObject(i);
Client client = new Client();
client.Id = obj.optInt("id");
client.UserId = obj.optInt("user_id");
client.Name = helper_string.optString(obj, "name");
client.Reg_Num = obj.optString("reg_num");
client.Email = helper_string.optString(obj, "email");
client.Address1 = helper_string.optString(obj, "address1");
client.Address2 = helper_string.optString(obj, "address2");
client.City = helper_string.optString(obj, "city");
client.State = helper_string.optString(obj, "state");
client.Postcode = helper_string.optString(obj, "postcode");
client.Country = helper_string.optString(obj, "country");
array_list_clients.add(client);
array_clients[i] = client.Name + " " + "Reg No. : "+ client.Reg_Num ;
if (currentInvoice != null && currentInvoice.ClientId == client.Id) {
selected_client_index = i;
currentClient = client;
}
/*if (obj.optInt("invoice_number") > 0)
invoice_number = obj.optInt("invoice_number");*/
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(NewInvoiceActivity.this, R.layout.custom_simple_spinner_item, array_clients);
spinner_client.setAdapter(adapter);
spinner_client.setSelection(selected_client_index);
}
if (invoice_lines.length() > 0) {
for (int i = 0; i < invoice_lines.length(); i++) {
JSONObject obj = invoice_lines.getJSONObject(i);
Item item = new Item();
item.Id = obj.optInt("id");
item.Quantity = obj.optInt("quantity");
item.Name = helper_string.optString(obj, "name");
item.Rate = obj.optDouble("rate");
item.Description = helper_string.optString(obj, "description");
array_list_items.add(item);
}
calculate_total();
setListViewHeightBasedOnChildren(list_items);
}
if (array_list_items_from_intent != null && array_list_items_from_intent.size() > 0) {
for (int i = 0; i < array_list_items_from_intent.size(); i++) {
array_list_items.add(array_list_items_from_intent.get(i));
}
calculate_total();
setListViewHeightBasedOnChildren(list_items);
}
} catch (Exception ex) {
Toast.makeText(NewInvoiceActivity.this, R.string.error_try_again_support, Toast.LENGTH_LONG).show();
}
// if (progressDialog != null && progressDialog.isShowing()) {
// // If the response is JSONObject instead of expected JSONArray
// progressDialog.dismiss();
// }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (progressDialog != null && progressDialog.isShowing()) {
// If the response is JSONObject instead of expected JSONArray
progressDialog.dismiss();
}
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
try {
JSONObject json = new JSONObject(new String(response.data));
// Toast.makeText(NewInvoiceActivity.this, json.has("message") ? json.getString("message") : json.getString("error"), Toast.LENGTH_LONG).show();
} catch (JSONException ex) {
Toast.makeText(NewInvoiceActivity.this, R.string.error_try_again_support, Toast.LENGTH_SHORT).show();
}
} else {
// Toast.makeText(NewInvoiceActivity.this, error != null && error.getMessage() != null ? error.getMessage() : error.toString(), Toast.LENGTH_LONG).show();
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("X-API-KEY", MainActivity.api_key);
return params;
}
};
// Get a RequestQueue
RequestQueue queue = MySingleton.getInstance(NewInvoiceActivity.this).getRequestQueue();
//Used to mark the request, so we can cancel it on our onStop method
postRequest.setTag(TAG);
MySingleton.getInstance(NewInvoiceActivity.this).addToRequestQueue(postRequest);
}
The error ArrayIndexOutOfBoundsException: length=1; index=1 means your array at index 1 is not valid; in other words, you are trying to access the second element of an array that has only one element.
The below code will give a similar error:
public class ReplicateError {
public static void main(String args[]) {
// reproducing java.lang.ArrayIndexOutOfBoundsException : 1 error
String[] clients = {"John"};
String client = clients[1];
// this will throw java.lang.ArrayIndexOutOfBoundsException : 1
System.out.println(client);
}
}
I suggest you do a bound check:
if (args.length < 2) {
System.err.println("Not enough arguments received.");
return;
}
I'm using Volley in my android application but I'm facing a problem, I have to use volley only for async connections?
Because per example I have an 1800 record database from web service to my application I start my volley and retrieve fine but I'm inserting this records on my SQLite and when I do that my application freezy why?
I thinking volley have async methods to handle this but it freezy when I loop on a volley and insert. My dialogue stops animation and everything.
Before volley I use the Assyntask from android and never freezy my application and I'm using httpost but now I change to volley and I'm facing this issue I will share my code :
public void volleyJsonObjectRequest(String url) {
String REQUEST_TAG = "com.androidtutorialpoint.volleyJsonObjectRequest";
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Sincronizando pedidos..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
List<HashMap<String,String>> listObjectsServer = new ArrayList<>();
try {
MDAutomap controller;
controller = new MDAutomap(getActivity());
JSONArray jsonArrayPedidos = response.getJSONArray("pedidos");
if (jsonArrayPedidos != null && jsonArrayPedidos.length() > 0) {
HashMap<String, String> pedidos = new HashMap<String, String>();
for (int i = 0; i < jsonArrayPedidos.length(); i++) {
JSONObject obj = jsonArrayPedidos.getJSONObject(i);
pedidos.put("nomeusuario", obj.getString("nomeUsuario"));
pedidos.put("id", obj.getString("id"));
pedidos.put("nome", obj.getString("nome"));
pedidos.put("eventoid", obj.getString("eventoid"));
pedidos.put("descricao", obj.getString("descricao"));
pedidos.put("valor", obj.getString("valor"));
pedidos.put("veiculo", obj.getString("veiculo"));
pedidos.put("transactioncode", obj.getString("transactioncode"));
pedidos.put("referencecode", obj.getString("referencecode"));
pedidos.put("status", obj.getString("status"));
pedidos.put("flag", obj.getString("flag"));
pedidos.put("usuario", obj.getString("usuario"));
pedidos.put("created_at", obj.getString("created_at"));
pedidos.put("updated_at", obj.getString("updated_at"));
if (controller.checkPedido(pedidos.get("id"))) {
controller.updatePedido(pedidos);
}else {
controller.inserirPedido(pedidos);
}
}
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
//userMsg("Sincronizado com sucesso os pedidos.");
}else {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
//userMsg("Não existe pedidos para sincronizar.");
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
userMsg("Não foi possível fazer conexão, por favor tenta novamente.");
}
}
);
Yes it will freeze because it is getting huge data from service and inserting in Db on main UI thread . So i solved that problem by taking a async task inside volley response and it worked in my case
private void hitApiForSyncDropdownsData(final String ApiType) {
showDialog();
String jsonAsParamstr = makeJsonStr(ApiType);
JsonObjectRequest req = new JsonObjectRequest(wholeUrl, makeJsonFromStrJson(jsonAsParamstr),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString(Constant.Utils.responseCode).equals("1")) {
new ProcessJsonAsync(ApiType).execute(response, null, null);
//processing response in Async as getting heavy reponse and inserting into DB
} else {
showShortToast(response.getString(Constant.Utils.responseMessage));
dismissDialog();
}
} catch (JSONException e) {
e.printStackTrace();
dismissDialog();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
showmsgForVolleyIfConnProb(error, context);
}
});
req = setretryPolicy(req);
AppController.getInstance().addToRequestQueue(req);
}
and that async Code would look like
private class ProcessJsonAsync extends AsyncTask<JSONObject, Void, Integer> {
String ApiType;
ProcessJsonAsync(String ApiType) {
this.ApiType = ApiType;
}
protected Integer doInBackground(JSONObject... jsonObjects) {
ArrayList<DataModel> dataModelArraylist = new ArrayList<>();
Integer insertedResult = -1;
try {
JSONObject response = jsonObjects[0];
if (response.getString(Constant.Utils.responseCode).equalsIgnoreCase("1")) {
JSONArray jsonarray = response.getJSONArray(Constant.Utils.responseObject);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
dataModelArraylist.add(new DataModel(jsonObj.getString("data1"), jsonObj.getString("data2"));
}
DataStrucTable dataStrucTable=new DataStructTable();
insertedResult=dataStrucTable.insertArrayInDb(dataModelArraylist);
//here it will insert thousands of entries in DB on background thread and will not hang your UI
}
} catch (JSONException e) {
e.printStackTrace();
}
return insertedResult;
}
#Override
protected void onPostExecute(Integer integer) {
Toast.makeText(context, integer == -1 ? "Data couldn't insert in DB" :"Data successfully inserted", Toast.LENGTH_SHORT).show();
}
}
I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})
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,.