java如何使用JSON显示天气数据?
基本上,我为天气应用程序设计了UI/UX,设置了一个远程应用程序 用于从OpenWeatherMap API获取数据的it连接类:
RemoteFetch。java:
import 安卓.content.Context;
import 安卓x.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;
}
}
}
为内部的RemoteFetch类创建了一个thread
来调用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,但我的应用程序是不同的,而且 包含我需要从设置中添加的更多详细信息,我已尝试 有这么多的方法一直在匹配我的应用程序界面,但都没有成功
到目前为止,通过天气设置,一切正常,只有
问题在于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"
}
]
}
}
# 1 楼答案
这似乎是一个重复我留下的链接的链接,你可能会发现有用的下面
但作为一个简单的答案,你可以用文本来表示这些天气数据,就像上面那个问题所回答的那样,然后你可以选择在你想要的UI中设置放置位置的选项。 JSON格式将非常简单:
您可以通过以下方式访问这些数据:-
如果你觉得我的答案奇怪、难以理解或难以理解,你可以查看我在下面嵌入的问题。谢谢 [1] :How to retrieve weather data in json [android]