以下是通过输入城市名称或地名来查找天气的代码。结果是来自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&lt;&gt;扩展的类的名称。并有方法doInBackground和onPostExecute()..请帮助我为什么结果String返回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();
}
}
});
答案 0 :(得分:0)
请在编写任何Java代码之前测试您的API 。
您的网址中有一个结尾\n
。
只需打开代码中的实际网址,或者cURL it ...
curl 'http://api.openweathermap.org/data/2.5/weather?q=San%20Antonio&appid=cd66504ca815ddc1971662a9f2147f84\n' | jq
{
"cod": 401,
"message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."
}
删除最后的\n
{
"coord": {
"lon": -98.49,
"lat": 29.42
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 288.15,
"pressure": 1023,
"humidity": 27,
"temp_min": 285.15,
"temp_max": 291.15
},
"visibility": 16093,
"wind": {
"speed": 3.6,
"deg": 30
},
"clouds": {
"all": 1
},
"dt": 1488423180,
"sys": {
"type": 1,
"id": 2713,
"message": 0.0075,
"country": "US",
"sunrise": 1488459476,
"sunset": 1488501264
},
"id": 4726206,
"name": "San Antonio",
"cod": 200
}
答案 1 :(得分:0)
我发现您的代码几乎没有问题。试试这个。
String message = "";
JSONObject jsonObject = new JSONObject(result);
JSONArray arr = jsonObject.optJSONArray("weather");
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.optJSONObject(i);
String main = jsonPart.optString("main");
String description = jsonPart.optString("description");
if (!TextUtils.isEmpty(main) && !TextUtils.isEmpty(description)) {
message += main + ": " + description + "\r\n";
}
}
if (!TextUtils.isEmpty(message)) {
weatherReport.setText(message);
} else {
Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();
}