Retrofit+GreenDao请求数据保存数据库

//本篇文章只供参考和学习greendao的使用和retrofit的网络请求判断在没网的时候从数据库读取展示数据

//recyclerview适配器
public class MyAdapter extends RecyclerView.Adapter {


    private Context context;
    private List list;

    public MyAdapter(Context context, List list) {
        this.context = context;
        this.list = list;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item, null);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }


    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.tvTitle.setText(list.get(position).getTitle());
        holder.tvTime.setText(list.get(position).getTime());
    }

    @Override
    public int getItemCount() {
        return list.size();
    }


    class ViewHolder extends RecyclerView.ViewHolder{
        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.tv_time)
        TextView tvTime;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}


//创建数据库
@Entity
public class CateGory {
    @Id
    private Long id;
    private String title;
    private String time;
    //这些是你创建数据库的字段这些创建完直接点Build>>MakeModel就能生成根类在使用greendao的时候到依赖问题
    
}

//泛型类
public class OneBean<T> {
    private boolean error;
    private T results;


    public boolean isError() {
        return error;
    }

    public void setError(boolean error) {
        this.error = error;
    }

    public T getResults() {
        return results;
    }

    public void setResults(T results) {
        this.results = results;
    }
}

//请求的接口bean类
public class MyBean2 {
    private String _id;
    private String createdAt;
    private String desc;
    private String publishedAt;
    private String source;
    private String type;
    private String url;
    private boolean used;
    private String who;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public boolean isUsed() {
        return used;
    }

    public void setUsed(boolean used) {
        this.used = used;
    }

    public String getWho() {
        return who;
    }

    public void setWho(String who) {
        this.who = who;
    }
}
//主页的业务显示判断网络等等
public class HomeFragment extends Fragment {


    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    Unbinder unbinder;
    private View view;
    private List list;
    private MyAdapter radapter;
    private CateGoryDao dao;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.home, container, false);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dao= DbHelperUtils.getInstance(getActivity()).getCategoryDao();

        list=new ArrayList();
        radapter=new MyAdapter(getActivity(),list);
        recyclerview.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
        LinearLayoutManager manager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        recyclerview.setLayoutManager(manager);
        recyclerview.setAdapter(radapter);


        int netype = InternetUtils.getInstance(getActivity()).getNetype();

        if (netype==-1){
            EventBus.getDefault().post("当前没有网络,需要显示数据库数据");
            getDb();
        }else if (netype==1){
            EventBus.getDefault().post("当前有wifi网络");
            getNetData();
        }else{
            EventBus.getDefault().post("当前手机有网络");
            getNetData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void getDb() {
        List cateGories = dao.loadAll();
        list.addAll(cateGories);
        //刷新适配器
        radapter.notifyDataSetChanged();
    }

    public void getNetData() {
        Retrofit getretrofit = RetrofitUtils.getInstance("http://gank.io/api/").getretrofit();

        RetrofitService retrofitService = getretrofit.create(RetrofitService.class);

        Call>> call = retrofitService.get(10, 1);
        call.enqueue(new Callback>>() {
            @Override
            public void onResponse(Call>> call, Response>> response) {
                OneBean> body = response.body();
                List results = body.getResults();
                dao.deleteAll();
                for(int i=0;ilist.add(new CateGory(null, results.get(i).getDesc(), results.get(i).getCreatedAt()));
                    dao.insert(list.get(i));
                }

                radapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call>> call, Throwable t) {

            }
        });
    }

    //事件总线程
    @Subscribe
    public void onEventMainThread(Object event) {
        Toast.makeText(getActivity(), event + "", Toast.LENGTH_SHORT).show();
    }

    //销毁
    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消注册
        EventBus.getDefault().unregister(this);
    }

}

//拼接接口  如果需要post请求只需要改成@post就可以了
public interface RetrofitService {
    @GET("data/Android/{id1}/{id2}")
    Call>> get(@Path("id1") int id1, @Path("id2") int id2);
}
 //数据库封装
public class DbHelperUtils {
    private static volatile DbHelperUtils instance;
    private final DaoSession daoSession;

    private DbHelperUtils(Context context){
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "user", null);

        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    public static DbHelperUtils getInstance(Context context){
        if (instance==null){
            synchronized (DbHelperUtils.class){
                if (null==instance){
                    instance=new DbHelperUtils(context);
                }
            }
        }
        return instance;
    }
//如果需要换查询的数据库就需要改变CateGoryDao 
public CateGoryDao getCategoryDao(){
    return daoSession.getCateGoryDao();
}
}

//请求网络封装
public class InternetUtils {

    private static volatile InternetUtils instance;
    private Context context;

    private InternetUtils(Context context) {
        this.context = context;
    }

    public static InternetUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (InternetUtils.class) {
                if (instance == null) {
                    instance = new InternetUtils(context);
                }
            }
        }
        return instance;
    }


    public int getNetype() {
        int neType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo == null) {
            return neType;
        }


        int phoneType = networkInfo.getType();
        if (phoneType==ConnectivityManager.TYPE_MOBILE){
            neType=2;
        }else if(phoneType==ConnectivityManager.TYPE_WIFI){
            neType=1;
        }
        return neType;

    }

}

 
//网络请求解析封装
public class RetrofitUtils {
    private static volatile RetrofitUtils instance;
    private final Retrofit retrofit;

    private RetrofitUtils(String baseurl) {
        retrofit=new Retrofit.Builder()
                .baseUrl(baseurl)//Retrofit网络请求再也不用写Gson解析了只需要GsonConverterFactory就行了
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    //简单的同步锁
    public static RetrofitUtils getInstance(String baseurl){
        if (instance==null){
            synchronized (RetrofitUtils.class){
                if (instance==null){
                    instance=new RetrofitUtils(baseurl);
                }
            }
        }
        return instance;
    }
    //返回的是请求到的数据
    public Retrofit getretrofit(){
        return retrofit;
    }
}
//MainActivity主页面只有5分Fragment在这就不一一展出了  每个类继承Fragment动态添加就行了
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.bottomTabBar)
    BottomTabBar bottomTabBar;

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

        bottomTabBar.init(getSupportFragmentManager())
                .setImgSize(25,25)
                .setFontSize(8)
                .setTabPadding(4,6,10)
                .setChangeColor(Color.RED,Color.BLACK)
                .addTabItem("首页",R.drawable.home, HomeFragment.class)
                .addTabItem("想法",R.drawable.home, Xiang.class)
                .addTabItem("市场",R.drawable.home, ShiChang.class)
                .addTabItem("通知",R.drawable.home, Tong.class)
                .addTabItem("更多",R.drawable.home, More.class)
                .isShowDivider(false)
                .setOnTabChangeListener(new BottomTabBar.OnTabChangeListener() {
                    @Override
                    public void onTabChange(int position, String name) {

                    }
                });

    }
}
 //主页面
xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="com.example.renzhijun20171201.MainActivity">


    <com.hjm.bottomtabbar.BottomTabBar
        android:id="@+id/bottomTabBar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">
    com.hjm.bottomtabbar.BottomTabBar>


RelativeLayout>
//item布局
xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/ic_launcher"
        android:id="@+id/imageView" />

    <TextView
        android:id="@+id/tv_title"
        android:textSize="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView" />

    <TextView
        android:id="@+id/tv_time"
        android:textSize="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_title"
        android:layout_toRightOf="@+id/imageView"
        android:layout_toEndOf="@+id/imageView"
        android:layout_marginTop="26dp" />

RelativeLayout>


你可能感兴趣的:(Retrofit+GreenDao请求数据保存数据库)