【发布时间】:2017-03-02 02:53:14
【问题描述】:
以下是通过输入城市名称或地名来查找天气的代码。结果是来自doInBackground方法的字符串...但不幸的是它返回null...
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result == null){
Toast.makeText(MainActivity.this,"Place not found",Toast.LENGTH_LONG).show();
}
else{
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
weatherReport.setText(message);
} else {
Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();
}
doInBackground() 方法..
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
//combined the exceptions MalformedURL and IOException to a common to display a toast msg
catch (Exception e) {
e.printStackTrace();
}
return null;
}
下载 url ..DownloadTask 是从 AsyncTask 扩展的类的名称,并具有方法 doInBackground 和 onPostExecute().. 请帮助我了解为什么结果字符串返回 null..
weather.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
//to hide the keyboard after pressing the button
InputMethodManager manager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
manager.hideSoftInputFromInputMethod(weatherInput.getWindowToken(),0);
DownloadTask downloadTask = new DownloadTask();
//used to encode the entered input for url.. for example San Fransisco appears in url
//as San%20Fransisco ... and to enable that we use the encoder...
String encodedCity = URLEncoder.encode(city,"UTF-8");
downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity +
"&appid=cd66504ca815ddc1971662a9f2147f84\n");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
【问题讨论】:
-
您是否检查了来自接口的响应“消息”:“无效的 API 密钥。有关详细信息,请参阅 openweathermap.org/faq#error401。”
-
嗯...你做了
return null;,并且你打印了一个异常,所以也许检查一下logcat -
另外,
main != ""不是 How to compare strings in Java