xutils获取json并解析

这篇文章主要是利用xutils从服务器获取数据,并用gson解析到本地,显示出来。
这里写图片描述

1、 xutils从服务器获取数据原理:

使用方法:

  HttpUtils http=new HttpUtils;
        http.send(HttpRequest.HttpMethod.GET,"url", new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {

            }
            @Override
            public void onFailure(HttpException e, String s) {

            }
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
            }
        });

1、 发送的参数列表 http.send(HttpRequest.HttpMethod.GET,”url”, new RequestCallBack()。
http.send源代码:

public <T> HttpHandler<T> send(HttpMethod method, String url, RequestCallBack<T> callBack) {
        return this.send(method, url, (RequestParams)null, callBack);
    }

看HttpHnadler类可知,发送的请求最终是在httphandler中的doInBackground,也就是开启任务,发送请求给服务器,使用ResponseInfo类接收从网络获取数据。

 protected Void doInBackground(Object... params) {

2 、 RequestCallBack()源代码如下:抽象类RequestCallBack中的两个抽象方法,分别是成功和失败的回调。成功接收的参数即是从服务器获取的数据ResponseInfo,失败后传入的参数为异常类,打印异常信息。

public abstract class RequestCallBack<T> {
    private static final int DEFAULT_RATE = 1000;
    private static final int MIN_RATE = 200;
    private String requestUrl;
    protected Object userTag;
    private int rate;
    public RequestCallBack() {
        this.rate = 1000;
    }
   public RequestCallBack(int rate, Object userTag) {
        this.rate = rate;
        this.userTag = userTag;
    }
    public void setUserTag(Object userTag) {
        this.userTag = userTag;
    }
    public void onStart() {
    }
    public void onCancelled() {
    }
    public void onLoading(long total, long current, boolean isUploading) {
    }
    public abstract void onSuccess(ResponseInfo<T> var1);
    public abstract void onFailure(HttpException var1, String var2);
}
2、 gson : 使用gson要定义bean类,并且类中定义的名称要和json解析数据的名称相同。

Demo中代码如下:
MainActivity中的代码:

public class MainActivity extends Activity {
    //获取天气的url:http://m.weather.com.cn/atad/101010100.html
    private String url = "https://api.douban.com/v2/book/1220562";
    private TextView tv_tag;
    private ListView listview;
    private MyAdapter adapter;
    private ArrayList<Tag> list;
    private TextView tv_title;
    private TextView tv_price;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // tv_tag=(TextView) findViewById(R.id.tv_tag);
        listview = (ListView) findViewById(R.id.listview);
        tv_title=(TextView) findViewById(R.id.tv_title);
        tv_price=(TextView) findViewById(R.id.tv_price);
        list = new ArrayList<Tag>();
        //初始化数据;
        getData();
        adapter = new MyAdapter(this, list);
        listview.setAdapter(adapter);
    }
    private void getData() {
        // TODO Auto-generated method stub
        HttpUtils http=new HttpUtils();
        http.send(HttpMethod.GET, url, new RequestCallBack<String>() {
           //加载失败的时候;
            @Override
            public void onFailure(HttpException e, String s) {
                // TODO Auto-generated method stub  
            }
           //加载成功;
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                // TODO Auto-generated method stub
                dealData(responseInfo.result);
                System.out.println("---"+responseInfo.result);
            }
            //正在加载的时候显示;可以显示百分比;也可以弹出对话框之类的提示;
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                // TODO Auto-generated method stub
                super.onLoading(total, current, isUploading);
            }
        });
    }
    private void dealData(String result) {
        //gson在解析的时候,{}代码对象;【】代表集合;
        Gson gson = new Gson();
        //json中所有的数据已经返回到book实体中;
        Book book = gson.fromJson(result, Book.class);
        Log.i("info", book.getTitle() + ":" + book.getPublisher() + ":"
                + book.getTags().size());
        tv_title.setText("书名:"+book.getTitle());
        tv_price.setText("价格:"+book.getPrice());
        list = book.getTags();
        //list集合加入数据后刷新adapter;不刷新则获取不到数据;
        adapter.refreshData(list);
    }

}

2在适配器中的代码如下:

public class MyAdapter extends BaseAdapter{
    private ArrayList<Tag> list;
    private Context context;
    public MyAdapter(Context context,ArrayList<Tag> list){
       this.context=context;
       this.list=list;
    }
    //刷新list列表中的adapter;
    public void refreshData(ArrayList<Tag> list) {
           this.list=list;
           notifyDataSetChanged();
        }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();

    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        // TODO Auto-generated method stub
        ViewHolder vh;
        if(convertView==null){
            vh=new ViewHolder();
            convertView=LayoutInflater.from(context).inflate(R.layout.item, null);
            vh.tv_count=(TextView) convertView.findViewById(R.id.tv_count);
            vh.tv_title=(TextView) convertView.findViewById(R.id.tv_title);
            convertView.setTag(vh); 
        }else{
            vh=(ViewHolder) convertView.getTag();
        }
    vh.tv_count.setText(list.get(position).getCount());
        vh.tv_title.setText(list.get(position).getTitle());
        return convertView;
    }
    static final class ViewHolder{
        TextView tv_count;
        TextView tv_title;
    }

Demo下载地址eclipse版
http://download.csdn.net/detail/androidxiaogang/9204873

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值