Java Code Examples for com.android.volley.Response

The following examples show how to use com.android.volley.Response. These examples are extracted from open source projects. 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 Project: openshop.io-android   Source File: ProductFragment.java    License: MIT License 6 votes vote down vote up
/**
 * Load product wishlist info. Determine state of wishlist button.
 * If a user is logged out, nothing will happen.
 *
 * @param productId id of product.
 */
private void getWishListInfo(long productId) {
    User user = SettingsMy.getActiveUser();
    if (user != null) {
        // determine if product is in wishlist
        String wishlistUrl = String.format(EndPoints.WISHLIST_IS_IN_WISHLIST, SettingsMy.getActualNonNullShop(getActivity()).getId(), productId);
        JsonRequest getWishlistInfo = new JsonRequest(Request.Method.GET, wishlistUrl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                prepareWishListButton(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MsgUtils.logAndShowErrorMessage(getActivity(), error);
            }
        }, getFragmentManager(), user.getAccessToken());
        getWishlistInfo.setRetryPolicy(MyApplication.getDefaultRetryPolice());
        getWishlistInfo.setShouldCache(false);
        MyApplication.getInstance().addToRequestQueue(getWishlistInfo, CONST.PRODUCT_REQUESTS_TAG);
    }
}
 
Example 2
Source Project: openshop.io-android   Source File: AccountFragment.java    License: MIT License 6 votes vote down vote up
private void syncUserData(@NonNull User user) {
    String url = String.format(EndPoints.USER_SINGLE, SettingsMy.getActualNonNullShop(getActivity()).getId(), user.getId());
    pDialog.show();

    GsonRequest<User> getUser = new GsonRequest<>(Request.Method.GET, url, null, User.class,
            new Response.Listener<User>() {
                @Override
                public void onResponse(@NonNull User response) {
                    Timber.d("response: %s", response.toString());
                    SettingsMy.setActiveUser(response);
                    refreshScreen(SettingsMy.getActiveUser());
                    if (pDialog != null) pDialog.cancel();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (pDialog != null) pDialog.cancel();
            MsgUtils.logAndShowErrorMessage(getActivity(), error);
        }
    }, getFragmentManager(), user.getAccessToken());
    getUser.setRetryPolicy(MyApplication.getDefaultRetryPolice());
    getUser.setShouldCache(false);
    MyApplication.getInstance().addToRequestQueue(getUser, CONST.ACCOUNT_REQUESTS_TAG);
}
 
Example 3
Source Project: TouchNews   Source File: NetRequestUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get请求获取JsonObject
 *
 * @param url      url
 * @param param    param
 * @param listener callback
 */
public void getJson(String url, Map<String, String> param, final RequestListener listener) {
    url += prepareParam(param);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            listener.onResponse(response);
            Log.i(TAG, response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onError(error);
            Log.i(TAG, error.getMessage(), error);
        }
    });
    mRequestQueue.add(jsonObjectRequest);
}
 
Example 4
Source Project: LuxVilla   Source File: searchableactivity.java    License: 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);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Snackbar.make(rvc1,"Falha ao ligar ao servidor",Snackbar.LENGTH_LONG).show();

            }
        });

        requestQueue.add(jsonArrayRequest);
    }
 
Example 5
Source Project: LuxVilla   Source File: separadorporto.java    License: 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 6
Source Project: HttpRequestProcessor   Source File: VolleyProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void post(String url, Map<String, Object> params, final ICallBack callback) {
    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            callback.onSuccess(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            callback.onFailed(volleyError.toString());
        }
    });
    mQueue.add(stringRequest);
}
 
Example 7
Source Project: allenglish   Source File: AboutModelImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void checkNewVersion() {
    Map<String, String> map = new HashMap<>();
    map.put("appKey", "56bd51ddb76877188a1836d791ed8436");
    map.put("_api_key", "a08ef5ee127a27bd4210f7e1f9e7c84e");
    VolleySingleton.getInstance().addToRequestQueue(new GsonRequest<>(Request.Method.POST, "https://www.pgyer.com/apiv2/app/view",
            ViewBean.class,
            null, map,
            new Response.Listener<ViewBean>() {
                @Override
                public void onResponse(ViewBean response) {
                    if (response.data.buildVersion.equals(CommonUtils.getVersionName(BaseApplication.getInstance()))) {
                        listener.onNoNewVersion();
                    } else {
                        listener.onGetANewVersion(response.data.buildUpdateDescription);
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            listener.onCheckFailed();
        }
    }));
}
 
Example 8
Source Project: odyssey   Source File: LastFMProvider.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fetches the image URL for the raw image blob.
 *
 * @param model         Album to look for an image
 * @param listener      Callback listener to handle the response
 * @param errorListener Callback to handle a fetch error
 */
private void getAlbumImageURL(final ArtworkRequestModel model,
                              final Response.Listener<JSONObject> listener, final Response.ErrorListener errorListener) {
    String albumName = model.getEncodedAlbumName();
    String artistName = model.getEncodedArtistName();

    if (albumName.isEmpty() || artistName.isEmpty()) {
        errorListener.onErrorResponse(new VolleyError("required arguments are empty"));
    } else {
        String url = LAST_FM_API_URL + "album.getinfo&album=" + albumName + "&artist=" + artistName + "&api_key=" + API_KEY + LAST_FM_FORMAT_JSON;

        if (BuildConfig.DEBUG) {
            Log.v(TAG, url);
        }

        OdysseyJsonObjectRequest jsonObjectRequest = new OdysseyJsonObjectRequest(url, null, listener, errorListener);

        mRequestQueue.add(jsonObjectRequest);
    }
}
 
Example 9
Source Project: UberClone   Source File: NetworkUtil.java    License: MIT License 6 votes vote down vote up
public void httpRequest(String url, final HttpResponse httpResponse){
    if(availableNetwok()){
        RequestQueue queue= Volley.newRequestQueue(context);

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        httpResponse.httpResponseSuccess(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(stringRequest);
    }
}
 
Example 10
Source Project: openshop.io-android   Source File: UpdateCartItemDialogFragment.java    License: MIT License 6 votes vote down vote up
private void getProductDetail(CartProductItem cartProductItem) {
    String url = String.format(EndPoints.PRODUCTS_SINGLE, SettingsMy.getActualNonNullShop(getActivity()).getId(), cartProductItem.getVariant().getProductId());

    setProgressActive(true);

    GsonRequest<Product> getProductRequest = new GsonRequest<>(Request.Method.GET, url, null, Product.class,
            new Response.Listener<Product>() {
                @Override
                public void onResponse(@NonNull Product response) {
                    setProgressActive(false);
                    setSpinners(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            setProgressActive(false);
            MsgUtils.logAndShowErrorMessage(getActivity(), error);
        }
    });
    getProductRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice());
    getProductRequest.setShouldCache(false);
    MyApplication.getInstance().addToRequestQueue(getProductRequest, CONST.UPDATE_CART_ITEM_REQUESTS_TAG);
}
 
Example 11
public void getStatus(final int position) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, BACKEND_URL + "/registerees/totalUsers" , null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        int totalUsers = response.getInt("count");
                        status.setText(String.format("You are position %d of %d", position, totalUsers));
                        totalNumberOfUsers = totalUsers;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "That didn't work!");
        }
    });
    queue.add(jsonObjectRequest);
}
 
Example 12
Source Project: RestaurantApp   Source File: Request.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void requestVolleyDeskList(final ChangeDeskStatus changeDeskStatus, final int orderId, final int status){

        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(requestMethod, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                changeDeskStatus.changeStatus(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(context, String.valueOf(error), Toast.LENGTH_SHORT).show();
            }
        }){
            @Override
            public byte[] getBody() {
                HashMap<String, Integer> params = new HashMap<String, Integer>();
                params.put("orderId", orderId);
                params.put("status", status);
                return new JSONObject(params).toString().getBytes();
            }
        };

        requestQueue.add(jsonObjectRequest);

    }
 
Example 13
Source Project: allenglish   Source File: BaseLearningModelImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getLeanCloudBean(String tableName, int limit, int skin, String tag, String createdAt) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.CONTENT_TYPE, Constants.CONTENT_TYPE_VALUE);
    headers.put(Constants.X_LC_Id, Constants.X_LC_ID_VALUE);
    long timestamp = System.currentTimeMillis();
    headers.put(Constants.X_LC_SIGN, MD5.md5(timestamp + Constants.X_LC_KEY_VALUE) + "," + timestamp);
    String url;
    if (tag != null) {
        url = "https://leancloud.cn:443/1.1/classes/" + tableName + "?where={\"createdAt\":{\"$lt\":{\"__type\":\"Date\",\"iso\":\"" + createdAt + "\"}},\"tag\":\"" + StringUtils.encodeText(tag) + "\"}&limit=" + limit + "&order=-createdAt";
    } else {
        url = "https://leancloud.cn:443/1.1/classes/" + tableName + "?where={\"createdAt\":{\"$lt\":{\"__type\":\"Date\",\"iso\":\"" + createdAt + "\"}}}&limit=" + limit + "&order=-createdAt";
    }
    VolleySingleton.getInstance()
            .addToRequestQueue(new GsonRequest<>(url, LeanCloudApiBean.class, headers, null, new Response.Listener<LeanCloudApiBean>() {
                @Override
                public void onResponse(LeanCloudApiBean response) {
                    beanList.addAll(response.results);
                    addListAds();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }));
}
 
Example 14
Source Project: volley   Source File: ImageRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * For API compatibility with the pre-ScaleType variant of the constructor. Equivalent to the
 * normal constructor with {@code ScaleType.CENTER_INSIDE}.
 */
@Deprecated
public ImageRequest(
        String url,
        Response.Listener<Bitmap> listener,
        int maxWidth,
        int maxHeight,
        Config decodeConfig,
        Response.ErrorListener errorListener) {
    this(
            url,
            listener,
            maxWidth,
            maxHeight,
            ScaleType.CENTER_INSIDE,
            decodeConfig,
            errorListener);
}
 
Example 15
Source Project: openshop.io-android   Source File: WishlistFragment.java    License: MIT License 5 votes vote down vote up
/**
 * Method remove concrete product from the wishlist by wishlistId.
 * Expected all non-null parameters.
 *
 * @param activity        related activity.
 * @param wishlistId      id of the wishlist item representing product.
 * @param user            related user account.
 * @param requestTag      string identifying concrete request. Useful for request cancellation.
 * @param requestListener listener for operation results.
 */
public static void removeFromWishList(final FragmentActivity activity, long wishlistId, User user, String requestTag, final RequestListener requestListener) {
    if (activity != null && wishlistId != 0 && user != null && requestTag != null && requestListener != null) {
        String url = String.format(EndPoints.WISHLIST_SINGLE, SettingsMy.getActualNonNullShop(activity).getId(), wishlistId);
        JsonRequest req = new JsonRequest(Request.Method.DELETE, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Timber.d("RemoveFromWishlist response: %s", response.toString());
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        requestListener.requestSuccess(0);
                    }
                }, 500);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(final VolleyError error) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        requestListener.requestFailed(error);
                    }
                }, 500);
                MsgUtils.logAndShowErrorMessage(activity, error);
            }
        }, activity.getSupportFragmentManager(), user.getAccessToken());
        req.setRetryPolicy(MyApplication.getDefaultRetryPolice());
        req.setShouldCache(false);
        MyApplication.getInstance().addToRequestQueue(req, requestTag);
    } else {
        if (requestListener != null) requestListener.requestFailed(null);
        Timber.e(new RuntimeException(), "Remove from wishlist product with null parameters.");
    }
}
 
Example 16
Source Project: tgen   Source File: PaymentService.java    License: Apache License 2.0 5 votes vote down vote up
public static RpcRequest GetPaymentListByStatus(final String status, final int offset, final int limit, final Listener<ArrayList<TPaymentBillSummary>> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Payment/GetPaymentListByStatus",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    ArrayList<TPaymentBillSummary> result;
                    result = BaseModule.doFromJSONArray(response, TPaymentBillSummary.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("status", status);
            msg.put("offset", offset);
            msg.put("limit", limit);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example 17
Source Project: tgen   Source File: ShipfForMeService.java    License: Apache License 2.0 5 votes vote down vote up
public static RpcRequest UserGetShipForMeOrderDetailByOrderId(final int orderId, final Listener<TShipForMeOrder> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(),
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TShipForMeOrder result;
                    result = BaseModule.fromJSON(response, TShipForMeOrder.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() {
            final ArrayList<Object> params = new ArrayList<>();
            params.add(orderId);

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

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example 18
Source Project: SaveVolley   Source File: RequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void publicMethods() throws Exception {
    // Catch-all test to find API-breaking changes.
    assertNotNull(Request.class.getConstructor(int.class, String.class,
            Response.ErrorListener.class));

    assertNotNull(Request.class.getMethod("getMethod"));
    assertNotNull(Request.class.getMethod("setTag", Object.class));
    assertNotNull(Request.class.getMethod("getTag"));
    assertNotNull(Request.class.getMethod("getErrorListener"));
    assertNotNull(Request.class.getMethod("getTrafficStatsTag"));
    assertNotNull(Request.class.getMethod("setRetryPolicy", RetryPolicy.class));
    assertNotNull(Request.class.getMethod("addMarker", String.class));
    assertNotNull(Request.class.getDeclaredMethod("finish", String.class));
    assertNotNull(Request.class.getMethod("setRequestQueue", RequestQueue.class));
    assertNotNull(Request.class.getMethod("setSequence", int.class));
    assertNotNull(Request.class.getMethod("getSequence"));
    assertNotNull(Request.class.getMethod("getUrl"));
    assertNotNull(Request.class.getMethod("getCacheKey"));
    assertNotNull(Request.class.getMethod("setCacheEntry", Cache.Entry.class));
    assertNotNull(Request.class.getMethod("getCacheEntry"));
    assertNotNull(Request.class.getMethod("cancel"));
    assertNotNull(Request.class.getMethod("isCanceled"));
    assertNotNull(Request.class.getMethod("getHeaders"));
    assertNotNull(Request.class.getDeclaredMethod("getParams"));
    assertNotNull(Request.class.getDeclaredMethod("getParamsEncoding"));
    assertNotNull(Request.class.getMethod("getBodyContentType"));
    assertNotNull(Request.class.getMethod("getBody"));
    assertNotNull(Request.class.getMethod("setShouldCache", boolean.class));
    assertNotNull(Request.class.getMethod("shouldCache"));
    assertNotNull(Request.class.getMethod("getPriority"));
    assertNotNull(Request.class.getMethod("getTimeoutMs"));
    assertNotNull(Request.class.getMethod("getRetryPolicy"));
    assertNotNull(Request.class.getMethod("markDelivered"));
    assertNotNull(Request.class.getMethod("hasHadResponseDelivered"));
    assertNotNull(
            Request.class.getDeclaredMethod("parseNetworkResponse", NetworkResponse.class));
    assertNotNull(Request.class.getDeclaredMethod("parseNetworkError", VolleyError.class));
    assertNotNull(Request.class.getDeclaredMethod("deliverResponse", Object.class));
    assertNotNull(Request.class.getMethod("deliverError", VolleyError.class));
}
 
Example 19
Source Project: odyssey   Source File: MusicBrainzProvider.java    License: 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 20
/**
 * Revoke token.
 */
public void revoke() {
    String TokenEndpoint = user.getTokenEndpoint();

    StringRequest getRequest = new StringRequest(Request.Method.POST, TokenEndpoint,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) { }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) { }
            }
    )
    {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();

            params.put("action", "revoke");
            params.put("token", user.getAccessToken());

            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(context);
    queue.add(getRequest);
}
 
Example 21
Source Project: elemeimitate   Source File: MenusAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	final ViewHolder viewHolder ;
	if(convertView == null){
		convertView = inflater.inflate(R.layout.item_menu_content, parent, false);
		viewHolder = new ViewHolder();
		viewHolder.iv_image = (ImageView)convertView.findViewById(R.id.item_menu_content_img);
		viewHolder.tv_menusName = (TextView)convertView.findViewById(R.id.item_menu_content_title);
		viewHolder.tv_price = (TextView)convertView.findViewById(R.id.item_menu_content_price);
		
		convertView.setTag(viewHolder);
	}else{
		viewHolder = (ViewHolder)convertView.getTag();
	}

	//创建一个RequestQueue对象
	RequestQueue requestQueue = Volley.newRequestQueue(context);
	     	
    //创建ImageRequest对象
	ImageRequest imageRequest = new ImageRequest(
			Constant.URL_WEB_SERVER+datas.get(position).get("menusImagePath").toString(),//url
	    	new Response.Listener<Bitmap>() {//监听器Listener
				@Override
	    		public void onResponse(Bitmap response) {
	    			viewHolder.iv_image.setImageBitmap(response);
	    		}
	    		//参数3、4表示图片宽高,Bitmap.Config.ARGB_8888表示图片每个像素占据4个字节大小
	    	}, 0, 0, Config.ARGB_8888, new Response.ErrorListener() {//图片加载请求失败的回调Listener
	    			@Override
	    			public void onErrorResponse(VolleyError error) {
	    				viewHolder.iv_image.setImageResource(R.drawable.ic_normal_pic);
	    			}
	    	});
	//将ImageRequest加载到Queue
	 requestQueue.add(imageRequest);
	    
	viewHolder.tv_menusName.setText(datas.get(position).get("menuName").toString());
	viewHolder.tv_price.setText("¥"+datas.get(position).get("total_price").toString());
	return convertView;
}
 
Example 22
Source Project: tgen   Source File: PackageService.java    License: Apache License 2.0 5 votes vote down vote up
public static RpcRequest SaveAcknowledge(final String packageIds, final String subject, final String content, final String level, final Listener<Void> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Package/SaveAcknowledge",
        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() {
            HashMap<String, Object> msg = new HashMap<String, Object>();
            msg.put("packageIds", packageIds);
            msg.put("subject", subject);
            msg.put("content", content);
            msg.put("level", level);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example 23
Source Project: Place-Search-Service   Source File: PlaceSearchFragment.java    License: MIT License 5 votes vote down vote up
private void searchPlaces() {
        dialog.show();
        final StringBuffer buffer = new StringBuffer();
        buffer.append(BaseUrl.SEARCH_URL);
//        buffer.append("http://127.0.0.1:8080/");

        buffer.append("startLng=").append(Longitude);
        buffer.append("&");
        buffer.append("startLat=").append(Latitude);
        buffer.append("&");
        if (!TextUtils.isEmpty(mPlaceSearchDistance.getText())) {
            buffer.append("distance=").append(mPlaceSearchDistance.getText()).append("&");
        } else {
            buffer.append("distance=").append(10).append("&");
        }

        buffer.append("category=").append(formatted_category).append("&keyword=").append(mPlaceSearchKeyWord.getText());
        Log.v("request url",buffer.toString());

        RequestQueue mQueue = Volley.newRequestQueue(context);
        StringRequest request = new StringRequest(Request.Method.GET, buffer.toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                dialog.dismiss();
                PlacesSearchResultObj obj = new Gson().fromJson(response, PlacesSearchResultObj.class);
                Intent intent = new Intent(context, PlacesSearchResultActivtity.class);
                intent.putExtra("data", obj);
                intent.putExtra("url", buffer.toString());
                startActivity(intent);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dialog.dismiss();
                Toast.makeText(getContext(),"No network",Toast.LENGTH_LONG).show();
            }
        });
        mQueue.add(request);
    }
 
Example 24
Source Project: swaggy-jenkins   Source File: PostRequest.java    License: MIT License 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
  String parsed;
  try {
    parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  } catch (UnsupportedEncodingException e) {
    parsed = new String(response.data);
  }
  return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example 25
Source Project: Study_Android_Demo   Source File: MainActivity.java    License: Apache License 2.0 5 votes vote down vote up
public void btnClick1(View view){

        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        tv.setText(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //若联网失败等情况
                //缓存中找
                Cache.Entry entry = queue.getCache().get(url);

                if(entry==null){
                    return;
                }

                byte[] data = entry.data;
                if(data!=null && data.length>0){
                    tv.setText(new String(data,0,data.length));
                }
            }
        });
//        {
//            //若设置Request.Method.POST
//            //post请求传参方式
//            @Override
//            protected Map<String, String> getParams() throws AuthFailureError {
//
//                Map<String,String> map = new HashMap<>();
//                map.put("name","realmo");
//                return map;
//            }
//        };

        queue.add(request);
    }
 
Example 26
Source Project: live-app-android   Source File: HTMobileClient.java    License: MIT License 5 votes vote down vote up
public void updatePublishableKey(@NonNull final Callback callback) {
    if (!isAuthorized()) {
        return;
    }

    Request request = new Request("https://live-api.htprod.hypertrack.com/api-key", new Response.Listener<JsonObject>() {
        @Override
        public void onResponse(JsonObject response) {
            Log.d(TAG, "getPublishableKey onResponse: " + response);
            String hyperTrackPublicKey = response.get("key").getAsString();
            SharedPreferences sharedPreferences = mContext.getSharedPreferences(mContext.getString(R.string.app_name), Context.MODE_PRIVATE);
            sharedPreferences.edit()
                    .putString("pub_key", hyperTrackPublicKey)
                    .putBoolean("is_tracking", true)
                    .apply();

            callback.onSuccess(HTMobileClient.this);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "onErrorResponse: " + error.getMessage());
            callback.onError(error.getMessage(), null);
        }
    });

    request.setShouldCache(false);

    request(request);
}
 
Example 27
Source Project: MagicPrint-ECommerce-App-Android   Source File: RegisterRequest.java    License: MIT License 5 votes vote down vote up
public RegisterRequest(String name, String password, String mobile, String email, String photo, Response.Listener<String> listener) {
    super(Method.POST, REGISTER_URL, listener, null);
    parameters = new HashMap<>();
    parameters.put("name", name);
    parameters.put("password", password);
    parameters.put("mobile", mobile);
    parameters.put("email", email);
    parameters.put("image", photo);

}
 
Example 28
Source Project: MagicPrint-ECommerce-App-Android   Source File: UpdateRequest.java    License: MIT License 5 votes vote down vote up
public UpdateRequest(String name, String mobile, String email, String newemail, Response.Listener<String> listener) {
    super(Method.POST, REGISTER_URL, listener, null);
    parameters = new HashMap<>();
    parameters.put("name", name);
    parameters.put("newemail", newemail);
    parameters.put("mobile", mobile);
    parameters.put("email", email);

}
 
Example 29
Source Project: openapi-generator   Source File: PostRequest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
  String parsed;
  try {
    parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  } catch (UnsupportedEncodingException e) {
    parsed = new String(response.data);
  }
  return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
 
Example 30
Source Project: TouchNews   Source File: NetRequestUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * get请求获取JsonObject 带Headers参数
     *
     * @param url      url
     * @param param    param
     * @param listener callback
     */
    public void getJsonWithHeaders(String url, final Map<String, String> param, final Map<String, String> headers, final RequestListener listener) {
        url += prepareParam(param);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.onResponse(response);
//                                Log.i ( TAG, response.toString ( ) );
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.onError(error);
//                                Log.i ( TAG, error.getMessage ( ), error );
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers == null) {
                    return super.getHeaders();
                } else {
                    return headers;
                }

            }

        };
        mRequestQueue.add(jsonObjectRequest);

    }