【发布时间】:2019-10-14 18:55:12
【问题描述】:
我的应用程序已运行。但没有加载任何文本。
我想使用 JSON 从 OpenWeatherMap api 获取数据。我不知道问题出在哪里。
这是我的邮递员观点 enter image description here
这是我的 Activity.java ( 如上图所示,我的 APIkey 工作正常。)
public class WeatherActivity extends AppCompatActivity {
TextView t1_temp,t2_city,t3_weather,t4_date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
t1_temp = (TextView)findViewById(R.id.w_temp);
t2_city = (TextView)findViewById(R.id.w_cityname);
t3_weather = (TextView)findViewById(R.id.w_weather);
t4_date = (TextView)findViewById(R.id.w_date);
find_weather();
}
public void find_weather(){
String url = "api.openweathermap.org/data/2.5/weather?appid=MyopenweatherAPIKEY&units=metric&q=Seoul";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject main_object = response.getJSONObject("main");
JSONArray array = response.getJSONArray("weather");
JSONObject object = array.getJSONObject(0);
String temp = String.valueOf(main_object.getDouble("temp"));
String weahtercondition = object.getString("description");
String city = response.getString("name");
t1_temp.setText(temp);
t2_city.setText(city);
t3_weather.setText(weahtercondition);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("KKKK-MM-dd");
String formatted_date = sdf.format(calendar.getTime());
t4_date.setText(formatted_date);
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jor);
}
}
这是我的 weather.xml
<RelativeLayout
android:id="@+id/weatherview"
android:layout_width="match_parent"
android:layout_height="250sp"
android:orientation="horizontal">
<TextView
android:id="@+id/w_temp"
android:layout_width="125dp"
android:layout_height="95dp"
android:text="30"
android:textSize="50dp" />
<TextView
android:id="@+id/w_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginStart="85dp"
android:layout_marginEnd="90dp"
android:layout_toEndOf="@+id/w_temp"
android:text="cond"
android:textSize="30dp" />
<TextView
android:id="@+id/w_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/w_temp"
android:layout_marginBottom="-67dp"
android:text="2019"
android:textSize="20dp" />
<TextView
android:id="@+id/w_cityname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/w_weather"
android:layout_marginStart="186dp"
android:layout_marginTop="84dp"
android:layout_toEndOf="@+id/w_date"
android:text="city"
android:textSize="35dp" />
请让我知道我在哪里犯了错误。 我没有头绪。因为它没有给出错误信息。
【问题讨论】:
标签: java android json parsing openweathermap