导入的权限
implementation 'org.greenrobot:eventbus:3.1.1'
implementation 'com.facebook.fresco:fresco:1.13.0'
implementation 'com.jakewharton:butterknife:8.4.0'
annotationProcessor "com.jakewharton:butterknife-compiler:8.4.0"
implementation 'com.squareup.retrofit2:retrofit:2.0.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.android.support:recyclerview-v7:28.+'
implementation 'org.greenrobot:greendao:3.0.1'
implementation 'org.greenrobot:greendao-generator:3.0.0'
implementation 'com.android.support:design:28.0.0'
public class Api {
//http://www.xieast.com/api/news/news.php?page=1
public static final String BSEE_URL=“http://www.xieast.com/api/news/”;
public static final String SHOU=“news.php?page=1”;
}
public interface ApiService {
@GET
Observable shuo(@Url String url);
@GET
Observable nn(@Url String url,@HeaderMap HashMap hashMap);
}
1
public class Aip {
//http://mnews.gw.com.cn/wap/data/news/news/mobile/jbgg/page_1.json
public static final String Base_Url="http://mnews.gw.com.cn/wap/data/news/news/";
public static final String Main_url="mobile/jbgg/page_";
}
2
public interface ApiService {
@GET(Aip.Main_url+"{page}")
Call> getShow(@Path("page") String page);
}
3解析接口中的数据
public class MyBean {
public List data;
public List getData() {
return data;
}
public void setData(List data) {
this.data = data;
}
@Override
public String toString() {
return "MyBean{" +
"data=" + data +
'}';
}
}
另一个类
@Entity
public class DataBean {
@Property(nameInDb = "title")
private String title;
@Override
public String toString() {
return "DataBean{" +
"title='" + title + '\'' +
'}';
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
@Generated(hash = 1538556504)
public DataBean(String title) {
this.title = title;
}
@Generated(hash = 908697775)
public DataBean() {
}
}
1写网络请求
public class RetrofitUtils {
//单例模式
private static RetrofitUtils retrofitUtils;
private RetrofitUtils(){
}
public static RetrofitUtils getInstance(){
if (retrofitUtils==null){
synchronized (RetrofitUtils.class){
if (retrofitUtils==null){
retrofitUtils=new RetrofitUtils();
}
}
}
return retrofitUtils;
}
//获取Retrofit方法
private static Retrofit retrofit;
private static synchronized Retrofit getRetrofit(String BASE_URL){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
//get方法
public T doGet(String BASE_URL,Class apiService){
//获取Retrofit
Retrofit retrofit = getRetrofit(BASE_URL);
//通过Java动态代理的方式获取动态代理对象
T t = retrofit.create(apiService);
return t;
}
}
2用M去请求网络
public class MainModel {
public void getHttpData(String page){
/**
* 网络请求
*/
ApiService apiService= RetrofitUtils.getInstance().doGet(Aip.Base_Url,ApiService.class);
apiService.getShow(page).enqueue(new Callback>() {
@Override
public void onResponse(Call> call, Response> response) {
MyBean myBean = response.body().get(0);
List data=myBean.getData();
if (mainListener!=null){
mainListener.onResult(data);
}
}
@Override
public void onFailure(Call> call, Throwable t) {
}
});
}
/**
* 定义接口
*/
public interface onMainListener{
void onResult(List data);
}
public onMainListener mainListener;
public void setMainListener(onMainListener mainListener){
this.mainListener=mainListener;
}
}
**3用P层去接受M层请求过来的数据传给V层**
把内存泄漏的方法抽基类
public abstract class BasePresenter {
private Reference tReference;
public void attachView(T t){
tReference = new WeakReference<>(t);
}
public void deatchView(){
if (tReference!=null){
tReference.clear();
tReference=null;
}
}
public abstract void onRelated(String page);
}
然后P层调用
public class MainPresenter extends BasePresenter{
private MainModel mainModel;
private MainView mainView;
public MainPresenter(MainView view){
mainView=view;
mainModel=new MainModel();
}
@Override
public void onRelated(String page) {
mainModel.getHttpData(page);
//调用m层接口回调监听 获取数据给view
mainModel.setMainListener(new MainModel.onMainListener() {
@Override
public void onResult(List data) {
mainView.getViewData(data);
}
});
}
}
V层的接口
public interface MainView {
void getViewData(List data);
}
把网络判断工具类抽出来
public class NetWorkUtils {
public static boolean getNetWork(Context context){
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info!=null){
return info.isAvailable();
}
return false;
}
}
数据库的方法
去清单文件注册
public class MyApplication extends Application {
private static MyApplication instance;
private DaoMaster.DevOpenHelper helper;
private SQLiteDatabase db;
private DaoMaster daoMaster;
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
//对象赋值
this.instance=this;
Fresco.initialize(this);
setDataBase();
}
public static MyApplication getInstance(){
return instance;
}
private void setDataBase(){
helper = new DaoMaster.DevOpenHelper(this, "bw_db", null);
db=helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
public DaoSession getDaoSession(){
return daoSession;
}
}
然后去写适配器
public class MyAdapter extends RecyclerView.Adapter{
private Context context;
private List list;
private final static int TYPE_CONTENT=0;//正常内容
private final static int TYPE_FOOTER=1;//下拉刷新
public MyAdapter(Context context,List list){
this.context=context;
this.list=list;
}
@Override
public int getItemViewType(int position) {
/**
* 判断集合长度到最后条目的时候就显示底部条目样式(一个加载进度圈)
*/
if (position==list.size()){
return TYPE_FOOTER;
}
return TYPE_CONTENT;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
/**
* 两种类型控制不同的条目样式
*/
if (i==TYPE_CONTENT){
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, null);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
else {
View view = LayoutInflater.from(context).inflate(R.layout.footer_layout, null);
FooterViewHolder footerViewHolder = new FooterViewHolder(view);
return footerViewHolder;
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
int itemViewType = getItemViewType(i);
//类型为内容时正常赋值
if (itemViewType==TYPE_CONTENT){
MyViewHolder myViewHolder= (MyViewHolder) viewHolder;
myViewHolder.title.setText(list.get(i).getTitle());
}else {
}
}
@Override
public int getItemCount() {
/**
* 因为添加一个底部所以长度加1
*/
return list.size()+1;
}
/**
* 展示条目MyViewHolder
*/
private class MyViewHolder extends RecyclerView.ViewHolder {
private final TextView title;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title_item);
}
}
/**
* 底部FooterViewHolder
*/
public class FooterViewHolder extends RecyclerView.ViewHolder {
private final ContentLoadingProgressBar pb_progress;
public FooterViewHolder(@NonNull View itemView) {
super(itemView);
pb_progress = itemView.findViewById(R.id.pb_progress);
}
}
}
然后写一个控制滑动的类
public abstract class onLoadMoreListener extends RecyclerView.OnScrollListener {
private int countItem;
private int lastItem;
private boolean isScolled = false;//是否可以滑动
private RecyclerView.LayoutManager layoutManager;
/**
* 加载回调方法
* @param countItem 总数量
* @param lastItem 最后显示的position
*/
protected abstract void onLoading(int countItem, int lastItem);
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//拖拽或者惯性滑动时isScolled设置为true
if (newState == SCROLL_STATE_DRAGGING || newState == SCROLL_STATE_SETTLING) {
isScolled = true;
} else {
isScolled = false;
}
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (recyclerView.getLayoutManager() instanceof LinearLayoutManager){
layoutManager = recyclerView.getLayoutManager();
countItem= layoutManager.getItemCount();
lastItem=((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();
}if (isScolled&&countItem!=lastItem&&lastItem==countItem-1){
onLoading(countItem,lastItem);
}
}
}
然后创建一个activity 抽基类
public abstract class BaseActivity extends AppCompatActivity {
public T presenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayout());
initView();
presenter=getPresenter();
presenter.attachView(presenter);
initData();
}
protected abstract void initData();
protected abstract T getPresenter();
protected abstract void initView();
public abstract int getLayout();
@Override
protected void onDestroy() {
super.onDestroy();
presenter.deatchView();
}
}
完善MainActivity
public class MainActivity extends BaseActivity implements MainView {
@BindView(R.id.swiperefreshlayout)
SwipeRefreshLayout swiperefreshlayout;
@BindView(R.id.rlv)
RecyclerView rlv;
private boolean netWork;
private DataBeanDao dataBeanDao;
private int page=1;
private Handler handler=new Handler();
private List list;
//布局
@Override
public int getLayout() {
return R.layout.activity_main;
}
@Override
protected void initView() {
//绑定ButterKnife
ButterKnife.bind(this);
//设置
rlv.setLayoutManager(new LinearLayoutManager(this));
rlv.addItemDecoration(new DividerItemDecoration(this, OrientationHelper.VERTICAL));
//网络判断
netWork = NetWorkUtils.getNetWork(this);
//实例Dao
dataBeanDao = MyApplication.getInstance().getDaoSession().getDataBeanDao();
}
@Override
protected MainPresenter getPresenter() {
//实例化P
presenter = new MainPresenter(this);
return presenter;
}
@Override
protected void initData() {
/**
* 下拉刷新
*/
swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (netWork){
page=1;
presenter.onRelated(page+".json");
handler.postDelayed(new Runnable() {
@Override
public void run() {
swiperefreshlayout.setRefreshing(false);
}
},3000);
}else {
//没网吐司圆圈转1s
Toast.makeText(MainActivity.this,"当前无网络",Toast.LENGTH_SHORT).show();
handler.postDelayed(new Runnable() {
@Override
public void run() {
swiperefreshlayout.setRefreshing(false);
}
},1000);
}
}
});
/**
* 上拉加载
*/
rlv.addOnScrollListener(new onLoadMoreListener() {
@Override
protected void onLoading(int countItem, int lastItem) {
if (netWork){
page++;
presenter.onRelated(page+".json");
handler.postDelayed(new Runnable() {
@Override
public void run() {
swiperefreshlayout.setRefreshing(false);
}
},3000);
}else {
//没网吐司圆圈转1s
Toast.makeText(MainActivity.this,"当前无网络",Toast.LENGTH_SHORT).show();
swiperefreshlayout.setRefreshing(false);
}
}
});
if (netWork){
//有网网络默认请求
presenter.onRelated(page+".json");
}else {
/**
* 查询 判断有没有数据
*/
List list=dataBeanDao.loadAll();
if (list.size()!=0){
MyAdapter myAdapter = new MyAdapter(MainActivity.this, list);
rlv.setAdapter(myAdapter);
}
}
}
@Override
public void getViewData(List data) {
if (page==1){
list=new ArrayList<>();
/**
* 先清空
* 在添加
*/
dataBeanDao.deleteAll();
for (int i=0;i
ManActivity布局
条目的布局
然后是加载时圈圈的布局哈哈