Java Code Examples for com.android.volley.RequestQueue#add()

The following examples show how to use com.android.volley.RequestQueue#add() . 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: LocalSearch.java    From MapsSDK-Native with 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 2
Source File: RVNetwork.java    From RestVolley with 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 3
Source File: WeatherProxy.java    From MaterialCalendar with Apache License 2.0 6 votes vote down vote up
public static void fetchWeatherContent(String dateParam) {
    StringRequest stringRequest = new StringRequest(Method.GET, WE, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                Logger.json(response);
                JSONObject result = new JSONObject(response);
                insertWeather(result);
            } catch (JSONException e) {
                Logger.d(e.getMessage());
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            /* TODO Auto-generated method stub */

        }
    });

    RequestQueue requestQueue = RQManager.getInstance().getRequestQueue();
    requestQueue.add(stringRequest);
    requestQueue.start();
}
 
Example 4
Source File: TabsGsonLoader.java    From android_tv_metro with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadDataByGson() {
    RequestQueue requestQueue = VolleyHelper.getInstance(getContext().getApplicationContext()).getAPIRequestQueue();
    GsonRequest<GenericSubjectItem<DisplayItem>> gsonRequest = new GsonRequest<GenericSubjectItem<DisplayItem>>(calledURL, new TypeToken<GenericSubjectItem<DisplayItem>>(){}.getType(), null, listener, errorListener);

    gsonRequest.setCacheNeed(getContext().getCacheDir() + "/" + cacheFileName);
    requestQueue.add(gsonRequest);
}
 
Example 5
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 6
Source File: VolleyClient.java    From EasyPay with Apache License 2.0 5 votes vote down vote up
@Override
public void post(final PayParams payParams, final CallBack c) {
    RequestQueue queue = Volley.newRequestQueue(payParams.getActivity());
    StringRequest request = new StringRequest(Request.Method.POST, payParams.getApiUrl(),
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    c.onSuccess(response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            c.onFailure();
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("pay_way", payParams.getPayWay().toString());
            params.put("price", String.valueOf(payParams.getGoodsPrice()));
            params.put("goods_name", payParams.getGoodsName());
            params.put("goods_introduction", payParams.getGoodsIntroduction());

            return params;
        }
    };

    queue.add(request);
}
 
Example 7
Source File: HaikuClient.java    From gplus-haiku-client-android with Apache License 2.0 5 votes vote down vote up
/**
 * Add a vote for a haiku. Requires that the user is authenticated.
 *
 * @param haiku the haiku to vote for.
 * @param listener and object to call when the request is complete.
 */
public void writeHaikuVote(final Haiku haiku, final HaikuServiceListener listener) {
    String path = VOTE_HAIKU.replace("{haiku_id}", haiku.id);
    RequestQueue rq = mVolley.getRequestQueue();
    HaikuApiRequest<Haiku> haikuPost = new HaikuApiRequest<Haiku>(
            (new TypeToken<Haiku>() {
            }),
            Request.Method.POST,
            Constants.SERVER_URL + path,
            new Response.Listener<Haiku>() {
                @Override
                public void onResponse(Haiku data) {
                    listener.onVoteWritten(data);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.d(TAG, "Write Haiku error: " + volleyError.getMessage());
                    if (listener != null) {
                        listener.onVoteWritten(haiku);
                    }
                }
            },
            true
    );
    haikuPost.setSession(mHaikuSession);
    haikuPost.setTag(POST_HAIKU);
    rq.add(haikuPost);
}
 
Example 8
Source File: WebServiceCoordinator.java    From opentok-android-sdk-samples with MIT License 5 votes vote down vote up
public void fetchSessionConnectionData(String sessionInfoUrlEndpoint) {

        RequestQueue reqQueue = Volley.newRequestQueue(context);
        reqQueue.add(new JsonObjectRequest(Request.Method.GET, sessionInfoUrlEndpoint,
                                            null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    String apiKey = response.getString("apiKey");
                    String sessionId = response.getString("sessionId");
                    String token = response.getString("token");

                    Log.i(LOG_TAG, "WebServiceCoordinator returned session information");

                    delegate.onSessionConnectionDataReady(apiKey, sessionId, token);

                } catch (JSONException e) {
                    delegate.onWebServiceCoordinatorError(e);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                delegate.onWebServiceCoordinatorError(error);
            }
        }));
    }
 
Example 9
Source File: ChatWindowView.java    From chat-window-android with MIT License 5 votes vote down vote up
/**
 * Checks the configuration and initializes ChatWindow, loading the view.
 */
public void initialize() {
    checkConfiguration();
    initialized = true;
    RequestQueue queue = Volley.newRequestQueue(getContext());
    JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.GET, "https://cdn.livechatinc.com/app/mobile/urls.json",
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("ChatWindowView", "Response: " + response);
                    String chatUrl = constructChatUrl(response);
                    initialized = true;
                    if (chatUrl != null && getContext() != null) {
                        webView.loadUrl(chatUrl);
                        webView.setVisibility(VISIBLE);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("ChatWindowView", "Error response: " + error);
                    initialized = false;
                    final int errorCode = error.networkResponse != null ? error.networkResponse.statusCode : -1;
                    final boolean errorHandled = chatWindowListener != null && chatWindowListener.onError(ChatWindowErrorType.InitialConfiguration, errorCode, error.getMessage());
                    if (getContext() != null) {
                        onErrorDetected(errorHandled, ChatWindowErrorType.InitialConfiguration, errorCode, error.getMessage());
                    }
                }
            });
    queue.add(stringRequest);
}
 
Example 10
Source File: HTTPRequest.java    From indigenous-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Do a Volley String POST Request.
 *
 * @param endpoint
 *   The endpoint to query.
 * @param params
 *   The params to send.
 */
public void doPostRequest(String endpoint, final Map<String, String> params) {
    StringRequest getRequest = new StringRequest(Request.Method.POST, endpoint,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (volleyRequestListener != null) {
                        volleyRequestListener.OnSuccessRequest(response);
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (volleyRequestListener != null) {
                        volleyRequestListener.OnFailureRequest(error);
                    }
                }
            }
    )
    {

        @Override
        protected Map<String, String> getParams() {
            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 11
Source File: GoProAction.java    From android-wear-GoPro-Remote with Apache License 2.0 5 votes vote down vote up
public static void fireGoProCommand(final String type, final String command,
        final boolean isBacpacRequest, final String password, RequestQueue queue) {

    final GoProRequest goProRequest = new GoProRequest(password, type, command,
            isBacpacRequest,
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(final VolleyError volleyError) {
                    Log.v(TAG, volleyError.toString());
                }
            }
    );
    queue.add(goProRequest);
}
 
Example 12
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 13
Source File: ManageFeedsActivity.java    From indigenous-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get feeds in channel.
 */
public void getFeeds() {

    if (!Utility.hasConnection(getApplicationContext())) {
        showRefreshMessage = false;
        checkRefreshingStatus();
        Snackbar.make(layout, getString(R.string.no_connection), Snackbar.LENGTH_SHORT).show();
        noConnection.setVisibility(View.VISIBLE);
        return;
    }

    String MicrosubEndpoint = user.getMicrosubEndpoint();
    MicrosubEndpoint += "?action=follow&channel=" + channelId;

    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

    StringRequest getRequest = new StringRequest(Request.Method.GET, MicrosubEndpoint,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

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

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

                        adapter.notifyDataSetChanged();
                    }
                    catch (JSONException e) {
                        showRefreshMessage = false;
                        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();

                    }

                    checkRefreshingStatus();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    showRefreshMessage = false;
                    Snackbar.make(layout, getString(R.string.no_feeds_found), Snackbar.LENGTH_SHORT).show();
                    checkRefreshingStatus();
                }
            }
    )
    {
        @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;
        }

    };

    getRequest.setRetryPolicy(new DefaultRetryPolicy(
            0,
            -1,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(getRequest);

}
 
Example 14
Source File: GsonRequest.java    From cnode-android with MIT License 4 votes vote down vote up
public void enqueue(RequestQueue queue) {
    queue.add(this);
}
 
Example 15
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 16
Source File: PushNotificationActivity.java    From indigenous-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Registers the Pushy device token to backend.
 *
 * @param deviceToken
 *   The Pushy device token.
 */
public void storePushyMeTokenOnBackend(final String deviceToken) {

    // Do not run this in case there's no endpoint.
    //noinspection ConstantConditions
    if (BuildConfig.SITE_DEVICE_REGISTRATION_ENDPOINT.length() == 0 || BuildConfig.SITE_ACCOUNT_CHECK_ENDPOINT.length() == 0) {
        return;
    }

    StringRequest getRequest = new StringRequest(Request.Method.POST, BuildConfig.SITE_DEVICE_REGISTRATION_ENDPOINT,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    enablePushyMe();
                    Snackbar.make(layout, getString(R.string.indigenous_registration_success), Snackbar.LENGTH_SHORT).show();

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String message = "unknown error";
                    int code = error.networkResponse.statusCode;
                    switch (code) {
                        case 404:
                            message = getString(R.string.indigenous_account_not_found);
                            break;
                        case 400:
                            message = getString(R.string.indigenous_account_blocked);
                            break;
                    }
                    Snackbar.make(layout, String.format(getString(R.string.indigenous_device_store_error), message), Snackbar.LENGTH_LONG).show();
                }
            }
    )
    {

        @Override
        protected Map<String, String> getParams() {
            User user = new Accounts(getApplicationContext()).getDefaultUser();
            Map<String, String> params = new HashMap<>();
            params.put("url", user.getMe());
            params.put("apiToken", siteApiToken.getText().toString());
            params.put("deviceToken", deviceToken);
            return params;
        }

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

    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    queue.add(getRequest);
}
 
Example 17
Source File: VolleyHttpRequest.java    From privacy-friendly-weather with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @see IHttpRequest#make(String, HttpRequestType, IProcessHttpRequest)
 */
@Override
public void make(String URL, HttpRequestType method, final IProcessHttpRequest requestProcessor) {
    RequestQueue queue = Volley.newRequestQueue(context, new HurlStack(null, getSocketFactory()));

    // Set the request method
    int requestMethod;
    switch (method) {
        case POST:
            requestMethod = Request.Method.POST;
            break;
        case GET:
            requestMethod = Request.Method.GET;
            break;
        case PUT:
            requestMethod = Request.Method.PUT;
            break;
        case DELETE:
            requestMethod = Request.Method.DELETE;
            break;
        default:
            requestMethod = Request.Method.GET;
    }

    // Execute the request and handle the response
    StringRequest stringRequest = new StringRequest(requestMethod, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    requestProcessor.processSuccessScenario(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    requestProcessor.processFailScenario(error);
                }
            }
    );

    queue.add(stringRequest);
}
 
Example 18
Source File: HomeFragment.java    From QuickNews with MIT License 4 votes vote down vote up
public void showNews(int position, RequestQueue requestQueue, ListView listView,
                     SwipeRefreshLayout refreshLayout) {
    String url = null;
    if (position == 4) {//段子的内容与其他不一样,单独处理
        url = "http://toutiao.com/api/article/recent/" +
                "?source=2&category=essay_joke&as=A1B5276908B3CCE";
        requestQueue.add(getJokeData(url, "", listView, refreshLayout));
        mNewsType = 3;
    } else {
        switch (position) {
            case 0:
                url = "http://toutiao.com/api/article/recent/" +
                        "?source=2&category=__all__&as=A105177907376A5";
                break;
            case 1:
                url = "http://toutiao.com/api/article/recent/" +
                        "?source=2&category=news_hot&as=A1B5C75918C3A2C";
                break;
            case 2:
                url = "http://toutiao.com/api/article/recent/" +
                        "?source=2&category=video&as=A195A71998C3BBD";
                break;
            case 3://社会
                url = "http://toutiao.com/api/article/recent/" +
                        "?source=2&category=news_society&as=A145F7D98893D5A";
                break;
            case 6://yule
                url = "http://toutiao.com/api/article/recent/" +
                        "?source=2&category=news_entertainment&as=A1C507392893DCD&";
                break;
            case 5://图片
                url = "http://toutiao.com/api/article/recent/" +
                        "?source=2&count=20&category=gallery_detail&max_behot_time=" +
                        "1469594722.33&utm_source=toutiao&device_platform=web" +
                        "&offset=0&as=A1D5C7D9E873C62";
                break;
            case 7:
                url = "http://toutiao.com/api/article/recent/" +
                        "?source=2&category=news_tech&as=A1B5373998E3FCB";
                break;


        }
        mNewsType = 1;
        requestQueue.add(getNewsData(url, "", listView, refreshLayout));
    }
}
 
Example 19
Source File: UpdatingUtil.java    From BaldPhone with Apache License 2.0 4 votes vote down vote up
public static void checkForUpdates(BaldActivity activity, boolean retAnswer) {
    if (!UpdatingUtil.isOnline(activity) && retAnswer) {
        BaldToast.from(activity)
                .setType(BaldToast.TYPE_ERROR)
                .setText(R.string.could_not_connect_to_server)
                .setLength(1)
                .show();
        return;
    }
    final RequestQueue queue = Volley.newRequestQueue(activity);
    final Lifecycle lifecycle = activity.getLifecycle();
    final LifecycleObserver observer = new LifecycleObserver() {
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        public void releaseRequest() {
            queue.cancelAll(VOLLEY_TAG);
            lifecycle.removeObserver(this);
        }
    };
    queue.add(
            new StringRequest(
                    Request.Method.GET,
                    MESSAGE_URL,
                    response -> {
                        try {
                            final BaldUpdateObject baldUpdateObject = BaldUpdateObject.parseMessage(response);
                            if (updatePending(baldUpdateObject)) {
                                BDB.from(activity)
                                        .setTitle(R.string.pending_update)
                                        .setSubText(R.string.a_new_update_is_available)
                                        .addFlag(BDialog.FLAG_OK | BDialog.FLAG_CANCEL)
                                        .setPositiveButtonListener(params -> {
                                            activity.startActivity(
                                                    new Intent(activity, UpdatesActivity.class)
                                                            .putExtra(UpdatesActivity.EXTRA_BALD_UPDATE_OBJECT, baldUpdateObject));
                                            return true;
                                        })
                                        .setNegativeButtonListener(params -> {
                                            BPrefs.get(activity)
                                                    .edit()
                                                    .putLong(BPrefs.LAST_UPDATE_ASKED_VERSION_KEY, System.currentTimeMillis())
                                                    .apply();
                                            return true;
                                        })
                                        .show();
                            } else {
                                if (retAnswer)
                                    BaldToast
                                            .from(activity)
                                            .setText(R.string.baldphone_is_up_to_date)
                                            .show();
                            }
                        } catch (JSONException e) {
                            if (retAnswer) {
                                BaldToast.from(activity).setType(BaldToast.TYPE_ERROR).setText(R.string.update_message_is_corrupted).show();
                                BaldToast.from(activity).setType(BaldToast.TYPE_ERROR).setText(S.str(e.getMessage())).show();
                            }
                        }
                        lifecycle.removeObserver(observer);
                    },
                    error -> {
                        if (retAnswer)
                            BaldToast.from(activity)
                                    .setLength(1)
                                    .setType(BaldToast.TYPE_ERROR)
                                    .setText(R.string.could_not_connect_to_server)
                                    .show();
                        lifecycle.removeObserver(observer);
                    }
            ).setTag(VOLLEY_TAG));
    lifecycle.addObserver(observer);
}
 
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);


    }