XUtils获取网络数据

XUtils简介:

xUtils是基于Afinal开发的目前功能比较完善的一个Android开源框架,官网:https://github.com/wyouflf/xUtils3
xUtils 包含了orm, http(s), image, view注解, 但依然很轻量级(246K), 并且特性强大, 方便扩展:
稳定的基石: AbsTask和统一的回调接口Callback, 任何异常, 即使你的回调方法实现有异常都会进入onError, 任何情况下onFinished总会让你知道任务结束了.
基于高效稳定的orm工具, http模块得以更方便的实现cookie(支持domain, path, expiry等特性)和 缓存(支持Cache-Control, Last-Modified, ETag等特性)的支持.
有了强大的http及其下载缓存的支持, image模块的实现相当的简洁, 并且支持回收被view持有, 但被Mem Cache移除的图片, 减少页面回退时的闪烁…
view注解模块仅仅400多行代码却灵活的支持了各种View注入和事件绑定, 包括拥有多了方法的listener的支持.

特点:

  • 更全面的http请求协议支持(11种谓词)
  • 支持超大文件(超过2G)上传
  • 拥有更加灵活的ORM, 和greenDao一致的性能
  • 更多的事件注解支持且不受混淆影响…
  • 图片绑定支持gif(受系统兼容性影响, 部分gif文件只能静态显示), webp; 支持圆角, 圆形, 方形等裁剪, 支持自动旋转…
  • 从3.5.0开始不再包含libwebpbackport.so, 需要在Android4.2以下设备兼容webp的请使用3.4.0版本
xutils主要有4个模块:注解模块,网络模块,图片加载模块,数据库模块。

导入依赖:

implementation ‘org.xutils:xutils:3.5.0’

java代码:

package com.example.work_day01;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.table.DbBase;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.net.URLEncoder;
import java.util.ArrayList;

@ContentView(R.layout.activity_work_01)
public class work_01 extends AppCompatActivity {
    private final String URL_1 = "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1";
    private ArrayList<FoodBean> foods;
    @ViewInject(R.id.lv)
    private ListView lv;
    private ListViewAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
    }
    @Event(value = {R.id.btn_1,R.id.btn_get,R.id.writeToDB},type = View.OnClickListener.class)
    private void MyOnClick_btn(View view){
        switch(view.getId()){
            case R.id.btn_1:
                Toast.makeText(this, "按钮一", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_get:
                toHTTPbyGet();
                break;
            case R.id.writeToDB:
                writeToDadaBase();
                break;
        }
    }

    /**
     * 操作数据库的方法
     */
    private void writeToDadaBase() {
        DbManager.DaoConfig config = new DbManager.DaoConfig();
        config.setDbName("work01.db");
        config.setDbVersion(1);
        DbManager manager = x.getDb(config);
        for(int i = 0;i < foods.size();i++){
            MyDatabaseBean bean = new MyDatabaseBean();
            bean.setId(i+1);
            bean.setName(foods.get(i).getName());
            bean.setPic(foods.get(i).getPic());
            try {
                manager.save(bean);
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
        Toast.makeText(this, "存储完毕!!!", Toast.LENGTH_SHORT).show();
    }

    private void toHTTPbyGet() {
        RequestParams params = new RequestParams(URL_1);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
//                Log.e("###json",result);
                toGetJson(result);//解析字符串 拿取数据
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("###error","访问出错!!!");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void toGetJson(String result) {
        foods = new ArrayList<>();
        //解析字符串
        try {
            JSONObject object = new JSONObject(result);
            JSONArray data = object.getJSONArray("data");
            for(int i = 0; i < data.length();i++){
                Log.e("###i",i+"");
                FoodBean foodBean = new FoodBean();
                String title = data.getJSONObject(i).getString("title");
                String pic = data.getJSONObject(i).getString("pic");
                foodBean.setName(title);
                foodBean.setPic(pic);
                Log.e("###pic",pic);
                foods.add(foodBean);
            }
            Message message = Message.obtain();
            message.what = 1;
            handler.sendMessage(message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e("###what",msg.what+"");
            if(msg.what == 1){
                adapter = new ListViewAdapter(work_01.this,foods);
                lv.setAdapter(adapter);
            }
        }
    };
}

适配器类:

package com.example.work_day01;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ContentView;
import org.xutils.x;

import java.util.ArrayList;

public class ListViewAdapter extends BaseAdapter {

    Context context;
    ArrayList<FoodBean> foods;

    public ListViewAdapter(Context context, ArrayList<FoodBean> foods) {
        this.context = context;
        this.foods = foods;
    }

    @Override
    public int getCount() {
        if(foods == null){
            return 0;
        }
        return foods.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        MyViewHolder holder = null;
        if(convertView == null){
            convertView = View.inflate(context,R.layout.item_1,null);
            holder = new MyViewHolder();
            holder.imageView = convertView.findViewById(R.id.img);
            holder.textView = convertView.findViewById(R.id.title_me);
            convertView.setTag(holder);
        }else{
            holder = (MyViewHolder)convertView.getTag();
        }

        if(holder != null){
            ImageOptions options = new ImageOptions.Builder().setFadeIn(true).build();
            x.image().bind(holder.imageView,foods.get(position).getPic(),options);
            holder.textView.setText(foods.get(position).getName());
        }

        return convertView;
    }

    public class MyViewHolder{
        ImageView imageView;
        TextView textView;
    }

}

bean类:

package com.example.work_day01;

public class FoodBean {
    private String name;
    private String pic;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }
}

效果图:

在这里插入图片描述
详细细节网址https://www.cnblogs.com/favour/p/6936385.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值