您好我是android编程的新手我正在制作asynctask来收集JSON数据。但是在调试代码中总是返回false,即使解析了JSON数据。我的代码也无法完成Asynctask和
public class WeatherGPS extends Activity {
ArrayList<Forecast> listItem;
ForecastAdapter adp;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather_gps);
listItem = new ArrayList<Forecast>();
ListView lv = (ListView) findViewById(R.id.listView);
adp = new ForecastAdapter(getApplicationContext(), R.layout.activity_list_item, listItem);
lv.setAdapter(null);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long Id) {
Toast.makeText(getApplicationContext(), listItem.get(position).getText(), Toast.LENGTH_LONG).show();
}
});
new JSONAsyncTask().execute("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog pd;
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(WeatherGPS.this);
pd.setMessage("Please wait");
pd.setTitle("Connecting...");
pd.show();
pd.setCancelable(false);
}
@Override
protected Boolean doInBackground(String... params) {
try {
HttpGet httppost = new HttpGet(params[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse respone = httpclient.execute(httppost);
int status = respone.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = respone.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONObject("query").getJSONObject("results").getJSONObject("channel").getJSONObject("item").getJSONArray("forecast");
for (int i = 0; i < jarray.length(); i++) {
JSONObject obj3 = jarray.getJSONObject(i);
Forecast forecast = new Forecast();
forecast.setCode(obj3.getString("code"));
forecast.setDate(obj3.getString("date"));
forecast.setDay(obj3.getString("day"));
forecast.setHigh(obj3.getString("high"));
forecast.setLow(obj3.getString("low"));
forecast.setText(obj3.getString("text"));
listItem.add(forecast);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pd.cancel();
adp.notifyDataSetChanged();
if (result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from the server", Toast.LENGTH_LONG).show();
}
}
}
}
我没有收到任何logcat错误
11-30 14:19:07.027 8802-8802/? I/art: Not late-enabling -Xcheck:jni (already on)
11-30 14:19:07.027 8802-8802/? I/art: Late-enabling JIT
11-30 14:19:07.027 8802-8802/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-30 14:19:07.104 8802-8802/com.example.weathergps W/System: ClassLoader referenced unknown path: /data/app/com.example.weathergps-2/lib/x86
11-30 14:19:07.302 8802-8830/com.example.weathergps D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-30 14:19:07.400 8802-8830/com.example.weathergps I/OpenGLRenderer: Initialized EGL, version 1.4
11-30 14:19:07.541 8802-8830/com.example.weathergps W/EGL_emulation: eglSurfaceAttrib not implemented
11-30 14:19:07.541 8802-8830/com.example.weathergps W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabea9fc0, error=EGL_SUCCESS
11-30 14:19:07.602 8802-8830/com.example.weathergps W/EGL_emulation: eglSurfaceAttrib not implemented
11-30 14:19:07.602 8802-8830/com.example.weathergps W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabea9fe0, error=EGL_SUCCESS
11-30 14:19:08.040 8802-8830/com.example.weathergps E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb3fd5410
这是我的json数据:
{
"query":{
"count":1,
"created":"2015-11-30T02:06:54Z",
"lang":"en-US",
"results":{
"channel":{
"title":"Yahoo! Weather - Nome, AK",
"link":"http://us.rd.yahoo.com/dailynews/rss/weather/Nome__AK/*http://weather.yahoo.com/forecast/USAK0170_f.html",
"description":"Yahoo! Weather for Nome, AK",
"language":"en-us",
"lastBuildDate":"Sun, 29 Nov 2015 4:54 pm AKST",
"ttl":"60",
"location":{
"city":"Nome",
"country":"United States",
"region":"AK"
},
"units":{
"distance":"mi",
"pressure":"in",
"speed":"mph",
"temperature":"F"
},
"wind":{
"chill":"29",
"direction":"0",
"speed":"0"
},
"atmosphere":{
"humidity":"78",
"pressure":"29.44",
"rising":"0",
"visibility":"6"
},
"astronomy":{
"sunrise":"11:19 am",
"sunset":"4:20 pm"
},
"image":{
"title":"Yahoo! Weather",
"width":"142",
"height":"18",
"link":"http://weather.yahoo.com",
"url":"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
},
"item":{
"title":"Conditions for Nome, AK at 4:54 pm AKST",
"lat":"64.5",
"long":"-165.41",
"link":"http://us.rd.yahoo.com/dailynews/rss/weather/Nome__AK/*http://weather.yahoo.com/forecast/USAK0170_f.html",
"pubDate":"Sun, 29 Nov 2015 4:54 pm AKST",
"condition":{
"code":"14",
"date":"Sun, 29 Nov 2015 4:54 pm AKST",
"temp":"29",
"text":"Light Snow"
},
"description":"\n<img src=\"http://l.yimg.com/a/i/us/we/52/14.gif\"/><br />\n<b>Current Conditions:</b><br />\nLight Snow, 29 F<BR />\n<BR /><b>Forecast:</b><BR />\nSun - Snow. High: 27 Low: 24<br />\nMon - AM Snow Showers. High: 25 Low: 13<br />\nTue - Mostly Sunny. High: 15 Low: 7<br />\nWed - Partly Cloudy. High: 9 Low: 2<br />\nThu - Mostly Cloudy. High: 5 Low: 1<br />\n<br />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Nome__AK/*http://weather.yahoo.com/forecast/USAK0170_f.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>\n",
"forecast":[
{
"code":"16",
"date":"29 Nov 2015",
"day":"Sun",
"high":"27",
"low":"24",
"text":"Snow"
},
{
"code":"14",
"date":"30 Nov 2015",
"day":"Mon",
"high":"25",
"low":"13",
"text":"AM Snow Showers"
},
{
"code":"34",
"date":"1 Dec 2015",
"day":"Tue",
"high":"15",
"low":"7",
"text":"Mostly Sunny"
},
{
"code":"30",
"date":"2 Dec 2015",
"day":"Wed",
"high":"9",
"low":"2",
"text":"Partly Cloudy"
},
{
"code":"28",
"date":"3 Dec 2015",
"day":"Thu",
"high":"5",
"low":"1",
"text":"Mostly Cloudy"
}
],
"guid":{
"isPermaLink":"false",
"content":"USAK0170_2015_12_03_7_00_AKST"
}
}
}
}
}
}
答案 0 :(得分:0)
你是Android开发的新手,可能你在多线程方面学到的第一件事是AsyncTasks
。避免使用它们!它们与活动的生命周期紧密相关,在配置更改时它们表现得非常糟糕。
使用http://square.github.io/retrofit/代替,它可以处理开箱即用的后台API调用。另外,您不需要使用for循环,getString("key");
等手动浏览json响应
您所需要的只是一堆与您的json响应具有相同结构的POJO
这是一个帮助您完成的基本教程:http://www.vogella.com/tutorials/Retrofit/article.html
还有谷歌的Volley库。 希望这会有所帮助。
答案 1 :(得分:0)
如果doInBackground
返回false
,则必须在某处抛出异常,因此我建议您将catch (Exception e)
添加到您的捕获中并从那里缩小错误。