Using the Volley library in Android using data from the weather API as an example

Every Android developer has to work with a network sooner or later. Android has many open source libraries, such as Retrofit, OkHttp or, for example, Volley, which we will dwell on in more detail today.

So what is this library like?

Volley is an HTTP library that simplifies and speeds up networking for Android applications.
GitHub library code .

So, to get started with Volley, we need to add it to build.gradle (module: app):

dependencies {
    ...
    implementation 'com.android.volley:volley:1.1.1'
}

It is also necessary to add permission to use the Internet in the manifest of our application:

<uses-permission android:name="android.permission.INTERNET" />

Next we need an API. In this tutorial, I will use the weather API from openweathermap.org/api .

Example of this API

To begin with, we will create a simple markup for displaying data taken from the API (Application programming interface).

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tempTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=": "
        android:textSize="20sp"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="50dp"
        android:layout_alignParentTop="true"
        android:layout_marginTop="50dp"
        />

    <TextView
        android:id="@+id/windTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="50dp"
        android:textSize="20sp"
        android:layout_marginTop="10dp"
        android:text=" :"
        />

</RelativeLayout>

Next, go to MainActivity and create the necessary fields:

private static final String testUrl = "https://samples.openweathermap.org/data/2.5/weather?id=2172797&appid=b6907d289e10d714a6e88b30761fae22"; //url,      JSON- 
RequestQueue mRequestQueue; //  
TextView tempTextView,windTextView; //     
double temp = 0,windSpeed = 0; //      JSON

We initialize the created field fields in onCreate:

tempTextView = findViewById(R.id.tempTextView);
windTextView = findViewById(R.id.windTextView);

mRequestQueue = Volley.newRequestQueue(this);

Now we come to the main topic of this tutorial - getting data from the API using the Volley library:

1) In the MainActivity we create the GetWeather method:

private void getWeather(String url) {
        final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, //GET - API-   
                url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject weather = response.getJSONObject("main"),wind = response.getJSONObject("wind"); // JSON- main  wind (   - ,   -  (JSONArray).
                    temp = weather.getDouble("temp"); 
                    windSpeed = wind.getDouble("speed");
                    //      API
                    setValues(); //   setValues    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() { //    
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mRequestQueue.add(request); //    
}

image
jsonformatter was used to bring json to its normal form .
It is worth noting that the names of the objects must be written in exactly the same way as in our API, otherwise they just won’t get it.

2) Create, directly, the setValues ​​method:

private void setValues() {
        tempTextView.setText(": " + temp);
        windTextView.setText(" : " + windSpeed);
}

3) Call the getWeather () and setValues ​​() methods in onCreate ():

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getWeather(testUrl);
        setValues();
}

4) Run the application and ... done!

image

PS: Some useful links for those who want to understand the issue more deeply:

The official documentation of the Volley library

For a better understanding of the essence of the API

Types of HTTP requests

Writing data in JSON format

P.SS: Application files on GitHub

All Articles