Monday, 21 December 2020

How to use JSON to display weather data?

Basically, I have designed UI/UX for a weather app, set up a remote connection class for it for fetching data from OpenWeatherMap API:

RemoteFetch.java:

 import android.content.Context;
 
 import androidx.appcompat.app.AppCompatActivity;
 
 import org.json.JSONObject;
 
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.URL;
 
 public class RemoteFetch extends AppCompatActivity {
 
     private static final String OPEN_WEATHER_MAP_API =
             "https://api.openweathermap.org/data/2.5/onecall?lat=9.0765&lon=7.3986&exclude=daily&appid=";
 
     public static JSONObject getJSON(Context context, String city){
         try {
             URL url = new URL(String.format(OPEN_WEATHER_MAP_API, city));
             HttpURLConnection connection =
                     (HttpURLConnection)url.openConnection();
 
             connection.addRequestProperty("x-api-key",
                     context.getString(R.string.open_weather_maps_app_id));
 
             BufferedReader reader = new BufferedReader(
                     new InputStreamReader(connection.getInputStream()));
 
             StringBuilder json = new StringBuilder(1024);
             String tmp;
             while((tmp=reader.readLine())!=null)
                 json.append(tmp).append("\n");
             reader.close();
 
             JSONObject data = new JSONObject(json.toString());
 
             // This value will be 404 if the request was not
             // successful
             if(data.getInt("cod") != 200){
                 return null;
             }
 
             return data;
         }catch(Exception e){
             return null;
         }
     }
 }

created a thread to call getJSON for the RemoteFetch class inside my fragment class and If the value returned by getJSON is null, should display an error message to the user:

 private void updateWeatherData(final String city) {
     new Thread(){
         public void run(){
             final JSONObject json = RemoteFetch.getJSON(getActivity(), city);
             if(json == null){
                 handler.post(new Runnable(){
                     public void run(){
                         Toast.makeText(getActivity(),
                                 getActivity().getString(R.string.place_not_found),
                                 Toast.LENGTH_LONG).show();
                     }
                 });
             } else {
                 handler.post(new Runnable(){
                     public void run(){
                         renderWeather(json);
                     }

If it isn't, should invoke the renderWeather method. The renderWeather method uses the JSON data to update the TextView objects that I set up in my fragment class:

 private void renderWeather(JSONObject json){
                         try {
                             cityField.setText(json.getString("name").toUpperCase(Locale.US)) +
                                     ", " +
                                     json.getJSONObject("sys").getString("country");
                             JSONObject details = json.getJSONArray("Weather").getJSONObject(0);
                             JSONObject main = json.getJSONObject("main");
                             detailsfield.setText(
                                     details.getString("description").toUpperCase(Locale.US) +
                                             "\n" + "Humidity: " + main.getString("humidity") + "%" +
                                             "\n" + "Pressure: " + main.getString("pressure") + " hpa");
 
                             current_temp.setText(
                                     String.format("%.2f", main.getDouble("temp")) + " \\u2103");
 
                             DateFormat df = DateFormat.getDateTimeInstance();
                             String updatedOn = df.format(new Date(json.getLong("dt") * 1000));
                             updatedField.setText("Last update: " + updatedOn);
 
                             setcurrent_output(details.getInt("id"),
                                     json.getJSONObject("sys").getLong("sunrise") * 1000,
                                     json.getJSONObject("sys").getLong("sunset") * 1000);
 
                         }catch (Exception e){
                             Log.e("lightweatherforcast", "One or more fields not found in this JSON data");
 
 
 
                         }
                     }
                 });
             }
         }
     }.start();
 }
  Now this is where the problem is because the tutorial I learned from used it to match their app UI but my app is different and

contains more details which I need to add from my setup, I have tried so many methods unfailingly to match my APP UI unsuccessfully.

So far, with the weather setup, everything works fine, the only problem is with the renderWeather method. I'm trying to use JSON to display the weather data in the following TextViews currently:

 *`User city(cityField)`,
 *`Current time(Updated Field)`
 *`Current Temperature(current_temp)`
 *`Condition of the current temperature(current_output)`
 *`Tomorrow Temperature(small_temp1)`
 *`Condition of tomorrow's temperature(small_icon1)`
 *`Next tomorrow's temperature(small_temp2)`
 *`Condition of Next tomorrow's temperature(small_icon2)`
 *`Sunrise time(rise_time)`
 *`Sunset set(set_time)`

Under weather conditions panel:

 *`Temperature(temp_out)`
 *`Pressure(press_out)`
 *`Humidity(Humid_out)`
 *`Wind Speed(Ws_out)`
 *`Visibility(Visi_out)`
 *`UV index(UV_out)`

I plan to inject the weather data into all these texts in bracket(I've gotten the id of all of them in my fragment class, remaining to implement with JSON. The position for the data is already set up, my problem is placing them inside these images:

https://i.stack.imgur.com/kbbYk.png - for the city and current time https://i.stack.imgur.com/yDhqH.png - for current, tomorrow, and next tomorrow https://i.stack.imgur.com/1x0GU.png - for sunrise and sunset https://i.stack.imgur.com/5awl5.png - for weather conditions.

I'm not quite new to android dev, but it's my first time handling these sets of data, please don't refer me to any tutorial as I've already picked a lot of samples from varieties of them, just that most of them are very basic, old and buggy. Please ask me to provide more information if needed, I intentionally didn't post the API key I used for the app but it's in my setup in case you need it.

Process finished with exit code 0



from How to use JSON to display weather data?

No comments:

Post a Comment