how to get data from a weather server Part 1.

In this tutorial we access a weather data from a following Server: https://home.openweathermap.org

The first step is to to allow internet permission in Android manifest file.

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

Second add in build.gradle(Module:app) following dependency:implementation ‘com.android.volley:volley:1.1.1’
Now we need to set up a Network based HTTP client.In this example we use a JSON object example from a server.

RequestQueue queue = Volley.newRequestQueue(this);String url ="https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22";

Our JSON File from a weather server:

{"coord":{"lon":139.01,"lat":35.02},"weather":

[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":

{"temp":285.514,"pressure":1013.75,"humidity":100,"temp_min":285.514,"temp_max":285.514,"sea_level":1023.22,"grnd_level":1013.75},"wind":{"speed":5.52,"deg":311},"clouds":

{"all":0},"dt":1485792967,"sys":

{"message":0.0025,"country":"JP","sunrise":1485726240,"sunset":1485763863},"id":1907296,"name":"Tawarano","cod":200}

Now we need to implement anonymous method and overload with url,Request.Method.GET,new Response.Listener<String>:

Using a JSONObject and JSONArray we access  to our data from server

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

                   
try {
    JSONObject jsonObject = new JSONObject(response);
    JSONArray results =  jsonObject.getJSONArray("weather");
    JSONObject resultObject = (JSONObject) results.get(0);

    String id = resultObject.getString("description");
    JSONObject jsonObject2 = new JSONObject(response);


String txtitem =  jsonObject2.getJSONObject("main").getString("temp");

tx.setText("Temperature:"+txtitem+"K");
float celsius = Float.parseFloat(txtitem)-273.15f;
txc.setText("Temperature:"+celsius+"C°");
txd.setText("description: "+id);

    }catch(JSONException ex){

}
          }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Error","doesnt work");

            }
        });
queue.add(stringRequest);
 }

Full code:

public class MainActivity extends AppCompatActivity {
    // Instantiate the RequestQueue.


TextView tx;
TextView txc;
TextView txd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tx = findViewById(R.id.txt);
        txc = findViewById(R.id.txtc);
txd = findViewById(R.id.txtDescription);

        RequestQueue queue = Volley.newRequestQueue(this);

        String url =
  "https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22";


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


try {
    JSONObject jsonObject = new JSONObject(response);
    JSONArray results =  jsonObject.getJSONArray("weather");
    JSONObject resultObject = (JSONObject) results.get(0);

    String id = resultObject.getString("description");

    Log.i("temperature",id);

    JSONObject jsonObject2 = new JSONObject(response);


  String txtitem =  jsonObject2.getJSONObject("main").getString("temp");

tx.setText("Temperature:"+txtitem+"K");
float celsius = Float.parseFloat(txtitem)-273.15f;
txc.setText("Temperature:"+celsius+"C°");
txd.setText("description: "+id);







}catch(JSONException ex){

}


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Error","doesnt work");

            }
        });
        queue.add(stringRequest);

    }

    // Request a string response from the provided URL.


// Add the request to the RequestQueue.


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txtc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txtDescription"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Android Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="learn.hq.weatherforecast">
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

OUTPUT:

Source Code:

}

Leave a Reply