GreenDao,注解,RecyclerView,EventBus,Retrofit展示列表


添加依赖

//BottomTabBar
compile 'com.hjm:BottomTabBar:1.1.1'

//黄油刀
compile 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//recyclerview
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'

//Eventbus
compile 'org.greenrobot:eventbus:3.1.1'

//Retrofit
compile 'com.squareup.retrofit2:retrofit:2.3.0'//retrofit依赖
//compile 'com.squareup.retrofit2:converter-scalars:2.1.0 '//场景是这样,服务端返回一个不定类型的json数据,无法确定映射的Gson对象。
compile 'com.squareup.retrofit2:converter-gson:2.1.0'//retrofit内部封装的GSON
//compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'//log

//fresco
compile 'com.facebook.fresco:fresco:0.12.0'
//  API < 14 上的机器支持 WebP 时,需要添加
compile 'com.facebook.fresco:animated-base-support:0.12.0'
// 支持 WebP (静态图+动图),需要添加
compile 'com.facebook.fresco:animated-webp:0.12.0'
compile 'com.facebook.fresco:webpsupport:0.12.0'

// greendao依赖
compile 'org.greenrobot:greendao:3.2.2'


// 应用插件
apply plugin: 'org.greenrobot.greendao'
//
greendao {
    schemaVersion 1
    daoPackage 'com.bwei.heqi20171202mnlx.gen'
    targetGenDir 'src/main/java'
}

主project
buildscript {
    repositories {
        jcenter()
        mavenCentral()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

布局

activity_main

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

    <com.hjm.bottomtabbar.BottomTabBar
        android:id="@+id/bottom_tab_bar"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </com.hjm.bottomtabbar.BottomTabBar>
</LinearLayout>

home_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>

</LinearLayout>

other_frag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_height="match_parent"
        android:layout_width="match_parent"/>

</LinearLayout>

rv_list.xml RecyclerView的子布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/desc_tv"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"/>

    <TextView
        android:id="@+id/publishedAt_tv"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_marginTop="10dp"/>
</LinearLayout>




MainActivity

import android.app.usage.UsageEvents;
import android.graphics.Color;
import android.support.annotation.BoolRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.bwei.heqi20171202mnlx.fragment.Home;
import com.bwei.heqi20171202mnlx.fragment.Other2;
import com.bwei.heqi20171202mnlx.utils.NetUtils;
import com.hjm.bottomtabbar.BottomTabBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //黄油刀
        ButterKnife.bind(this);
        //注册EventBus
        EventBus.getDefault().register(this);

        int netype = new NetUtils().getNetype(this);
        if(netype==1||netype==2){
            EventBus.getDefault().post("成功");
        }else if(netype==-1){
            EventBus.getDefault().post("失败");
        }

        bottomTabBar.init(getSupportFragmentManager())
                .setImgSize(60,60)
                .setFontSize(12)
                .setTabPadding(4,6,10)
                .setChangeColor(Color.RED,Color.DKGRAY)
                .addTabItem("首页",R.mipmap.ic_launcher, Home.class)
                .addTabItem("想法",R.mipmap.ic_launcher, Other2.class)
                .addTabItem("市场",R.mipmap.ic_launcher, Other2.class)
                .addTabItem("通知",R.mipmap.ic_launcher, Other2.class)
                .addTabItem("更多",R.mipmap.ic_launcher, Other2.class)
                .isShowDivider(false)
                .setOnTabChangeListener(new BottomTabBar.OnTabChangeListener() {
                    @Override
                    public void onTabChange(int position, String name) {

                    }
                });

    }

    @Subscribe
    public void onEventMainThread(Object event) {
        Toast.makeText(this,event+"",Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}


utils包
NetUtils
import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

/**
 * Created by HQ on 2017/12/2.
 */

public class NetUtils {
    public int getNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        //无网络
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        //手机网络
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 2;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {//wifi网络
            netType = 1;
        }
        //返回
        return netType;
    }

}


DBUtils类

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.bwei.heqi20171202mnlx.gen.DaoMaster;
import com.bwei.heqi20171202mnlx.gen.DaoSession;
import com.bwei.heqi20171202mnlx.gen.ResultsBeanDao;

/**
 * Created by HQ on 2017/12/2.
 */

public class DButils {
    private static volatile DButils instance;
    private final ResultsBeanDao dao;

    private DButils(Context context){
      /* dao =new DaoMaster(new DaoMaster.DevOpenHelper(context,"msg",null)
                .getWritableDatabase())
               .newSession()
               .getResultsBeanDao();*/

        //初始化数据库的一些配置
        DaoMaster.DevOpenHelper mHelper =new DaoMaster.DevOpenHelper(context,"msg",null);
        //获取数据库操作对象
        SQLiteDatabase db = mHelper.getWritableDatabase();
        // 获取DaoMaster对象
        DaoMaster daoMaster = new DaoMaster(db);
        //获取DaoSession对象
        DaoSession daoSession = daoMaster.newSession();
        //拿到要操作的对象
        dao = daoSession.getResultsBeanDao();

    }
    public static DButils getInstance(Context context) {
        if (instance == null) {
            synchronized (DButils.class) {
                if (instance == null) {
                    instance = new DButils(context);
                }
            }
        }
        return instance;
    }
    public ResultsBeanDao getDao(){
        if(dao!=null){
            return dao;
        }
        return null;
    }

}

RetrofitUtils类

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by HQ on 2017/12/2.
 */

public class RetrofitUtils {
    private static volatile RetrofitUtils instance;
    private final Retrofit build;

    private RetrofitUtils(String baseUrl){
        build = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(baseUrl)
                .build();
    }
    public static RetrofitUtils getInstance(String baseUrl){
        if(instance==null){
            synchronized (RetrofitUtils.class) {
                if (instance == null) {
                    instance=new RetrofitUtils(baseUrl);
                }
            }
        }
        return instance;
    }

    public Retrofit getBuild(){
        return build;
    }
    public <T> T getCreate(Class<T> cls){
        return build.create(cls);
    }

}
 

fragment包

Home类

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bwei.heqi20171202mnlx.AdapterRv;
import com.bwei.heqi20171202mnlx.R;
import com.bwei.heqi20171202mnlx.bean.MessageBean;
import com.bwei.heqi20171202mnlx.bean.ResultsBean;
import com.bwei.heqi20171202mnlx.gen.ResultsBeanDao;
import com.bwei.heqi20171202mnlx.interfaces.IServiceApi;
import com.bwei.heqi20171202mnlx.utils.DButils;
import com.bwei.heqi20171202mnlx.utils.RetrofitUtils;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by HQ on 2017/12/2.
 */

public class Home extends Fragment{

    private View view;

    private ResultsBeanDao dao;
    private IServiceApi serviceApi;
    private List<ResultsBean> list = new ArrayList<>();
    private AdapterRv adapterRv;
    private RecyclerView rv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_frag, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //获取控件
        rv = (RecyclerView) view.findViewById(R.id.rv);
        //获取数据库操作对象

        //通过单例模式获取代理对象



        //list=getDataFromDB();
        //Log.e("TAG", list.size()+"");
        adapterRv = new AdapterRv(getActivity(), list);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rv.setLayoutManager(manager);
        rv.setAdapter(adapterRv);
        if (list==null||list.size()==0){
            Log.e("-------","内存无数据");
            dao = DButils.getInstance(getActivity()).getDao();
            List<ResultsBean> dataFromDB = getDataFromDB();
            list.addAll(dataFromDB);
            if (list==null||list.size()==0){
                Log.e("-------","数据库无数据");
                serviceApi = RetrofitUtils.getInstance("http://gank.io/").getCreate(IServiceApi.class);
                getNetResult();
            }
        }

    }
        public void getNetResult(){
            Log.e("lll","开始请求网络");
        Call<MessageBean> call = serviceApi.getResults("10", "1");
            call.enqueue(new Callback<MessageBean>() {
                @Override
                public void onResponse(Call<MessageBean> call, Response<MessageBean> response) {

                    List<ResultsBean> results = response.body().getResults();
                    for (ResultsBean r:results) {
                        dao.insert(new ResultsBean(r.get_id(),r.getCreatedAt(),r.getDesc(),
                                r.getPublishedAt(),r.getSource(),r.getType(),r.getUrl(),r.getUsed(),r.getWho()));

                    }


                    list.addAll(getDataFromDB());
                    //list = getDataFromDB();
                    adapterRv.notifyDataSetChanged();
                }

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

                }
            });

        }
    private List<ResultsBean> getDataFromDB(){
        //查询所有数据
        List<ResultsBean> resultsBeen = dao.loadAll();
        return resultsBeen;
    }
}


bean包

MessageBean类

import java.util.List;

/**
 * Created by HQ on 2017/12/2.
 */

public class MessageBean {
    private boolean error;
    private List<ResultsBean> results;

    public boolean isError() {
        return error;
    }

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

    public List<ResultsBean> getResults() {
        return results;
    }

    public void setResults(List<ResultsBean> results) {
        this.results = results;
    }
}

ResultsBean类

点击Build下的Make Module自动生成
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;

/**
 * Created by HQ on 2017/12/2.
 */
@Entity
public class ResultsBean {
    @Id
    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 getWho() {
        return this.who;
    }
    public void setWho(String who) {
        this.who = who;
    }
    public boolean getUsed() {
        return this.used;
    }
    public void setUsed(boolean used) {
        this.used = used;
    }
    public String getUrl() {
        return this.url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getType() {
        return this.type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getSource() {
        return this.source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    public String getPublishedAt() {
        return this.publishedAt;
    }
    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }
    public String getDesc() {
        return this.desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public String getCreatedAt() {
        return this.createdAt;
    }
    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }
    public String get_id() {
        return this._id;
    }
    public void set_id(String _id) {
        this._id = _id;
    }
    @Generated(hash = 1208044492)
    public ResultsBean(String _id, String createdAt, String desc,
            String publishedAt, String source, String type, String url,
            boolean used, String who) {
        this._id = _id;
        this.createdAt = createdAt;
        this.desc = desc;
        this.publishedAt = publishedAt;
        this.source = source;
        this.type = type;
        this.url = url;
        this.used = used;
        this.who = who;
    }
    @Generated(hash = 1822271928)
    public ResultsBean() {
    }
   
}
 
interfaces包
IServiceApi接口类

import com.bwei.heqi20171202mnlx.bean.MessageBean;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

/**
 * Created by HQ on 2017/12/2.
 */

public interface IServiceApi {

    @GET("api/data/Android/{num}/{page}")
    Call<MessageBean> getResults(@Path("num")String num, @Path("page") String page);

}


Adapter类

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.bwei.heqi20171202mnlx.bean.ResultsBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HQ on 2017/12/2.
 */

public class AdapterRv extends RecyclerView.Adapter<AdapterRv.ViewHolder>{
    private Context context;
    private List<ResultsBean> list= new ArrayList<>();

    public AdapterRv(Context context, List<ResultsBean> list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        holder.descTv.setText(list.get(position).getDesc());
        holder.publishedAtTv.setText(list.get(position).getPublishedAt());
    }

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

    class ViewHolder extends RecyclerView.ViewHolder{

        TextView descTv;
        TextView publishedAtTv;

        public ViewHolder(View itemView) {
            super(itemView);
            descTv=(TextView)itemView.findViewById(R.id.desc_tv);
            publishedAtTv=(TextView)itemView.findViewById(R.id.publishedAt_tv);
//            ButterKnife.bind(context, itemView)
        }
    }
}


 

 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值