Java Code Examples for com.android.volley.Response#Listener

The following examples show how to use com.android.volley.Response#Listener . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Request.java    From RestaurantApp with GNU General Public License v3.0 9 votes vote down vote up
public void requestVolley(final VolleyCallback callback){

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(requestMethod, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                callback.onSucces(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        requestQueue.add(jsonObjectRequest);

    }
 
Example 2
Source File: Request.java    From RestaurantApp with GNU General Public License v3.0 6 votes vote down vote up
public void requestDeleteBasket(final DeleteCallback callback, final int basketId){

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(requestMethod, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                callback.deleteResponse(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            public byte[] getBody() {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("basketId", String.valueOf(basketId));
                return new JSONObject(params).toString().getBytes();
            }
        };

        requestQueue.add(jsonObjectRequest);

    }
 
Example 3
Source File: separadorbraga.java    From LuxVilla with Apache License 2.0 6 votes vote down vote up
private void sendjsonRequest(){

        JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.GET,"http://brunoferreira.esy.es/serverdata.php",null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                casas=parsejsonResponse(response);
                adaptador.setCasas(casas);
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setVisibility(View.VISIBLE);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressBar.setVisibility(View.GONE);
                swipeRefreshLayout.setVisibility(View.VISIBLE);
                Snackbar.make(recyclerViewtodas,"Falha ao ligar ao servidor",Snackbar.LENGTH_LONG).show();

            }
        });

        requestQueue.add(jsonArrayRequest);
    }
 
Example 4
Source File: MainActivity.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
public void btnClick4(View view){
    ImageRequest request = new ImageRequest("http://cdn8.staztic.com/app/a/5993/5993203/volley-17-l-280x280.png", new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap response) {
            iv.setImageBitmap(response);
        }
    }, 200, 200, ImageView.ScaleType.FIT_XY, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    queue.add(request);

}
 
Example 5
Source File: OrderService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest UserAddToCartByOrderId(final int orderId, final Listener<Void> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(),
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {if (listener != null) {
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            final ArrayList<Object> params = new ArrayList<>();
            params.add(orderId);

            HashMap<String, Object> msg = new HashMap<>();
            msg.put("id", getMsgID());
            msg.put("method", "Order.UserAddToCartByOrderId");
            msg.put("params", params);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example 6
Source File: ImageRequest.java    From volley with Apache License 2.0 5 votes vote down vote up
@Override
protected void deliverResponse(Bitmap response) {
    Response.Listener<Bitmap> listener;
    synchronized (mLock) {
        listener = mListener;
    }
    if (listener != null) {
        listener.onResponse(response);
    }
}
 
Example 7
Source File: ShipfForMeService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest UserUpdateShipForMeOrder(final int orderId, final String warehouseCode, final String shipperName, final String wayBill, final String alternative, final boolean takePhoto, final String repack, final Listener<Void> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(),
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {if (listener != null) {
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            final ArrayList<Object> params = new ArrayList<>();
            params.add(orderId);
            params.add(warehouseCode);
            params.add(shipperName);
            params.add(wayBill);
            params.add(alternative);
            params.add(takePhoto);
            params.add(repack);

            HashMap<String, Object> msg = new HashMap<>();
            msg.put("id", getMsgID());
            msg.put("method", "ShipfForMe.UserUpdateShipForMeOrder");
            msg.put("params", params);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example 8
Source File: OrderService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest GetOrderListByStatus(final String originCode, final String orderStatus, final String warehouseCode, final Listener<ArrayList<TOrder>> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Order/GetOrderListByStatus",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    ArrayList<TOrder> result;
                    result = BaseModule.doFromJSONArray(response, TOrder.class);

                    listener.onResponse(result);
                } catch (Exception ex) {
                     
                    // Log.d("ex", ex.toString());
                    // Log.d("jsonObject", response);
                     
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            HashMap<String, Object> msg = new HashMap<String, Object>();
            msg.put("originCode", originCode);
            msg.put("orderStatus", orderStatus);
            msg.put("warehouseCode", warehouseCode);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example 9
Source File: VolleyNetworking.java    From card-reader with MIT License 5 votes vote down vote up
/**
 * Volley class to make HTTP Post Requests to Google Cloud Vision API
 *
 * @param object, The POST request JSON body
 */
public void callGoogleVisionAPI(JSONObject object) {
    progressBar.setVisibility(View.VISIBLE);
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    String url = "https://vision.googleapis.com/v1/images:annotate?key=" + CLOUD_VISION_API_KEY;
    JsonObjectRequest postRequest = new JsonObjectRequest(url, object,
            new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response) {
                    // response
                    progressBar.setVisibility(View.GONE);
                    if(response!= null) {
                        String bCardText = getRelevantString(response);
                        try {
                            bCardText = bCardText.replace("\n", " ");
                            obtainedText.setText(bCardText);
                        }catch (NullPointerException e){
                            e.printStackTrace();
                        }
                    } else{
                        Log.w(TAG, "response is null");
                    }
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(context, "Network error. Processing failed", Toast.LENGTH_LONG).show();
                    Log.w(TAG, error.toString());
                }
            }
    );
    requestQueue.add(postRequest);
}
 
Example 10
Source File: OrderService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest GetArrivedOrderSummary(final String originCode, final String warehouseCode, final Listener<ArrayList<TArrivedOrderSummary>> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Order/GetArrivedOrderSummary",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    ArrayList<TArrivedOrderSummary> result;
                    result = BaseModule.doFromJSONArray(response, TArrivedOrderSummary.class);

                    listener.onResponse(result);
                } catch (Exception ex) {
                     
                    // Log.d("ex", ex.toString());
                    // Log.d("jsonObject", response);
                     
                    listener.onResponse(null);
                }
            }
        }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onResponse(null);
        }
    }) {
        @Override
        public byte[] getBody() {
            HashMap<String, Object> msg = new HashMap<String, Object>();
            msg.put("originCode", originCode);
            msg.put("warehouseCode", warehouseCode);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example 11
Source File: WishlistFragment.java    From openshop.io-android with MIT License 5 votes vote down vote up
/**
 * Load wishlist content.
 *
 * @param user logged user.
 */
private void getWishlistContent(@NonNull User user) {
    String url = String.format(EndPoints.WISHLIST, SettingsMy.getActualNonNullShop(getActivity()).getId());

    progressDialog.show();
    GsonRequest<WishlistResponse> getWishlist = new GsonRequest<>(Request.Method.GET, url, null, WishlistResponse.class,
            new Response.Listener<WishlistResponse>() {
                @Override
                public void onResponse(@NonNull WishlistResponse wishlistResponse) {
                    if (progressDialog != null) progressDialog.cancel();

                    for (int i = 0; i < wishlistResponse.getItems().size(); i++) {
                        wishlistAdapter.add(i, wishlistResponse.getItems().get(i));
                    }
                    checkIfEmpty();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (progressDialog != null) progressDialog.cancel();
            MsgUtils.logAndShowErrorMessage(getActivity(), error);
        }
    }, getFragmentManager(), user.getAccessToken());
    getWishlist.setRetryPolicy(MyApplication.getDefaultRetryPolice());
    getWishlist.setShouldCache(false);
    MyApplication.getInstance().addToRequestQueue(getWishlist, CONST.CART_REQUESTS_TAG);
}
 
Example 12
Source File: MusicBrainzProvider.java    From odyssey with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void fetchImage(final ArtworkRequestModel model, final Context context,
                       final Response.Listener<ImageResponse> listener, final ArtFetchError errorListener) {
    switch (model.getType()) {
        case ALBUM:
            getAlbumMBID(model,
                    response -> parseMusicBrainzReleaseJSON(model, 0, response, context, listener, errorListener),
                    error -> errorListener.fetchVolleyError(model, context, error));
            break;
        case ARTIST:
            // not used for this provider
            break;
    }
}
 
Example 13
Source File: ConsoleApi.java    From swagger-aem with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * 

*/
public void getAemProductInfo (final Response.Listener<List<String>> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/system/console/status-productinfo.json".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();



  String[] contentTypes = {
    
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
        }

  String[] authNames = new String[] { "aemAuth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
          try {
            responseListener.onResponse((List<String>) ApiInvoker.deserialize(localVarResponse,  "array", String.class));
          } catch (ApiException exception) {
             errorListener.onErrorResponse(new VolleyError(exception));
          }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}
 
Example 14
Source File: SearchActivity.java    From QuickNews with MIT License 4 votes vote down vote up
public JsonObjectRequest getNewsData(String baseUrl, final String parameter, final ListView listView){
    System.out.println("访问的Url为"+(baseUrl+parameter));
    JsonObjectRequest jsonObjectRequest=new JsonObjectRequest((baseUrl + parameter).trim(), null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try{
                        System.out.println("Volley得到的response是+"+response.toString());
                        Gson gson = new Gson();
                        data=gson.fromJson(response.toString(),new TypeToken<Data>(){}.getType());
                        List<News> newsList =new ArrayList<>();
                        newsList=data.getData();
                        System.out.println("newsList的size是"+newsList.size());
                        mProgressBar.setVisibility(View.GONE);
                        mLvSearchResult.setVisibility(View.VISIBLE);
                        NewsAdapter adapter=new NewsAdapter(SearchActivity.this,newsList,1,parameter);
                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

                        final List<News> finalNewsList = newsList;
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                Intent intent=new Intent(SearchActivity.this, NewsActivity.class);
                                System.out.println("i的位置"+i);
                                System.out.println("newsList的size"+ finalNewsList.size());
                                System.out.println("newsList.get(i).getDisplay_url()"+ finalNewsList.get(i).getDisplay_url());
                                intent.putExtra("news_url", finalNewsList.get(i).getDisplay_url());
                                startActivity(intent);
                            }
                        });

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

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println("获取信息失败……");
            System.out.println("error是"+error.toString());

        }
    });

    System.out.println("jsonObjectRequest"+jsonObjectRequest.toString());
    return jsonObjectRequest;
}
 
Example 15
Source File: StringRequestGet.java    From Tpay with GNU General Public License v3.0 4 votes vote down vote up
public StringRequestGet(String url, Response.Listener<String> listener, @Nullable Response.ErrorListener errorListener) {
    super(Method.GET, url, null, listener, errorListener);
    setRetryPolicy(new DefaultRetryPolicy(5000, 0, 0));
}
 
Example 16
Source File: HttpRequest.java    From android-instagram-connector with Apache License 2.0 4 votes vote down vote up
public HttpRequest(int method, String url, String body, Response.Listener<HttpResponse> listener, Response.ErrorListener errorListener) {
    super(method, url,errorListener);

    this.mListener = listener;
    this.mBody = body;
}
 
Example 17
Source File: FeedActivity.java    From indigenous-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Search feeds.
 */
public void searchFeeds(final String url) {

    if (!Utility.hasConnection(getApplicationContext())) {
        Snackbar.make(layout, getString(R.string.no_connection), Snackbar.LENGTH_SHORT).show();
        return;
    }

    Snackbar.make(layout, getString(R.string.feed_searching), Snackbar.LENGTH_LONG).show();
    String MicrosubEndpoint = user.getMicrosubEndpoint();
    StringRequest getRequest = new StringRequest(Request.Method.POST, MicrosubEndpoint,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject object;
                        JSONObject microsubResponse = new JSONObject(response);
                        JSONArray itemList = microsubResponse.getJSONArray("results");

                        Feeds.clear();
                        for (int i = 0; i < itemList.length(); i++) {
                            object = itemList.getJSONObject(i);
                            Feed item = new Feed();
                            item.setUrl(object.getString("url"));
                            item.setType(object.getString("type"));
                            item.setChannel(channelId);
                            Feeds.add(item);
                        }

                        if (Feeds.size() > 0) {
                            resultTitle.setVisibility(View.VISIBLE);
                            adapter.notifyDataSetChanged();
                        }
                        else {
                            Snackbar.make(layout, getString(R.string.feed_no_results), Snackbar.LENGTH_SHORT).show();
                        }
                    }
                    catch (JSONException e) {
                        String message = String.format(getString(R.string.feed_parse_error), e.getMessage());
                        final Snackbar snack = Snackbar.make(layout, message, Snackbar.LENGTH_INDEFINITE);
                        snack.setAction(getString(R.string.close), new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    snack.dismiss();
                                }
                            }
                        );
                        snack.show();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Snackbar.make(layout, getString(R.string.feed_search_error), Snackbar.LENGTH_SHORT).show();
                }
            }
    )
    {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();

            params.put("action", "search");
            params.put("query", url);
            return params;
        }

        @Override
        public Map<String, String> getHeaders() {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            headers.put("Authorization", "Bearer " + user.getAccessToken());
            return headers;
        }
    };

    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    queue.add(getRequest);
}
 
Example 18
Source File: PlaceSearchReviewFragment.java    From Place-Search-Service with MIT License 4 votes vote down vote up
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_review, container, false);

    list_review = (ListView) view.findViewById(R.id.reviewList);
    layout = view.findViewById(R.id.layout);
    review_none_txt = view.findViewById(R.id.review_none_txt);
    Bundle arguments = getArguments();
    obj = (PlacesSearchResultObj.PlacesSearchResultItemObj) arguments.getSerializable("data");
    String place_id = obj.getPlace_id();
    context = getActivity();

    RequestQueue mQueue = Volley.newRequestQueue(context);
    String details_url = BaseUrl.Place_id_info_url + place_id;
    Log.v("url:", BaseUrl.Place_id_info_url + place_id);// the url can get the detail json
    JsonObjectRequest jsonRequest = new JsonObjectRequest
            (Request.Method.GET, details_url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response != null) {
                        try {
                            Log.v("the response is ", response.toString());
                            JSONObject json_details = response.getJSONObject("result");
                            String placeDetails = json_details.toString();
                            Gson gson = new Gson();
                            details = gson.fromJson(placeDetails, new TypeToken<Details>() {}.getType());
                            originDetails = details.myclone();
                            yelpRequest(details,view);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }finally {
                            if (context instanceof PlacesSearchItemActivity){
                                ((PlacesSearchItemActivity)context).requsetNumberAdd();
                            }
                        }
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.i("the error is ",error.toString());
                    Toast.makeText(getContext(),"API failure",Toast.LENGTH_LONG).show();
                    error.printStackTrace();
                    if (context instanceof PlacesSearchItemActivity){
                        ((PlacesSearchItemActivity)context).requsetNumberAdd();
                    }
                }
            });
    mQueue.add(jsonRequest);

    return view;
}
 
Example 19
Source File: CustomApi.java    From swagger-aem with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * 
 * @param tags    * @param combineTagsOr 
*/
public void getAemHealthCheck (String tags, Boolean combineTagsOr, final Response.Listener<String> responseListener, final Response.ErrorListener errorListener) {
  Object postBody = null;


  // create path and map variables
  String path = "/system/health".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  // header params
  Map<String, String> headerParams = new HashMap<String, String>();
  // form params
  Map<String, String> formParams = new HashMap<String, String>();

  queryParams.addAll(ApiInvoker.parameterToPairs("", "tags", tags));
  queryParams.addAll(ApiInvoker.parameterToPairs("", "combineTagsOr", combineTagsOr));


  String[] contentTypes = {
    
  };
  String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json";

  if (contentType.startsWith("multipart/form-data")) {
    // file uploading
    MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();
    

    HttpEntity httpEntity = localVarBuilder.build();
    postBody = httpEntity;
  } else {
    // normal form params
        }

  String[] authNames = new String[] { "aemAuth" };

  try {
    apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames,
      new Response.Listener<String>() {
        @Override
        public void onResponse(String localVarResponse) {
          try {
            responseListener.onResponse((String) ApiInvoker.deserialize(localVarResponse,  "", String.class));
          } catch (ApiException exception) {
             errorListener.onErrorResponse(new VolleyError(exception));
          }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
          errorListener.onErrorResponse(error);
        }
    });
  } catch (ApiException ex) {
    errorListener.onErrorResponse(new VolleyError(ex));
  }
}
 
Example 20
Source File: Facts.java    From Crimson with Apache License 2.0 3 votes vote down vote up
private void getFactDetails() {

        String url = "http://webianks.com/crimson/all_facts.json";

        VolleySingleton volleySingleton = VolleySingleton.getInstance();
        RequestQueue requestQueue = volleySingleton.getRequestQueue();

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                //got the response

                parseFacts(response);

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

                try {
                    Toast.makeText(getActivity(),"Can't fetch facts.",Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        requestQueue.add(jsonObjectRequest);


    }