Search in sources :

Example 1 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project Space-Station-Tracker by Kiarasht.

the class MapsActivity method trackISS.

/**
     * Get the Lat and Lon of ISS and move the map to that position when called.
     */
private void trackISS() {
    final String url = "https://api.wheretheiss.at/v1/satellites/25544";
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                // Server responded successfully
                mSuccess = 0;
                final double latParameter = Double.parseDouble(response.getString("latitude"));
                final double lngParameter = Double.parseDouble(response.getString("longitude"));
                final LatLng ISS = new LatLng(latParameter, lngParameter);
                final String LAT;
                final String LNG;
                if (latParameter < 0) {
                    LAT = mDecimalFormat.format(latParameter) + "° S";
                } else {
                    LAT = mDecimalFormat.format(latParameter) + "° N";
                }
                if (lngParameter < 0) {
                    LNG = mDecimalFormat.format(lngParameter) + "° W";
                } else {
                    LNG = mDecimalFormat.format(lngParameter) + "° E";
                }
                final String position = LAT + ", " + LNG;
                final String visibility = response.getString("visibility");
                final StringBuilder moreInfo = new StringBuilder();
                moreInfo.append("Altitude: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("altitude")))).append(" km").append("\n").append("Velocity: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("velocity")))).append(" kph").append("\n").append("Footprint: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("footprint")))).append(" km").append("\n").append("Solar LAT: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("solar_lat")))).append("°").append("\n").append("Solar LON: ").append(mDecimalFormat.format(Double.parseDouble(response.getString("solar_lon")))).append("°").append("\n").append("Visibility: ").append(visibility.substring(0, 1).toUpperCase()).append(visibility.substring(1)).append("\n");
                MapsActivity.this.runOnUiThread(new Runnable() {

                    public void run() {
                        if (mOnce) {
                            mMap.moveCamera(CameraUpdateFactory.newLatLng(ISS));
                            if (mMap.getUiSettings().isScrollGesturesEnabled()) {
                                mMap.getUiSettings().setScrollGesturesEnabled(false);
                            }
                            mOnce = false;
                        } else if (mSharedPreferences.getBoolean("lock_ISS", false)) {
                            mMap.moveCamera(CameraUpdateFactory.newLatLng(ISS));
                            if (mMap.getUiSettings().isScrollGesturesEnabled()) {
                                mMap.getUiSettings().setScrollGesturesEnabled(false);
                            }
                        } else if (!mSharedPreferences.getBoolean("lock_ISS", false)) {
                            mMap.getUiSettings().setScrollGesturesEnabled(true);
                        }
                        if (mMarker != null) {
                            mMarker.remove();
                        }
                        mDescription.setText(moreInfo.toString());
                        mLatLong.setText(position);
                        mMarkerOptions.position(ISS);
                        mMarker = mMap.addMarker(mMarkerOptions);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError e) {
            // Server did not respond. Got 5 chances before stop trying.
            if (++mSuccess <= 4) {
                Toast.makeText(MapsActivity.this, getResources().getString(R.string.errorLessFive, mSuccess, mRefreshrate), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MapsActivity.this, R.string.errorFiveTimes, Toast.LENGTH_LONG).show();
                if (mTimer != null) {
                    mTimer.cancel();
                    mTimer.purge();
                }
                mTimer = null;
            }
        }
    });
    jsonObjectRequest.setTag(TAG);
    mRequestQueue.add(jsonObjectRequest);
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) LatLng(com.google.android.gms.maps.model.LatLng)

Example 2 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project Space-Station-Tracker by Kiarasht.

the class Locations method displayPasses.

/**
     * After successfully getting a city and country from the last JSON parsing, search a database
     * to see when ISS will pass by this city, country.
     */
public List<Date> displayPasses(final String latitude, final String longitude, final Context applicationContext) {
    // Used for Alert service
    final List<Date> passes = new ArrayList<>();
    final String url;
    if (latitude == null && longitude == null) {
        // Location.java is calling this method
        url = "http://api.open-notify.org/iss-pass.json?lat=" + mLatitude + "&lon=" + mLongitude + "&n=20";
    } else {
        // Alert.java is calling this method
        url = "http://api.open-notify.org/iss-pass.json?lat=" + latitude + "&lon=" + longitude;
    }
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                final JSONArray results = response.getJSONArray("response");
                final List<SightSee> dates = new ArrayList<>();
                for (int i = 0; i < results.length(); ++i) {
                    final JSONObject aPass = results.getJSONObject(i);
                    passes.add(new Date(Long.parseLong(aPass.getString("risetime")) * 1000L));
                    final SightSee aSightSee = new SightSee(aPass.getInt("duration"), aPass.getInt("risetime"));
                    dates.add(aSightSee);
                }
                final View headerView = LayoutInflater.from(mActivity).inflate(R.layout.locations_header, null);
                headerView.post(new Runnable() {

                    @Override
                    public void run() {
                        headerView.getLayoutParams().height = mFlexibleSpaceImageHeight;
                    }
                });
                mAdapter = new LocationAdapter(mActivity, headerView);
                mAdapter.setDataSet(dates);
                mRecyclerView.setAdapter(mAdapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError e) {
            if (latitude == null && longitude == null) {
                Toast.makeText(Locations.this, R.string.errorConnection, Toast.LENGTH_LONG).show();
            }
        }
    });
    // If Alert.java called us
    if (requestQueue == null) {
        RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
        requestQueue.add(jsonObjectRequest);
    } else {
        // If Locations.java called us
        jsonObjectRequest.setTag(TAG);
        requestQueue.add(jsonObjectRequest);
    }
    // Only Alert.java benefits from this return
    return passes;
}
Also used : VolleyError(com.android.volley.VolleyError) LocationAdapter(com.restart.spacestationtracker.adapter.LocationAdapter) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) ImageView(android.widget.ImageView) ObservableRecyclerView(com.github.ksoichiro.android.observablescrollview.ObservableRecyclerView) View(android.view.View) AdView(com.google.android.gms.ads.AdView) TextView(android.widget.TextView) Date(java.util.Date) Response(com.android.volley.Response) JSONObject(org.json.JSONObject) SightSee(com.restart.spacestationtracker.data.SightSee) RequestQueue(com.android.volley.RequestQueue) ArrayList(java.util.ArrayList) List(java.util.List) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest)

Example 3 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project Space-Station-Tracker by Kiarasht.

the class PeopleinSpace method display_people.

/**
     * Displays a list of astronauts in a RecyclerView
     */
private void display_people() {
    final String url = "http://www.howmanypeopleareinspacerightnow.com/peopleinspace.json";
    final List<Astronaut> peopleInSpace = new ArrayList<>();
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                LinearLayoutManager layoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
                mRecyclerView.setLayoutManager(layoutManager);
                mAdapter = new PeopleInSpaceAdapter(mActivity, peopleInSpace);
                mRecyclerView.setHasFixedSize(true);
                mRecyclerView.setNestedScrollingEnabled(true);
                mAdapter.setDataSet(peopleInSpace);
                mRecyclerView.setAdapter(mAdapter);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError e) {
        }
    }) {

        @Override
        protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
            try {
                String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
                JSONObject jsonResponse = new JSONObject(jsonString);
                try {
                    JSONArray astronauts = jsonResponse.getJSONArray("people");
                    for (int i = 0; i < astronauts.length(); ++i) {
                        JSONObject anAstronaut = astronauts.getJSONObject(i);
                        final String name = anAstronaut.getString("name");
                        final String image = anAstronaut.getString("biophoto");
                        final String countryLink = anAstronaut.getString("countryflag");
                        final String launchDate = anAstronaut.getString("launchdate");
                        String role = anAstronaut.getString("title");
                        final String location = anAstronaut.getString("location");
                        final String bio = anAstronaut.getString("bio");
                        final String wiki = anAstronaut.getString("biolink");
                        final String twitter = anAstronaut.getString("twitter");
                        if (role != null && !role.isEmpty())
                            role = role.substring(0, 1).toUpperCase() + role.substring(1);
                        Astronaut storeAnAstronaut = new Astronaut(name, image, countryLink, launchDate, role, location, bio, wiki, twitter);
                        peopleInSpace.add(storeAnAstronaut);
                    }
                    Collections.sort(peopleInSpace);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
            } catch (UnsupportedEncodingException e) {
                return Response.error(new ParseError(e));
            } catch (JSONException je) {
                return Response.error(new ParseError(je));
            }
        }
    };
    mRequestQueue.add(jsonObjectRequest);
}
Also used : VolleyError(com.android.volley.VolleyError) Astronaut(com.restart.spacestationtracker.data.Astronaut) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) PeopleInSpaceAdapter(com.restart.spacestationtracker.adapter.PeopleInSpaceAdapter) JSONException(org.json.JSONException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.android.volley.Response) NetworkResponse(com.android.volley.NetworkResponse) JSONObject(org.json.JSONObject) NetworkResponse(com.android.volley.NetworkResponse) ParseError(com.android.volley.ParseError) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest)

Example 4 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project buglife-android by Buglife.

the class SubmitReportTask method execute.

/**
 * Asynchronously executes a POST request
 * @param report a JSON payload with the report to submit
 * @param callback Calls back with the result of the request; this is called on the main thread
 */
public void execute(JSONObject report, final ReportSubmissionCallback callback) {
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, BUGLIFE_REPORT_URL, report, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.d("Report submitted successfully!");
            callback.onSuccess();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("Error submitting report", error);
            callback.onFailure(ReportSubmissionCallback.Error.NETWORK, error);
        }
    });
    mNetworkManager.addToRequestQueue(request);
    Log.d("JSON object request for report added to request queue...");
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest)

Example 5 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project yellowmessenger-sdk by yellowmessenger.

the class DiscoverFragment method fetchFeaturedBots.

public void fetchFeaturedBots() throws UnsupportedEncodingException {
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("country", PreferencesManager.getInstance(getContext()).getCountry());
        jsonObject.put("type", PreferencesManager.getInstance(getContext()).getAccount());
    } catch (Exception e) {
        e.printStackTrace();
    }
    String url = "https://corona.botplatform.io/settings";
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                if (response.getBoolean("success") && getActivity() != null) {
                    JSONArray objects = response.getJSONArray("data");
                    if (objects != null && objects.length() > 0) {
                        final List<Featured> featuredList = new LinkedList<>();
                        JSONArray featuredObjs = objects.getJSONObject(0).getJSONArray("value");
                        for (int i = 0; i < featuredObjs.length(); i++) {
                            JSONObject featuredObj = featuredObjs.getJSONObject(i);
                            featuredList.add(gson.fromJson(featuredObj.toString(), Featured.class));
                        }
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                DiscoverFragment.this.featuredObjects.clear();
                                DiscoverFragment.this.featuredObjects.addAll(featuredList);
                                DiscoverFragment.this.featuredAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    jsonObjectRequest.setRetryPolicy(retryPolicy);
    queue.add(jsonObjectRequest);
}
Also used : VolleyError(com.android.volley.VolleyError) JSONArray(org.json.JSONArray) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Response(com.android.volley.Response) JSONObject(org.json.JSONObject) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest)

Aggregations

JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)109 JSONObject (org.json.JSONObject)109 VolleyError (com.android.volley.VolleyError)97 Response (com.android.volley.Response)95 HashMap (java.util.HashMap)62 RequestQueue (com.android.volley.RequestQueue)59 User (model.User)50 JSONException (org.json.JSONException)45 Gson (com.google.gson.Gson)24 Context (android.content.Context)18 Test (org.junit.Test)18 Toast (android.widget.Toast)17 GsonBuilder (com.google.gson.GsonBuilder)17 NetworkResponse (com.android.volley.NetworkResponse)12 TextView (android.widget.TextView)9 DefaultRetryPolicy (com.android.volley.DefaultRetryPolicy)7 Wallet (it.angelic.mpw.model.jsonpojos.wallet.Wallet)7 HomeStats (it.angelic.mpw.model.jsonpojos.home.HomeStats)5 Intent (android.content.Intent)4 Pair (android.util.Pair)4