Ejemplo n.º 1
0
  public void getRideEstimates() {
    MyVolley.init(context);
    RequestQueue queue = MyVolley.getRequestQueue();
    StringRequest myReq =
        new StringRequest(
            Request.Method.GET,
            "https://api.uber.com/v1/estimates/price",
            reqSuccessListenerFoodList(),
            reqErrorListenerFoodList()) {

          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("server_token", "maMItAGDV5HHqKAG3nLfLTlhMOnQscAONF_aeFcu");
            return headers;
          }

          protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();

            params.put("start_latitude", String.valueOf((float) 28.613939));
            params.put("start_longitude", String.valueOf((float) 77.209021));
            params.put("end_latitude", String.valueOf((float) 28.7499));
            params.put("end_longitude", String.valueOf((float) 77.1170));

            return params;
          }
        };
    myReq.setRetryPolicy(new DefaultRetryPolicy(25000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(myReq);
  }
Ejemplo n.º 2
0
  public void btnPostJson(View view) {

    // TODO 提交JSON

    JSONObject json = new JSONObject();

    try {
      json.put("name", "abc");
      json.put("pass", "123");
    } catch (JSONException e) {
      e.printStackTrace();
    }

    JsonObjectRequest request =
        new JsonObjectRequest(
            "http://10.0.175.103:8080/post",
            json,
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                textView.setText("" + response.toString());
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                textView.setText("" + error.getMessage());
              }
            });

    RequestQueue requestQueue = NetworkSingleton.getInstance().getRequestQueue();

    requestQueue.add(request);
  }
Ejemplo n.º 3
0
  public void makeArrayType() {
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            Config.LOGIN_WAMP_URL + "taskmeTipZadatkaCitanje.php",
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                // If we are getting success from server
                List<String> useri = Arrays.asList(response.split(","));
                arrayTask.clear();
                arrayTask.addAll(useri);
                adapter1.notifyDataSetChanged();

                System.out.print("iz respons e" + Arrays.asList(arrayTask));
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                System.out.print("error: " + error.toString());
              }
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            return null;
          }
        };
    // Adding the string request to the queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
  }
Ejemplo n.º 4
0
  /**
   * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
   *
   * @param context A {@link android.content.Context} to use for creating the cache dir.
   * @param stack An {@link HttpStack} to use for the network, or null for default.
   * @return A started {@link RequestQueue} instance.
   */
  public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
      if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
      } else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
        // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
      }
    }

    Network network = new BasicNetwork(stack);

    final DiskBasedCache cache = new DiskBasedCache(cacheDir);
    RequestQueue queue = new RequestQueue(cache, network);
    queue.start();

    return queue;
  }
  /**
   * @Declaration : - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
   * completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError
   * *error))completionHandler @Description : Creates an HTTP request for the specified URL request
   * object, and calls a handler upon completion.
   *
   * @param request An NSURLRequest object that provides the URL, cache policy, request type, body
   *     data or body stream, and so on.
   * @param completionHandler The completion handler to call when the load request is complete. This
   *     handler is executed on the delegate queue. Unless you have provided a custom delegate, this
   *     parameter must not be nil, because there is no other way to retrieve the response data.
   * @return Return Value The new session data task. @Discussion After you create the task, you must
   *     start it by calling its resume method.
   */
  public NSURLSessionDataTask dataTaskWithRequestCompletionHandler(
      NSURLRequest request,
      final PerformBlock.VoidBlockNSDataNSURLResponseNSError completionHandler) {
    RequestQueue queue = Volley.newRequestQueue(GenericMainContext.sharedContext);
    JsonObjectRequest jsonRequest =
        new JsonObjectRequest(
            Request.Method.GET,
            request.URL.getUrlString().getWrappedString(),
            new JSONObject(),
            new Response.Listener<JSONObject>() {

              @Override
              public void onResponse(JSONObject response) {
                try {
                  completionHandler.perform(
                      new NSData(response.toString().getBytes("UTF-8")),
                      new NSURLResponse().initWithJSONResponse(response),
                      new NSError());
                } catch (UnsupportedEncodingException e) {
                  Log.d(NSURLSession.class.getSimpleName(), String.valueOf(e));
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
              }
            });
    queue.add(jsonRequest);

    return new NSURLSessionDataTask(request.URL);
  }
Ejemplo n.º 6
0
  void fetchLatestNews() {
    ConnectivityManager connectivityManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final Context context = this;
    if (connectivityManager.getActiveNetworkInfo().isConnected()) {
      Toast.makeText(this, R.string.info_fetching_news, Toast.LENGTH_SHORT).show();

      RequestQueue requestQueue = Volley.newRequestQueue(this);
      StringRequest request =
          new StringRequest(
              _mashableUrlString,
              new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                  MashableNews mashableNews = new Gson().fromJson(response, MashableNews.class);
                  _dataSet.addAll(mashableNews.newsItems);
                  _recyclerViewAdapter.notifyDataSetChanged();
                }
              },
              new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                  Toast.makeText(
                          context,
                          R.string.error_fetching_news + error.getLocalizedMessage(),
                          Toast.LENGTH_SHORT)
                      .show();
                  Log.e("MainActivity", error.getMessage());
                }
              });
      requestQueue.add(request);
    } else {
      Toast.makeText(this, R.string.no_connection_when_fetching_news, Toast.LENGTH_SHORT).show();
    }
  }
Ejemplo n.º 7
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RequestQueue queue = Volley.newRequestQueue(getActivity());
    // http://www.omdbapi.com/?plot=short&amp;r=json&amp;i=
    String url = getString(R.string.episode_detail_url) + getImDBId();

    final EpisodeBaseActivity baseActivity = (EpisodeBaseActivity) getActivity();
    baseActivity.showLoadingIndicator();

    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            url,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                EpisodeDetails episodeDetails =
                    EpisodeDetailResponseParser.parseEpisodeDetails(response);

                if (episodeDetails != null) {
                  TextView valYear = (TextView) getActivity().findViewById(R.id.valYear);
                  valYear.setText(episodeDetails.getYear());

                  TextView valRated = (TextView) getActivity().findViewById(R.id.valRated);
                  valRated.setText(episodeDetails.getRated());

                  TextView valReleased = (TextView) getActivity().findViewById(R.id.valReleased);
                  valReleased.setText(episodeDetails.getReleasedDate());

                  TextView valSeason = (TextView) getActivity().findViewById(R.id.valSeason);
                  valSeason.setText(episodeDetails.getSeasonNumber());

                  TextView valEpisode = (TextView) getActivity().findViewById(R.id.valEpisode);
                  valEpisode.setText(episodeDetails.getEpisodeNumber());

                  TextView valRuntime = (TextView) getActivity().findViewById(R.id.valRuntime);
                  valRuntime.setText(episodeDetails.getRunDuration());

                  getActivity().setTitle(episodeDetails.getTitle());
                  baseActivity.hideLoadingIndicator();
                } else {
                  baseActivity.showErrorDialog(
                      getString(R.string.errorAlertTitle), getString(R.string.errorMessage));
                  baseActivity.hideLoadingIndicator();
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                baseActivity.hideLoadingIndicator();
                baseActivity.showErrorDialog(
                    getString(R.string.errorAlertTitle), getString(R.string.errorMessage));
              }
            });
    queue.add(stringRequest);
  }
  @Override
  protected Boolean doInBackground(Void... params) {
    HashMap<String, String> hashMap = new HashMap<>();
    hashMap.put("action", status);

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    JsonObjectRequest request =
        new JsonObjectRequest(Request.Method.PATCH, URL, new JSONObject(hashMap), null, null) {
          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("REST-API-TOKEN", pID);
            headers.put("X-HTTP-Method-Override", "PATCH");
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("User-agent", System.getProperty("http.agent"));
            return headers;
          }

          @Override
          protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            System.out.println(response.statusCode);

            success = response.statusCode == 200;

            return super.parseNetworkResponse(response);
          }
        };
    requestQueue.add(request);

    return success;
  }
Ejemplo n.º 9
0
  private void showListIzv(final String uvjet, final String naziv) {
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            Config.LOGIN_WAMP_URL + "taskmeIzvjestajIspisZadatka.php",
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                List<String> klijent = Arrays.asList(response.split(","));

                arrayFinalTasks.addAll(klijent);
                adapter1.notifyDataSetChanged();
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {}
            }) {
          @Override
          protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            System.out.print("UVJET " + uvjet);
            System.out.print("NAZIV  " + naziv);
            params.put("UVJET", uvjet);
            params.put("IME", naziv);
            return params;
          }
        };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    System.out.println("request " + stringRequest);
    requestQueue.add(stringRequest);
  }
Ejemplo n.º 10
0
  private void retrieveCharacters() {

    Characters = new ArrayList<>();
    Response.Listener<JSONArray> successListener =
        new Response.Listener<JSONArray>() {
          @Override
          public void onResponse(JSONArray response) {
            parseJsonObjectToCharacter(response);
          }
        };

    Response.ErrorListener errorListener =
        new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError error) {
            System.out.println(error.getMessage());
          }
        };

    JSONObject request = null;
    String url = "http://walkingdead.rawb.xyz/api/walkingdead/GetCharacters?season=1&episode=1";

    JsonArrayRequest jsObjRequest =
        new JsonArrayRequest(url, request, successListener, errorListener);

    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
    queue.add(jsObjRequest);
  }
  public void UrlRequest() {

    try {
      url =
          BASE_URL
              + PARAM.API_KEY
              + API_KEY
              + PARAM.QUERY
              + URLEncoder.encode(query, "utf-8")
              + PARAM.TARGET
              + TARGET
              + PARAM.START
              + START
              + PARAM.DISPLAY
              + DISPLAY;

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

    Log.d("volley", url);
    RequestQueue queue = MapVolley.getInstance(context).getRequestQueue();

    StringRequest sr =
        new StringRequest(Request.Method.GET, url, successListener(), errorListener());

    queue.add(sr);
  }
Ejemplo n.º 12
0
  public void checkSession() {
    final SharedPreferences sharedPref =
        getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
    final String sessionToken =
        sharedPref.getString(getString(R.string.preference_session_token), null);

    if (sessionToken == null) return;

    // Resposta de sucesso
    Response.Listener<JSONObject> successListener =
        new Response.Listener<JSONObject>() {
          @Override
          public void onResponse(JSONObject responseJson) {
            Log.d(LOG_TAG, "Success");
            Log.d(LOG_TAG, responseJson.toString());
            hideProgressDialog();

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString(getString(R.string.preference_user_object), responseJson.toString());
            editor.commit();

            Intent intent = new Intent(MainActivity.this, DashboardActivity.class);
            startActivity(intent);
            finish();
          }
        };

    // Resposta de erro
    Response.ErrorListener errorListener =
        new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError volleyError) {
            Log.d(LOG_TAG, "Erro");
            Log.d(LOG_TAG, volleyError.toString());
            hideProgressDialog();
          }
        };

    // Envia requisição
    showProgressDialog();

    JsonObjectRequest request =
        new JsonObjectRequest(
            Request.Method.GET, ApiEndpoints.SESSION_INFO, successListener, errorListener) {
          @Override
          public HashMap<String, String> getHeaders() {
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("Authentication-Token", sessionToken);
            return params;
          }
        };
    request.setRetryPolicy(
        new DefaultRetryPolicy(
            ApiEndpoints.TIMEOUT,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    RequestQueue queue = Volley.newRequestQueue(this);
    queue.add(request);
  }
Ejemplo n.º 13
0
  @Override
  public void save(ShoppingCartItemModel model) {
    String url = "";

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    url = AppRetailDaoAbstract.URL_API + ShoppingCartItemModel.SHOPPING_CART_ITEM;

    Map<String, String> params = new HashMap<>();

    params.put("id", model.getId());
    params.put("idShoppingCart", model.getIdShoppingCart());
    params.put("idProduct", model.getIdProduct());
    params.put("status", model.getStatus());
    params.put("amountRequested", model.getAmountPurchased().toString());
    params.put("amountPurchased", model.getAmountPurchased().toString());
    params.put("unitPrice", model.getUnitValue().toString());
    params.put("pictureUrl", model.getPictureUrl());
    params.put("totalItem", model.getTotalItem().toString());

    HelperJsonArrayRequest jsArrRequest =
        new HelperJsonArrayRequest(
            Request.Method.PUT, url, params, view.getListener(), view.getErrorListener());

    requestQueue.add(jsArrRequest);
  }
Ejemplo n.º 14
0
  public void login(final Context context, String login, final Intent intent) {
    String url = apiServerUrl + apiPath + loginPath + "?login="******"APIManager", "FailedLogin: " + error.getMessage());
              }
            });

    queue.add(stringRequest);
  }
Ejemplo n.º 15
0
  public void rate(
      Context context, Response.Listener<String> responseListener, String eventID, float rate) {
    String url =
        apiServerUrl
            + apiPath
            + eventsPath
            + "/"
            + eventID
            + ratePath
            + "?rate="
            + String.valueOf(rate);
    RequestQueue queue = Volley.newRequestQueue(context);
    // Request a string response from the provided URL.
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            url,
            responseListener,
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Log.e("APIManager", "FailedRate: " + error.getMessage());
              }
            });

    queue.add(stringRequest);
  }
Ejemplo n.º 16
0
  void SetLock() {
    String l = new String("lock");
    Response.Listener<String> listener =
        new Response.Listener<String>() {
          @Override
          public void onResponse(String response) {
            try {
              // Log.i("tagconvertstr", "[" + response + "]");
              JSONObject jsonObject = new JSONObject(response);
              boolean success = jsonObject.getBoolean("success");

              if (success) {

                Toast.makeText(getApplication(), "Lock Set", Toast.LENGTH_SHORT).show();

              } else {
                Toast.makeText(getApplication(), "Lock Error", Toast.LENGTH_SHORT).show();
              }
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        };

    Lockrequest lr = new Lockrequest(l, listener);
    RequestQueue queue = Volley.newRequestQueue(getApplication());
    queue.add(lr);
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.around_me, container, false);

    if (location.latitude != 0 && location.longitude != 0)
      myLocation = new LatLng(location.latitude, location.longitude);
    else myLocation = new LatLng(40.7431735, -73.9799391);

    url =
        url
            + "location="
            + myLocation.latitude
            + ","
            + myLocation.longitude
            + "&radius="
            + radius
            + "&key="
            + key;

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

    final JsonObjectRequest jsObjRequest =
        new JsonObjectRequest(
            Request.Method.GET,
            url,
            (String) null,
            new Response.Listener<JSONObject>() {

              @Override
              public void onResponse(JSONObject response) {
                AroundMeParser parse = new AroundMeParser();
                JSONArray cleanPlaces = parse.cleanPlaces(parse.parseResponse(response));
                try {
                  cleanPlaces = sortTop25(cleanPlaces);
                  display(cleanPlaces);
                } catch (JSONException e) {
                  e.printStackTrace();
                  Toast.makeText(
                          getActivity(), "ERROR while Sorting or Display", Toast.LENGTH_SHORT)
                      .show();
                }
              }
            },
            new Response.ErrorListener() {

              @Override
              public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                // Toast.makeText(getActivity(), "ERROR: " + error.getMessage(),
                // Toast.LENGTH_SHORT).show();
                Log.i("", "ERROR: + error.getMessage()");
              }
            });

    requestQueue.add(jsObjRequest);

    return view;
  }
Ejemplo n.º 18
0
  public void getPubs() {

    pubs = new ArrayList<>();

    // Create request queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    //  Create json array request
    // todo
    JsonArrayRequest jsonArrayRequest =
        new JsonArrayRequest(
            "https://mysterious-shelf-1380.herokuapp.com/pubs/nearby/?x=" + a + "&y=" + b,
            new Response.Listener<JSONArray>() {
              public void onResponse(JSONArray jsonArray) {

                // Successfully download json
                // So parse it and populate the listview
                for (int i = 0; i < jsonArray.length(); i++) {
                  try {
                    Pub pub = new Pub();

                    // name, address
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    pub.setName(jsonObject.getString("name"));
                    pub.setAddress(jsonObject.getString("address"));

                    // prices
                    ArrayList<BeerPrice> beerPrices = new ArrayList<>();
                    JSONArray beerPricesJson = jsonObject.getJSONArray("beer_prices");
                    for (int j = 0; j < beerPricesJson.length(); ++j) {
                      JSONObject beer_price = beerPricesJson.getJSONObject(j);
                      float price = (float) beer_price.getDouble("price");
                      int votes = beer_price.getInt("votes");
                      beerPrices.add(new BeerPrice(price, votes));
                    }

                    pub.setBeerPrices(beerPrices);
                    // perks
                    HashMap<String, Boolean> perks = new HashMap<>();
                    for (String perk : Global.PERKS) {
                      perks.put(perk, jsonObject.getBoolean(perk));
                    }
                    pub.setPerks(perks);

                    pubs.add(pub);
                  } catch (JSONException e) {
                    e.printStackTrace();
                  }
                }
                populateMarks();
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError volleyError) {
                Log.e("Error", "Unable to parse json array");
              }
            });
    requestQueue.add(jsonArrayRequest);
  }
Ejemplo n.º 19
0
  void SendShareListToServer(
      final String ShoppingListName, final String nick, final String nickID) {
    try {

      RequestQueue MyRequestQueue = Volley.newRequestQueue(context);
      // Create data variable for sent values to server
      DebugLog.console("[ShoppingListAdapter]:Calling SendShareListToServer");

      String url = Commonthings.LocalServerAddress + "/qshop/client.php";
      StringRequest MyStringRequest =
          new StringRequest(
              Request.Method.POST,
              url,
              new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                  // This code is executed if the server responds, whether or not the response
                  // contains data.
                  // The String 'response' contains the server's response.
                  DebugLog.console(
                      "[ShoppingListAdapter]:Success Server Response " + response.toString());
                  Toast.makeText(
                          context,
                          ShoppingListName + " List Successfully Shared With " + nick,
                          Toast.LENGTH_LONG)
                      .show();
                }
              },
              new Response
                  .ErrorListener() { // Create an error listener to handle errors appropriately.
                @Override
                public void onErrorResponse(VolleyError error) {
                  // This code is executed if there is an error.
                  DebugLog.console(
                      "[ShoppingListAdapter]:Fail Server Response " + error.getMessage());
                  Toast.makeText(
                          context, "Something went wrong.Please try again.", Toast.LENGTH_LONG)
                      .show();
                }
              }) {
            protected Map<String, String> getParams() {
              Map<String, String> MyData = new HashMap<String, String>();
              MyData.put(
                  "action",
                  "setitemsnotificationAction"); // Add the data you'd like to send to the server.
              MyData.put("itemlist_to", "123"); // Add the data you'd like to send to the server.
              MyData.put("itemlist_from", "14444444");
              MyData.put("flag", "0");
              MyData.put("itemlist", ShoppingListName);
              return MyData;
            }
          };

      MyRequestQueue.add(MyStringRequest);

    } catch (Exception ex) {
      DebugLog.console(ex, "[ShoppingListAdapter]:Exception inside SendShareListToServer");
    }
  }
  private void eliminar(final Vehiculo vehiculo, final User sesion) {
    RequestQueue mRequestQueue;
    mRequestQueue = VolleySingleton.getInstance().getmRequestQueue();
    StringRequest request =
        new StringRequest(
            Request.Method.POST,
            "http://52.23.181.133/index.php/eliminarVehiculo",
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                try {
                  JSONObject json = new JSONObject(response);
                  if (json.getBoolean("exito")) {
                    Toast.makeText(
                            getApplicationContext(),
                            "Vehículo eliminado correctamente",
                            Toast.LENGTH_LONG)
                        .show();
                    Intent intent =
                        new Intent(DetalleVehiculoActivity.this, VehiculoActivity.class);
                    intent.putExtra("sesion", sesion);
                    intent.putExtra("vehiculo", vehiculo);
                    startActivity(intent);
                  } else {
                    Toast.makeText(
                            getApplicationContext(), json.getString("error"), Toast.LENGTH_LONG)
                        .show();
                  }
                } catch (JSONException e) {
                  Toast.makeText(
                          getApplicationContext(),
                          "Se ha producido un error al establecer comunicación con los servidores de Gerprin. Inténtelo de nuevo más tarde",
                          Toast.LENGTH_LONG)
                      .show();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Toast.makeText(
                        getApplicationContext(),
                        "Se ha producido un error al establecer comunicación con los servidores de Gerprin. Inténtelo de nuevo más tarde",
                        Toast.LENGTH_LONG)
                    .show();
              }
            }) {
          @Override
          protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();

            params.put("vehiculo_id", String.valueOf(vehiculo.getId()));

            return params;
          }
        };
    mRequestQueue.add(request);
  }
Ejemplo n.º 21
0
  public void sendTokenRequest() {
    progressWheel.setVisibility(View.VISIBLE);
    RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.POST,
            getRequestUrl(),
            new Response.Listener<String>() {
              @Override
              public void onResponse(String s) {
                progressWheel.setVisibility(View.GONE);
                Log.e("Value", s);
                preferenceClass.saveAccessToken(s);
                if (preferenceClass.getAccessToken() != null
                    && preferenceClass.getAccessToken().length() != 0) {
                  sendLoginJsonRequest();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError volleyError) {
                if (volleyError instanceof TimeoutError
                    || volleyError instanceof NoConnectionError) {
                  Snackbar.make(
                          loginLayout,
                          "Something is wrong with your internet connection. Please check your settings",
                          Snackbar.LENGTH_LONG)
                      .show();

                } else if (volleyError instanceof AuthFailureError) {
                  // TODO
                } else if (volleyError instanceof ServerError) {
                  hideKeyboard();
                  Snackbar.make(
                          loginLayout,
                          "We are facing problems in connecting to our servers. Just chill and try after some time :)",
                          Snackbar.LENGTH_LONG)
                      .show();
                } else if (volleyError instanceof NetworkError) {
                  Snackbar.make(
                          loginLayout,
                          "Something is wrong with your internet connection. Please check your settings",
                          Snackbar.LENGTH_LONG)
                      .show();

                } else if (volleyError instanceof ParseError) {

                  // TODO
                }
              }
            });
    stringRequest.setRetryPolicy(
        new DefaultRetryPolicy(
            9000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue.add(stringRequest);
  }
  public void getInternships(final tabBarActivity sender) {
    RequestQueue requestQueue;
    requestQueue = Volley.newRequestQueue(sender);
    String url = "https://bridge.jobs/api/api/Student/GetInternships";

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(sender);
    final String AccessToken = prefs.getString("AccessToken", null);

    JsonObjectRequest getInternships =
        new JsonObjectRequest(
            Request.Method.GET,
            url,
            null,
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                System.out.println(response);
                BRIMDataModel.savedInternshipsDataSource = response;
                String internshipRecords = "Records";
                JSONArray internshipRecordsArray = null;
                try {
                  internshipRecordsArray =
                      BRIMDataModel.savedInternshipsDataSource.getJSONArray(internshipRecords);
                } catch (JSONException e) {
                  Log.e("BRIM", "Error: JSON exception", e);
                }
                BRIMDataModel.homeviewInternships = internshipRecordsArray;
                JSONObject testArray = null;
                int id = 0;
                for (int i = 0; i < internshipRecordsArray.length(); i++) {
                  try {
                    testArray = internshipRecordsArray.getJSONObject(i);
                    id = testArray.getInt("Id");
                    System.out.println(id);
                  } catch (JSONException e) {
                    Log.e("BRIM", "Error: JSON exception", e);
                  }
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                VolleyLog.e("Error: ", error.getMessage());
              }
            }) {
          @Override
          public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            String auth = "Bearer " + AccessToken;
            params.put("Authorization", auth);

            return params;
          }
        };
    requestQueue.add(getInternships);
  }
Ejemplo n.º 23
0
 private void initData() {
   /**
    * 获取专辑音频列表
    * url:http://mobile.ximalaya.com/mobile/others/ca/album/track/321705/true/1/20?albumId=321705&pageSize=20&isAsc=true&position=3&device=android
    * *
    */
   String url =
       "http://mobile.ximalaya.com/mobile/others/ca/album/track/321705/true/"
           + currentPageNum
           + "/20?albumId=321705&pageSize=20&isAsc=true&position=3&device=android";
   RequestQueue queue = Volley.newRequestQueue(getContext());
   JsonObjectRequest request =
       new JsonObjectRequest(
           Request.Method.GET,
           url,
           null,
           new Response.Listener<JSONObject>() {
             @Override
             public void onResponse(JSONObject jsonObject) {
               Log.e("JSONResult", jsonObject.toString());
               JSONObject tracksObject = jsonObject.optJSONObject("tracks");
               JSONArray array = tracksObject.optJSONArray("list");
               for (int i = 0; i < array.length(); i++) {
                 JSONObject audioObject = array.optJSONObject(i);
                 Asset mAsset = new Asset();
                 mAsset.trackId = audioObject.optInt("trackId");
                 mAsset.downloadUrl = audioObject.optString("downloadUrl");
                 mAsset.title = audioObject.optString("title");
                 mAsset.createdAt = audioObject.optLong("createdAt");
                 mAsset.playtimes = audioObject.optInt("playtimes");
                 mAsset.duration = audioObject.optInt("duration");
                 mAsset.comments = audioObject.optInt("comments");
                 mAsset.playUrl64 = audioObject.optString("playUrl64");
                 audioList.add(mAsset);
               }
               int currentPage = tracksObject.optInt("pageId");
               int maxPageId = tracksObject.optInt("maxPageId");
               if (currentPage < maxPageId) {
                 loadMore = true;
                 currentPageNum++;
                 listView.addFooterView(footerView);
               } else {
                 listView.removeFooterView(footerView);
                 loadMore = false;
               }
               if (mAdapter == null) {
                 mAdapter = new AudiolistAdapter(audioList, getActivity());
                 listView.setAdapter(mAdapter);
               } else {
                 mAdapter.notifyDataSetChanged();
               }
               lastfinish = true;
             }
           },
           null);
   queue.add(request);
 }
 private void cancelFromRequestQueue(Request req, String tag) {
   if (null != makaanGetRequestQueue) {
     if (tag == null && null != req) {
       tag = requestUrlToTag.get(req.getUrl());
       makaanGetRequestQueue.cancelAll(tag);
     } else if (null != tag) {
       makaanGetRequestQueue.cancelAll(tag);
     }
   }
 }
Ejemplo n.º 25
0
  public void downloadSpaces() {

    final List<String> result = new ArrayList<String>();

    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(getActivity());
    String url = "http://opendata.paris.fr/api/records/1.0/search/?dataset=parcsetjardinsparis2010";

    // Request a string response from the provided URL.
    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            url,
            // if its works
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {

                // use the ObjectMapper from org.codehaus.jackson.map.ObjectMapper
                final ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                String jsonObject =
                    response; // we are getting in from the onResponse in the *MainActivity.java*

                try {
                  DataSet dataSet =
                      objectMapper.readValue(response, new TypeReference<DataSet>() {});
                  for (EV ev : dataSet.getRecords()) {
                    result.add(ev.getFields().getNom_ev());
                  }
                  names = new String[result.size()];
                  for (int i = 0; i < result.size(); i++) {
                    Log.d(">>" + i, result.get(i));
                    names[i] = result.get(i);
                  }
                  setupRecyclerView(rv);

                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            },

            // if it does not work
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                Log.d("volley erro", error.toString());
              }
            });

    // Add the request to the RequestQueue.
    queue.add(stringRequest);
  }
Ejemplo n.º 26
0
  // Método encargado de realizar peticiones de creación, modificación o eliminación de un usuario
  // y que recibe como parámetro de entrada la URI para realizar dicha petición al servicio web.
  public void peticionServicioUsuario(String uri) {
    // Se declara e inicializa una variable de tipo RequestQueue, encargada de crear
    // una nueva petición en la cola del servicio web.
    RequestQueue queue = Volley.newRequestQueue(getActivity());

    // Se declara e inicializa un objeto de tipo StringRequest, que permite recuperar un
    // String a partir de la URL que recibe. El constructor de la clase StringRequest
    // recibe como argumentos de entrada el método para que el cliente realice operaciones
    // sobre el servicio web, la uri para el acceso al recurso, la interfaz Response.Listener,
    // encargada de devolver la respuesta parseada a la petición del cliente, y la interfaz
    // Response.ErrorListener encargada de entregar una respuesta errónea desde el servicio web.
    StringRequest sRequest =
        new StringRequest(
            Request.Method.GET,
            uri,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                try {
                  // Nuevo usuario insertado o Usuario borrado correctamente
                  Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                try {
                  Toast.makeText(
                          getActivity(),
                          "Error en la petición de servicio de usuario: " + error.toString(),
                          Toast.LENGTH_LONG)
                      .show();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });

    // Se definen las políticas para la petición realizada. Recibe como argumento una
    // instancia de la clase DefaultRetryPolicy, que recibe como parámetros de entrada
    // el tiempo inicial de espera para la respuesta, el número máximo de intentos,
    // y el multiplicador de retardo de envío por defecto.
    sRequest.setRetryPolicy(
        new DefaultRetryPolicy(
            15000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    // Se añade la petición a la cola con el objeto de tipo JsonArrayRequest.
    queue.add(sRequest);
  }
  private ArrayList<GooglePlace> autoComplete(String autotext) {
    Log.e("in autocomplete", "success --> " + autotext);
    final ArrayList<GooglePlace> list = new ArrayList();
    StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);

    sb.append("?key=" + API_KEY);

    sb.append("&components=country:in");

    try {
      sb.append("&input=" + URLEncoder.encode(autotext, "utf8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

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

    Log.e("json is", sb.toString());
    JsonObjectRequest jsonObjectRequest =
        new JsonObjectRequest(
            Request.Method.GET,
            sb.toString(),
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {

                try {
                  JSONArray jsonArray = response.getJSONArray("predictions");
                  for (int i = 0; i < jsonArray.length(); i++) {
                    String placeDesc = jsonArray.getJSONObject(i).getString("description");
                    String placeId = jsonArray.getJSONObject(i).getString("place_id");
                    list.add(new GooglePlace(placeDesc, placeId));
                  }

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

                MainActivity activity = (MainActivity) context;
                activity.updateArraryListData(list);
                arrayList = list;
                notifyDataSetChanged();
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {}
            });
    requestQueue.add(jsonObjectRequest);
    return list;
  }
Ejemplo n.º 28
0
  private static RequestQueue newRequestQueue(Context context) {
    Proxy proxy = NetUtil.getProxy();
    File cacheDir =
        new File(DirectoryManager.getDirectory(DirectoryManager.DIR.CACHE), DEFAULT_CACHE_DIR);

    String userAgent = "CGTong/0";
    try {
      String packageName = context.getPackageName();
      PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
      userAgent = packageName + "/" + info.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
      return null;
    }
    if (Build.VERSION.SDK_INT >= 9) {
      stack = new HurlStack(proxy);
    } else {
      // Prior to Gingerbread, HttpUrlConnection was unreliable.
      // See:
      // http://android-developers.blogspot.com/2011/09/androids-http-clients.html
      AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent);
      if (proxy != null) {
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      stack = new HttpClientStack(client);
    }
    Network network = new BasicNetwork(stack);

    final DiskBasedCache diskCache = new DiskBasedCache(cacheDir);
    // 监听目录的变化,切换cache目录
    DirectoryManager.addSdCardListener(
        new DirectoryManager.SdcardStatusListener() {
          @Override
          public void onChange(SDCARD_STATUS status) {
            new Thread(
                    new Runnable() {
                      @Override
                      public void run() {
                        diskCache.switchCache(
                            new File(
                                DirectoryManager.getDirectory(DirectoryManager.DIR.CACHE),
                                DEFAULT_CACHE_DIR));
                      }
                    })
                .start();
          }
        });

    RequestQueue queue = new RequestQueue(diskCache, network);
    // RequestQueue queue = Volley.newRequestQueue(context);
    queue.start();
    return queue;
  }
Ejemplo n.º 29
0
  @Override
  public void get(String id) {
    String url = "";

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    url = AppRetailDaoAbstract.URL_API + ShoppingCartItemModel.SHOPPING_CART_ITEM + "/" + id;
    HelperJsonArrayRequest jsArrRequest =
        new HelperJsonArrayRequest(
            Request.Method.GET, url, null, view.getListener(), view.getErrorListener());

    requestQueue.add(jsArrRequest);
  }
Ejemplo n.º 30
0
 public void removeCache(String url) {
   mRequestQueue.getCache().remove(url);
   if (mRequestQueue.getCache().get(url) == null) Log.e(TAG, "remove cache:" + url);
   myImageCache.remove(
       new StringBuilder(url.length() + 12)
           .append("#W")
           .append(168)
           .append("#H")
           .append(168)
           .append(url)
           .toString());
   Log.e(TAG, "remove isCache:" + mImageLoader.isCached(url, 168, 168));
 }