您的位置:首页 > 其它

自己实现简单的天气预报应用(3)

2015-03-04 12:28 162 查看
3.从获取的json数据中解析出数据并保存到一个ArrayList中

代码如下:(参考官方docs下的org.json API)

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;

public class ParseTools {

private static ArrayList<WeatherItem> mWeatherItems=new ArrayList<>();

public static ArrayList<WeatherItem> getInstance(String jsonData) throws  JSONException{
JSONObject object = (JSONObject) new JSONTokener(jsonData).nextValue();
JSONArray allData = object.getJSONArray("result");
for(int i=0;i<allData.length();++i){
WeatherItem witem=new WeatherItem();
JSONObject item=allData.getJSONObject(i);
witem.setDate(item.getString("days"));
witem.setWeek(item.getString("week"));
witem.setTemp_low(Integer.parseInt(item.getString("temp_low")));
witem.setTemp_high(Integer.parseInt(item.getString("temp_high")));
witem.setHumi_low(Integer.parseInt(item.getString("humi_low")));
witem.setHumi_high(Integer.parseInt(item.getString("humi_high")));
witem.setWeather(item.getString("weather"));
witem.setWinp(item.getString("winp"));
witem.setWind(item.getString("wind"));
mWeatherItems.add(witem);
}
return mWeatherItems;
}
}


然后回到网络请求部分,代码稍微修改如下:

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {

private ArrayList<WeatherItem> mWeatherItems=new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String url="http://api.k780.com:88/?app=weather.future&weaid=101270101&appkey=13217&sign=efb0ccae3443e25fe2238e5bb2f83bba&format=json";
RequestQueue mQueue= Volley.newRequestQueue(getApplicationContext());
mQueue.add(new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
//这里的响应可能较晚,因此这里返回的数据可能会在整个OnCreate完成之后,因此在这里获取的数据无法立即使用
try {
mWeatherItems = ParseTools.getInstance(jsonObject.toString());
Log.i("TAG","size : "+mWeatherItems.size());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_SHORT).show();
}
}));
mQueue.start();
}
}


这里出现的问题是,当start()被调用的时候,网络请求处理是在新的线程中进行的,因此,UIThread还是会继续执行,此时出现的问题就是在处理请求完之前,onResponse()是这个方法是不会被调用的,因此在此之前所有使用mWeatherItems的地方得到的mWeatherItems的大小都是0,也就是没有得到响应数据之前的状态。

下一阶段考虑解决以上问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: