Java Code Examples for com.android.volley.VolleyError

The following examples show how to use com.android.volley.VolleyError. 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: RestVolley   Author: HujiangTechnology   File: RVNetwork.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to prepare the request for a retry. If there are no more attempts remaining in the
 * request's retry policy, a timeout exception is thrown.
 * @param request The request to use.
 */
protected static void attemptRetryOnException(String logPrefix, Request<?> request, VolleyError exception) throws VolleyError {
    RetryPolicy retryPolicy = request.getRetryPolicy();
    int oldTimeout = request.getTimeoutMs();

    try {
        retryPolicy.retry(exception);
    } catch (VolleyError e) {
        request.addMarker(String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
        throw e;
    }
    request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));

    //reentry the requestQueue
    RequestQueue requestQueue = getRequestQueue(request);
    if (requestQueue != null) {
        requestQueue.add(request);
    }

    throw new RetryError();
}
 
Example #2
Source Project: MapsSDK-Native   Author: microsoft   File: LocalSearch.java    License: MIT License 6 votes vote down vote up
static void sendRequest(Context context, String query, GeoboundingBox bounds, Callback callback) {
    if (query == null || query.isEmpty()) {
        Toast.makeText(context, "Invalid query", Toast.LENGTH_LONG).show();
        return;
    }

    String boundsStr = String.format(Locale.ROOT,
        "%.6f,%.6f,%.6f,%.6f",
        bounds.getSouth(), bounds.getWest(), bounds.getNorth(), bounds.getEast());

    RequestQueue queue = Volley.newRequestQueue(context);
    queue.add(new StringRequest(
        Request.Method.GET,
        URL_ENDPOINT.replace("{query}", query).replace("{bounds}", boundsStr),
        (String response) -> {
            List<Poi> results = parse(response);
            if (results == null || results.isEmpty()) {
                callback.onFailure();
                return;
            }
            callback.onSuccess(results);
        },
        (VolleyError error) -> callback.onFailure()
    ));
}
 
Example #3
Source Project: meizhi   Author: xingrz   File: GalleryActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onRefresh() {
    refresh.setRefreshing(true);
    new GalleryRequest() {
        @Override
        protected void deliverResponse(List<Album> response) {
            Log.d(TAG, "total: " + response.size());
            refresh.setRefreshing(false);
            adapter.setList(response);
            application.getGalleryCache().addAll(response);
        }

        @Override
        public void deliverError(VolleyError error) {
            refresh.setRefreshing(false);
            Log.e(TAG, "error", error);
        }
    }.enqueue(application.getRequestQueue());
}
 
Example #4
Source Project: JianDan   Author: ZhaoKaiQiang   File: PictureAdapter.java    License: Apache License 2.0 6 votes vote down vote up
private void loadData() {

        RequestManager.addRequest(new Request4Picture(Picture.getRequestUrl(mType, page),
                new Response.Listener<ArrayList<Picture>>
                        () {
                    @Override
                    public void onResponse(ArrayList<Picture> response) {
                        getCommentCounts(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mLoadResultCallBack.onError(LoadResultCallBack.ERROR_NET, error.getMessage());
                mLoadFinisCallBack.loadFinish(null);
            }
        }), mActivity);
    }
 
Example #5
Source Project: android-kubernetes-blockchain   Author: IBM   File: LeaderboardsFragment.java    License: Apache License 2.0 6 votes vote down vote up
public void getUserFromMongo(String userId) {
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, BACKEND_URL + "/registerees/info/" + userId , null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    UserInfoModel userInfoModel = gson.fromJson(response.toString(), UserInfoModel.class);

                    userStats.setText(String.format("%s steps", String.valueOf(userInfoModel.getSteps())));
                    getUserPosition(String.valueOf(userInfoModel.getSteps()));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "That didn't work!");
        }
    });
    queue.add(jsonObjectRequest);
}
 
Example #6
Source Project: TouchNews   Author: cchao1024   File: ChatPresenter.java    License: Apache License 2.0 6 votes vote down vote up
private void onRequestMessage(String message) {
            /*“key”: “APIKEY”,
            “info”: “今天天气怎么样”,
            “loc”:“北京市中关村”,
            “userid”:“12345678”*/

    param.put(Keys.INFO, EncodeString(message));
    param.put("userid", "12345678");
    NetRequestUtil.getInstance().getJson(UrlUtil.URL_CHAT, param, new NetRequestUtil.RequestListener() {
        @Override
        public void onResponse(JSONObject response) {
            LogUtils.i(response);
            try {
                if (response.getString("code").equals("100000")) {
                    mView.onReceiveRespond(response.getString("text"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(VolleyError error) {
        }
    });
}
 
Example #7
Source Project: JianDan_OkHttpWithVolley   Author: ZhaoKaiQiang   File: Request4PushFreshComment.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Response<Boolean> parseNetworkResponse(NetworkResponse response) {

	try {
		String resultStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

		JSONObject resultObj = new JSONObject(resultStr);
		String result = resultObj.optString("status");
		String error=resultObj.optString("error");
		if ( result.equals("ok")) {
			return Response.success(true, HttpHeaderParser.parseCacheHeaders(response));
		} else {
			return Response.error(new VolleyError("错误原因:" + error));
		}
	} catch (Exception e) {
		e.printStackTrace();
		return Response.error(new VolleyError(e));
	}

}
 
Example #8
Source Project: catnut   Author: longkai   File: ComposeTweetActivity.java    License: MIT License 6 votes vote down vote up
private void injectListener() {
	listener = new Response.Listener<JSONObject>() {
		@Override
		public void onResponse(JSONObject response) {
			// delete posted text and thumbs
			mText.setText(null);
			if (mUris != null) {
				mUris.clear();
				mAdapter.notifyDataSetChanged();
			}
			Toast.makeText(ComposeTweetActivity.this, R.string.post_success, Toast.LENGTH_SHORT).show();
		}
	};
	errorListener = new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			Log.e(TAG, "post tweet error!", error);
			WeiboAPIError weiboAPIError = WeiboAPIError.fromVolleyError(error);
			Toast.makeText(ComposeTweetActivity.this, weiboAPIError.error, Toast.LENGTH_LONG).show();
		}
	};
	mCustomizedBar.findViewById(R.id.action_geo).setOnClickListener(this);
	mCustomizedBar.findViewById(R.id.action_send).setOnClickListener(this);
	mLocationMarker.setOnClickListener(this);
}
 
Example #9
Source Project: volley   Author: google   File: ImageLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The default implementation of ImageListener which handles basic functionality of showing a
 * default image until the network response is received, at which point it will switch to either
 * the actual image or the error image.
 *
 * @param view The imageView that the listener is associated with.
 * @param defaultImageResId Default image resource ID to use, or 0 if it doesn't exist.
 * @param errorImageResId Error image resource ID to use, or 0 if it doesn't exist.
 */
public static ImageListener getImageListener(
        final ImageView view, final int defaultImageResId, final int errorImageResId) {
    return new ImageListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (errorImageResId != 0) {
                view.setImageResource(errorImageResId);
            }
        }

        @Override
        public void onResponse(ImageContainer response, boolean isImmediate) {
            if (response.getBitmap() != null) {
                view.setImageBitmap(response.getBitmap());
            } else if (defaultImageResId != 0) {
                view.setImageResource(defaultImageResId);
            }
        }
    };
}
 
Example #10
Source Project: volley   Author: google   File: ImageLoader.java    License: Apache License 2.0 6 votes vote down vote up
protected Request<Bitmap> makeImageRequest(
        String requestUrl,
        int maxWidth,
        int maxHeight,
        ScaleType scaleType,
        final String cacheKey) {
    return new ImageRequest(
            requestUrl,
            new Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap response) {
                    onGetImageSuccess(cacheKey, response);
                }
            },
            maxWidth,
            maxHeight,
            scaleType,
            Config.RGB_565,
            new ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    onGetImageError(cacheKey, error);
                }
            });
}
 
Example #11
Source Project: product-emm   Author: wso2-attic   File: BasicNetworkTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #12
Source Project: volley   Author: google   File: BasicNetworkTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void noConnectionNoRetry() throws Exception {
    MockHttpStack mockHttpStack = new MockHttpStack();
    mockHttpStack.setExceptionToThrow(new IOException());
    BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
    Request<String> request = buildRequest();
    request.setRetryPolicy(mMockRetryPolicy);
    request.setShouldRetryConnectionErrors(false);
    doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
    try {
        httpNetwork.performRequest(request);
    } catch (VolleyError e) {
        // expected
    }
    // should not retry when there is no connection
    verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
}
 
Example #13
Source Project: allenglish   Author: veeson   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 #14
Source Project: product-emm   Author: wso2-attic   File: BasicNetworkTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        BasicHttpResponse fakeResponse =
                new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, "");
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #15
Source Project: volley   Author: google   File: BasicNetworkTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void serverError_disableRetries() throws Exception {
    for (int i = 500; i <= 599; i++) {
        MockHttpStack mockHttpStack = new MockHttpStack();
        HttpResponse fakeResponse = new HttpResponse(i, Collections.<Header>emptyList());
        mockHttpStack.setResponseToReturn(fakeResponse);
        BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack);
        Request<String> request = buildRequest();
        request.setRetryPolicy(mMockRetryPolicy);
        doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class));
        try {
            httpNetwork.performRequest(request);
        } catch (VolleyError e) {
            // expected
        }
        // should not retry any 500 error w/ HTTP 500 retries turned off (the default).
        verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
        reset(mMockRetryPolicy);
    }
}
 
Example #16
Source Project: CrossBow   Author: patrick-doyle   File: CrossbowImage.java    License: Apache License 2.0 6 votes vote down vote up
private void loadImage(ImageView imageView, int drawableID, String file, String url, int width, int height) {
    if(pendingImage != null) {
        pendingImage.cancel();
    }

    pendingImage = new PendingImage();

    if(url != null && file == null && drawableID == DEFAULT) {
        pendingImage.imageContainer = imageLoader.get(url, this, width, height, scaleType);
    }
    else if(url == null && file != null && drawableID == DEFAULT) {
        pendingImage.fileImageContainer = fileImageLoader.get(file, width, height, this);
    }
    else if(url == null && file == null && drawableID != DEFAULT) {
        ScaleTypeDrawable defaultScale = new ScaleTypeDrawable(defaultDrawable, this.preScaleType);
        imageView.setImageDrawable(defaultScale);
    }
    else {
        onErrorResponse(new VolleyError("No image source defined"));
    }
}
 
Example #17
Source Project: tgen   Author: ezbuy   File: PaymentService.java    License: Apache License 2.0 5 votes vote down vote up
public static RpcRequest GetPrepayBalance(final Listener<Double> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(),
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Double result;
                    result = BaseModule.fromJSON(response, Double.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<>();

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

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example #18
Source Project: android_volley_examples   Author: ogrebgr   File: Act_Params.java    License: Apache License 2.0 5 votes vote down vote up
private Response.ErrorListener createMyReqErrorListener() {
    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTvResult.setText(error.getMessage());
        }
    };
}
 
Example #19
Source Project: m2x-android   Author: attm2x   File: JsonRequest.java    License: MIT License 5 votes vote down vote up
private static void handleError(Context context, ResponseListener listener,
                                int requestCode, VolleyError error) {
    ApiV2Response apiResponse = new ApiV2Response();
    apiResponse.set_json(null);
    if(error.networkResponse!=null)
        apiResponse.set_status(String.valueOf(error.networkResponse.statusCode));

    if(error.networkResponse!=null && error.networkResponse.data!=null){
        try {
            apiResponse.set_raw(new String(error.networkResponse.data,"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    if(error.networkResponse!=null && error.networkResponse.statusCode<500){
        apiResponse.set_clientError(Boolean.TRUE);
        apiResponse.set_serverError(Boolean.FALSE);
    }else{
        apiResponse.set_clientError(Boolean.FALSE);
        apiResponse.set_serverError(Boolean.TRUE);
    }
    apiResponse.set_error(Boolean.TRUE);
    apiResponse.set_success(Boolean.FALSE);

    //Save response
    APISharedPreferences.saveLastResponse(context,apiResponse);
    listener.onRequestError(apiResponse,requestCode);
}
 
Example #20
Source Project: tgen   Author: ezbuy   File: OrderService.java    License: Apache License 2.0 5 votes vote down vote up
public static RpcRequest UpdateOrder(final int orderId, final int shipmentTypeId, final String warehouseCode, final double internalShipmentFee, final boolean insured, final String productRemark, 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(shipmentTypeId);
            params.add(warehouseCode);
            params.add(internalShipmentFee);
            params.add(insured);
            params.add(productRemark);

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

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example #21
Source Project: api-android-java   Author: igdb   File: PagesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testSinglePages() throws InterruptedException {
    setUp();
    Parameters parameters = new Parameters()
            .addIds("5");

    final CountDownLatch lock = new CountDownLatch(1);
    wrapper.pages(parameters, new OnSuccessCallback() {
        @Override
        public void onSuccess(JSONArray result) {
            try {
                lock.countDown();
                JSONObject object = result.getJSONObject(0);
                int testId = object.getInt("id");
                assertEquals(5, testId);
            } catch (JSONException e) {
                e.printStackTrace();
                fail("JSONException!!");
            }
        }

        @Override
        public void onError(VolleyError error) {
            fail("Volley Error!!");
        }
    });
    lock.await(20000, TimeUnit.MILLISECONDS);

}
 
Example #22
Source Project: CrossBow   Author: patrick-doyle   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to prepare the request for a retry. If there are no more attempts remaining in the
 * request's retry policy, a timeout exception is thrown.
 * @param request The request to use.
 */
private static void attemptRetryOnException(String logPrefix, Request<?> request,
        VolleyError exception) throws VolleyError {
    RetryPolicy retryPolicy = request.getRetryPolicy();
    int oldTimeout = request.getTimeoutMs();

    try {
        retryPolicy.retry(exception);
    } catch (VolleyError e) {
        request.addMarker(
                String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
        throw e;
    }
    request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));
}
 
Example #23
Source Project: school_shop   Author: Owater   File: ChooseSchoolActivity.java    License: MIT License 5 votes vote down vote up
private void initSchoolList(String url) {
	jsonData = null;
	stringRequest = new StringRequest(url, 
			new Response.Listener<String>() {

				@Override
				public void onResponse(String response) {
					jsonData=response;
					parseJson();
					loadingLayout.setVisibility(View.GONE);
				}

			}, new Response.ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					showToastError(error.toString());
					loadingLayout.setVisibility(View.GONE);
				}
			});
	stringRequest.setTag(stringRequestTag);
	requestQueue.add(stringRequest);
}
 
Example #24
Source Project: api-android-java   Author: igdb   File: WrapperTests.java    License: MIT License 5 votes vote down vote up
@Test
public void gameModes() throws Exception {
    setUp();
    Map<APIWrapper.Operator, String> args = new HashMap<>();
    args.put(APIWrapper.Operator.IDS, "5");

    final CountDownLatch lock = new CountDownLatch(1);
    wrapper.gameModes(args, new onSuccessCallback() {
        @Override
        public void onSuccess(JSONArray result) {
            JSONObject jo;
            try {
                lock.countDown();
                jo = result.getJSONObject(0);
                String s = jo.getString("name");
                assertThat(s, is("Massively Multiplayer Online (MMO)"));
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onError(VolleyError error) {

        }
    });
    lock.await(20000, TimeUnit.MILLISECONDS);

}
 
Example #25
Source Project: api-android-java   Author: igdb   File: PeopleTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testPeopleMultiAndSingle() throws InterruptedException {
    setUp();
    Parameters parameters = new Parameters()
            .addSearch("gabe newell")
            .addFields("name");

    final CountDownLatch lock = new CountDownLatch(1);
    wrapper.search(Endpoint.PEOPLE, parameters, new OnSuccessCallback() {
        @Override
        public void onSuccess(JSONArray result) {
            try {
                lock.countDown();
                JSONObject object1 = result.getJSONObject(0);

                assertEquals(108558, object1.getInt("id"));
                assertEquals("Gabe Newell", object1.getString("name"));

            } catch (JSONException e) {
                e.printStackTrace();
                fail("JSONException!!");
            }
        }

        @Override
        public void onError(VolleyError error) {
            fail("Volley Error!!");
        }
    });
    lock.await(20000, TimeUnit.MILLISECONDS);

}
 
Example #26
Source Project: api-android-java   Author: igdb   File: PulseSourcesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testSinglePulseSources() throws InterruptedException {
    setUp();
    Parameters parameters = new Parameters()
            .addIds("2");

    final CountDownLatch lock = new CountDownLatch(1);
    wrapper.pulseSources(parameters, new OnSuccessCallback() {
        @Override
        public void onSuccess(JSONArray result) {
            try {
                lock.countDown();
                JSONObject object = result.getJSONObject(0);
                int testId = object.getInt("id");
                assertEquals(2, testId);
            } catch (JSONException e) {
                e.printStackTrace();
                fail("JSONException!!");
            }
        }

        @Override
        public void onError(VolleyError error) {
            fail("Volley Error!!");
        }
    });
    lock.await(20000, TimeUnit.MILLISECONDS);

}
 
Example #27
Source Project: CrossBow   Author: patrick-doyle   File: CrossbowImage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onPreDraw() {

    ImageView view = this.imageView.get();
    if (view == null) {
        return true;
    }
    view.getViewTreeObserver().removeOnPreDrawListener(this);

    if (!this.hasSource()) {
        setError(new VolleyError("No image source Is empty"));
        return true;
    }

    if (!this.dontClear) {
        view.setImageBitmap(null);
    }

    if (this.defaultDrawable != null) {
        ScaleTypeDrawable defaultScale = new ScaleTypeDrawable(defaultDrawable, this.preScaleType);
        view.setImageDrawable(defaultScale);
    }

    int width = 0;
    int height = 0;
    if(this.width != DEFAULT && this.height != DEFAULT) {
        //Use provided width and height if provided
        width = this.width;
        height = this.height;
    }
    else if (!this.dontScale) {
        //Use the raw image
        width = view.getWidth();
        height = view.getHeight();
    }
    loadImage(view, this.drawable, this.file, this.url, width, height);

    return true;
}
 
Example #28
Source Project: android-common-utils   Author: LightSun   File: BasicNetwork.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to prepare the request for a retry. If there are no more attempts remaining in the
 * request's retry policy, a timeout exception is thrown.
 * @param request The request to use.
 */
private static void attemptRetryOnException(String logPrefix, Request<?> request,
        VolleyError exception) throws VolleyError {
    RetryPolicy retryPolicy = request.getRetryPolicy();
    int oldTimeout = request.getTimeoutMs();

    try {
        retryPolicy.retry(exception);
    } catch (VolleyError e) {
        request.addMarker(
                String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
        throw e;
    }
    request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));
}
 
Example #29
Source Project: api-android-java   Author: igdb   File: PulsesTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testMultiplePulse() throws InterruptedException {
    setUp();
    Parameters parameters = new Parameters()
            .addIds("25040,25047,25000");

    final CountDownLatch lock = new CountDownLatch(1);
    wrapper.pulses(parameters, new OnSuccessCallback() {
        @Override
        public void onSuccess(JSONArray result) {
            try {
                lock.countDown();
                JSONObject object1 = result.getJSONObject(0);
                JSONObject object2 = result.getJSONObject(1);
                JSONObject object3 = result.getJSONObject(2);

                assertEquals(25040, object1.getInt("id"));
                assertEquals(25047, object2.getInt("id"));
                assertEquals(25000, object3.getInt("id"));

            } catch (JSONException e) {
                e.printStackTrace();
                fail("JSONException!!");
            }
        }

        @Override
        public void onError(VolleyError error) {
            fail("Volley Error!!");
        }
    });
    lock.await(20000, TimeUnit.MILLISECONDS);

}
 
Example #30
Source Project: m2x-android   Author: attm2x   File: JsonRequest.java    License: MIT License 5 votes vote down vote up
private static void makeRequest(final Context context,
                                int method,
                                String url,
                                Map<String, String> params,
                                JSONObject body,
                                final ResponseListener listener,
                                final int requestCode) {

    if(params!=null && !params.isEmpty())
        url = url.concat("?".concat(ArrayUtils.mapToQueryString(params)));
    Log.d("JsonRequest", "body: " + body);
    JsonApiV2Request jsonObjReq = new JsonApiV2Request(
            method,
            url,
            body,
            new Response.Listener<ApiV2Response>() {
                @Override
                public void onResponse(ApiV2Response apiResponse) {
                    handleApiResponse(context, listener, requestCode, apiResponse);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    handleError(context, listener, requestCode, error);
                }
            })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return JsonRequest.getHeaders(context);
        }

    };

    //It's better if the queue is obtained with an app context to keep it alive while the app is in foreground.
    VolleyResourcesSingleton.getInstance(context.getApplicationContext()).addToRequestQueue(jsonObjReq);
}