[英]How to use JSON to display weather data?
基本上,我為天氣應用程序設計了 UI/UX,為它設置了一個遠程連接類以從 OpenWeatherMap API 獲取數據:
遠程獲取.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;
}
}
}
創建了一個thread
來為片段類中的 RemoteFetch 類調用getJSON
,如果getJSON
返回的值為 null,則應向用戶顯示錯誤消息:
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);
}
如果不是,則應調用renderWeather
方法。 renderWeather
方法使用 JSON 數據更新我在片段類中設置的TextView
對象:
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();
}
現在這就是問題所在,因為我從中學到的教程使用它來匹配他們的應用程序 UI,但我的應用程序是不同的,並且包含我需要從設置中添加的更多詳細信息,我已經嘗試了很多方法來匹配我的應用程序 UI不成功。
到目前為止,使用天氣設置,一切正常,唯一的問題是renderWeather
方法。 我目前正在嘗試使用JSON
在以下TextViews
顯示天氣數據:
*`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)`
在天氣條件面板下:
*`Temperature(temp_out)`
*`Pressure(press_out)`
*`Humidity(Humid_out)`
*`Wind Speed(Ws_out)`
*`Visibility(Visi_out)`
*`UV index(UV_out)`
進程以退出代碼 0 結束
這是 JSON 響應的樣子(為了可讀性而格式化):
{
"lat":9.08,
"lon":7.4,
"timezone":"Africa/Lagos",
"timezone_offset":3600,
"current":{
"dt":1608984165,
"sunrise":1608961391,
"sunset":1609003132,
"temp":305.15,
"feels_like":303.24,
"pressure":1012,
"humidity":25,
"dew_point":282.68,
"uvi":8.87,
"clouds":35,
"visibility":5000,
"wind_speed":2.6,
"wind_deg":150,
"weather":[
{
"id":721,
"main":"Haze",
"description":"haze",
"icon":"50d"
}
]
}
}
這似乎是重復的,我留下了您可能會在下面發現有用的鏈接的鏈接。
但是,作為在上面的問題中回答的以文本形式實際表示這些天氣數據的簡單答案,您可以選擇設置要將其放置在您想要的 UI 中的位置。 JSON 格式將很簡單,:-
city: {
id: 2643743, //City ID, You may find more about these at https://openweathermap.org/find?q=
name: "London", //City Name, Just the name of your city
coord: {
lon: -0.12574,//These are coordinates for the city, Find them at google maps
lat: 51.50853
},
country: "GB", //Country names, GB here stands for United Kingdom, learn more at https://sustainablesources.com/resources/country-abbreviations/
population: 0 //Country Population
},
cod: "200",
message: 0.0268,
cnt: 5,
list: [
{
dt: 1448535600,
temp: { //Average Temperature at these times of the day (Current data is for london)
day: 8.58,
min: 8.58,
max: 9.18,
night: 9.18,
eve: 8.58,
morn: 8.58
}, //This is average temperature properties
pressure: 1025.14,
humidity: 95,
weather: [
{//Average Rain (Properties & Probabilities)
id: 500,
main: "Rain",
description: "light rain",
icon: "10d"
}
],
speed: 3.67,
deg: 224,
clouds: 92,
rain: 0.35
},
{},
{},
{},
{}
]
您可以使用以下方法訪問這些數據:-
JSONObject forecastJson = new JSONObject(jsonString);
JSONArray forecastArray = forecastJson.getJSONArray("list");
double minTemp, maxTemp;
for(int i = 0; i < forecastArray.length(); i++) {
JSONObject dailyForecast = forecastArray.getJSONObject(i);
JSONObject tempObject = dailyForecast.getJSONObject("temp");
minTemp = tempObject.getDouble("min");
maxTemp = tempObject.getDouble("max");
//add these minTemp and maxTemp to array or the
//way you want to use
}
如果您發現我的回答很奇怪、難以理解或難以理解,您可以查看我在下面嵌入的問題。 謝謝。 [1]: 如何在json中檢索天氣數據[android]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.