【发布时间】:2016-12-19 21:10:18
【问题描述】:
我正在尝试在 android studio 中构建一个非常基本的天气应用程序。我正在使用 AsyncClass 返回多个字符串。
正如您在代码中看到的,我使用了一个名为“Wrapper”的类来存储我的字符串,因此我可以只返回一个类对象并在 AsyncTask 的 onPostExecute 方法中使用它。我面临的问题是,当我测试应用程序时,所有返回的字符串都以某种方式未定义(Wrapper 类的默认值)。这意味着字符串没有在 doInBackground 方法中更新,我似乎无法弄清楚为什么!
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
}
private class Wrapper
{
String Temperature = "UNDEFINED";
String city = "UNDEFINED";
String country = "UNDEFINED";
}
private class GetWeatherTask extends AsyncTask<String, Void, Wrapper> {
private TextView textView;
public GetWeatherTask(TextView textView) {
this.textView = textView;
}
@Override
protected Wrapper doInBackground(String... strings) {
Wrapper w = new Wrapper();
String Temperature = "x";
String city = "y";
String country = "z";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
JSONObject topLevel = new JSONObject(builder.toString());
JSONObject main = topLevel.getJSONObject("main");
JSONObject cityobj = topLevel.getJSONObject("city");
Temperature = String.valueOf(main.getDouble("temp"));
city = cityobj.getString("name");
country = cityobj.getString("country");
w.Temperature= Temperature;
w.city= city;
w.country=country;
urlConnection.disconnect();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return w;
}
@Override
protected void onPostExecute(Wrapper w) {
textView.setText("Current Temperature: " + w.Temperature + " C" + (char) 0x00B0
+"\n" + "Current Location: "+ w.country +"\n" + "City: "+ w.city );
}
}
}
更新:
原来我在代码中使用了错误的 url,我使用的是: http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s
我应该一直在使用:
http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=%s&appid=%s
-我应该使用天气预报而不是天气
【问题讨论】:
-
抱歉,现在编辑
-
在捕获块中输入
return null;。在onPostExecute()使用之前检查w==null是否。 -
现在会这样做并更新您
-
做了一个简单的 if else
-
您应该首先检查您从服务器返回的内容。如果它是有效的 json。所以检查
builder.toString()的值。
标签: java android android-asynctask