apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' // apply plugin android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "com.example.refitgreendao" minSdkVersion 15 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } greendao { targetGenDir 'src/main/java' daoPackage 'com.example.refitgreendao.dao' schemaVersion 1 } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'org.greenrobot:greendao:3.2.2' compile 'com.android.support:recyclerview-v7:26.0.0-alpha1' // add library compile 'com.jakewharton:butterknife:8.0.1' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'org.greenrobot:eventbus:3.1.1' compile 'com.facebook.fresco:fresco:1.5.0'}
以上是依赖
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context="com.example.refitgreendao.MainActivity"> <android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/recycleview"/> </LinearLayout>以上是首页的布局<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:orientation="horizontal" android:layout_height="wrap_content"> <com.facebook.drawee.view.SimpleDraweeView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/adapter_simpledraweeview"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/adapter_textview"/> </LinearLayout>这个是item的布局package com.example.muhanxi.myapplication.view;
import com.example.muhanxi.myapplication.Bean;
/**
* Created by muhanxi on 17/12/1.
*/
public interface IMainView {
public void onSuccess(Bean bean);
public void onFailure(Exception e);
}以上是mvp中的v层
package com.example.muhanxi.myapplication;
import android.app.Application;
import com.example.muhanxi.myapplication.dao.DaoMaster;
import com.example.muhanxi.myapplication.dao.DaoSession;
import com.facebook.drawee.backends.pipeline.Fresco;
import org.greenrobot.greendao.database.Database;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by muhanxi on 17/12/1.
*/
public class IApplication extends Application {
public static IGetDataBase iGetDataBase;
public static DaoSession session;
@Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://v.juhe.cn")
.addConverterFactory(GsonConverterFactory.create())
.build();
iGetDataBase = retrofit.create(IGetDataBase.class);
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"test");
Database database = helper.getWritableDb();
session = new DaoMaster(database).newSession();
}
}package com.example.muhanxi.myapplication.model;
/**
* Created by muhanxi on 17/12/1.
*/
public interface MainModel {
}以上是MVP中的m层
package com.example.muhanxi.myapplication.model;
import com.example.muhanxi.myapplication.Bean;
/**
* Created by muhanxi on 17/12/1.
*/
public interface ModelCallBack {
public void onSuccess(Bean bean);
public void onFailure(Exception e);
}
以上是mvp中的mpackage com.example.muhanxi.myapplication.model;
import com.example.muhanxi.myapplication.Bean;
import com.example.muhanxi.myapplication.IApplication;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by muhanxi on 17/12/1.
*/
public class MainModelImpl {
/**
* get 请求
* @param callBack
*/
public void getData(final ModelCallBack callBack){
Call<Bean> call = IApplication.iGetDataBase.get("88f7bbc507e3ecacfaeab2b47dd8936f");
call.enqueue(new Callback<Bean>() {
@Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
Bean bean = response.body();
callBack.onSuccess(bean);
// 保存到数据库
IApplication.session.getListBeanDao().insertInTx(bean.getResult().getList());
}
@Override
public void onFailure(Call<Bean> call, Throwable t) {
callBack.onFailure(new Exception(""));
}
});
}
/**
* post 请求
*/
public void postData(final ModelCallBack callBack){
Call<Bean> call = IApplication.iGetDataBase.post("88f7bbc507e3ecacfaeab2b47dd8936f");
call.enqueue(new Callback<Bean>() {
@Override
public void onResponse(Call<Bean> call, Response<Bean> response) {
Bean bean = response.body() ;
callBack.onSuccess(bean);
}
@Override
public void onFailure(Call<Bean> call, Throwable t) {
callBack.onFailure(new Exception(""));
}
});
}
}
以上是mvp中的mpackage com.example.muhanxi.myapplication.presenter;
import com.example.muhanxi.myapplication.Bean;
import com.example.muhanxi.myapplication.model.MainModelImpl;
import com.example.muhanxi.myapplication.model.ModelCallBack;
import com.example.muhanxi.myapplication.view.IMainView;
/**
* Created by muhanxi on 17/12/1.
*/
public class MainPresenter {
private IMainView iView ;
private MainModelImpl mainModel ;
public MainPresenter(IMainView view){
this.iView = view;
this.mainModel = new MainModelImpl();
}
public void get(){
mainModel.getData(new ModelCallBack() {
@Override
public void onSuccess(Bean bean) {
if(iView != null){
iView.onSuccess(bean);
}
}
@Override
public void onFailure(Exception e) {
if(iView != null){
iView.onFailure(e);
}
}
});
}
public void post(){
mainModel.postData(new ModelCallBack() {
@Override
public void onSuccess(Bean bean) {
if(iView != null){
iView.onSuccess(bean);
}
}
@Override
public void onFailure(Exception e) {
if(iView != null){
iView.onFailure(e);
}
}
});
}
}
以上是mvp中的Ppackage com.example.muhanxi.myapplication;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
/**
* Created by muhanxi on 17/12/1.
*/
public interface IGetDataBase {
/**
* get 请求
* @param key
* @return
*/
@GET("/weixin/query")
Call<Bean> get(@Query("key") String key);
/**
* post 请求
* @param key
* @return
*/
@FormUrlEncoded
@POST("/weixin/query")
Call<Bean> post(@Field("key") String key);
}以上是请求数据的类
package com.example.muhanxi.myapplication;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
@Entity
public class ListBean {
/**
* id : wechat_20171201008724
* title : 威廉·德雷谢维奇《简·奥斯丁的教导》:改变生活的艺术
* source : 文艺报1949
* firstImg : http://zxpic.gtimg.com/infonew/0/wechat_pics_-60604411.jpg/640
* mark :
* url : http://v.juhe.cn/weixin/redirect?wid=wechat_20171201008724
*/
@Id(autoincrement = true)
private Long iid;
private String id;
private String title;
private String source;
private String firstImg;
private String mark;
private String url;
@Generated(hash = 2061991154)
public ListBean(Long iid, String id, String title, String source, String firstImg,
String mark, String url) {
this.iid = iid;
this.id = id;
this.title = title;
this.source = source;
this.firstImg = firstImg;
this.mark = mark;
this.url = url;
}
@Generated(hash = 777734033)
public ListBean() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getFirstImg() {
return firstImg;
}
public void setFirstImg(String firstImg) {
this.firstImg = firstImg;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Long getIid() {
return this.iid;
}
public void setIid(Long iid) {
this.iid = iid;
}
@Override
public String toString() {
return "ListBean{" +
"iid=" + iid +
", id='" + id + '\'' +
", title='" + title + '\'' +
", source='" + source + '\'' +
", firstImg='" + firstImg + '\'' +
", mark='" + mark + '\'' +
", url='" + url + '\'' +
'}';
}
}以上是生成数据库的bean
package com.example.muhanxi.myapplication.dao;
import java.util.Map;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.AbstractDaoSession;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.internal.DaoConfig;
import com.example.muhanxi.myapplication.ListBean;
import com.example.muhanxi.myapplication.dao.ListBeanDao;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* {@inheritDoc}
*
* @see org.greenrobot.greendao.AbstractDaoSession
*/
public class DaoSession extends AbstractDaoSession {
private final DaoConfig listBeanDaoConfig;
private final ListBeanDao listBeanDao;
public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
daoConfigMap) {
super(db);
listBeanDaoConfig = daoConfigMap.get(ListBeanDao.class).clone();
listBeanDaoConfig.initIdentityScope(type);
listBeanDao = new ListBeanDao(listBeanDaoConfig, this);
registerDao(ListBean.class, listBeanDao);
}
public void clear() {
listBeanDaoConfig.clearIdentityScope();
}
public ListBeanDao getListBeanDao() {
return listBeanDao;
}
}以上是生成greendao的文件之一
package com.example.muhanxi.myapplication.dao;
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.example.muhanxi.myapplication.ListBean;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "LIST_BEAN".
*/
public class ListBeanDao extends AbstractDao<ListBean, Long> {
public static final String TABLENAME = "LIST_BEAN";
/**
* Properties of entity ListBean.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Iid = new Property(0, Long.class, "iid", true, "_id");
public final static Property Id = new Property(1, String.class, "id", false, "ID");
public final static Property Title = new Property(2, String.class, "title", false, "TITLE");
public final static Property Source = new Property(3, String.class, "source", false, "SOURCE");
public final static Property FirstImg = new Property(4, String.class, "firstImg", false, "FIRST_IMG");
public final static Property Mark = new Property(5, String.class, "mark", false, "MARK");
public final static Property Url = new Property(6, String.class, "url", false, "URL");
}
public ListBeanDao(DaoConfig config) {
super(config);
}
public ListBeanDao(DaoConfig config, DaoSession daoSession) {
super(config, daoSession);
}
/** Creates the underlying database table. */
public static void createTable(Database db, boolean ifNotExists) {
String constraint = ifNotExists? "IF NOT EXISTS ": "";
db.execSQL("CREATE TABLE " + constraint + "\"LIST_BEAN\" (" + //
"\"_id\" INTEGER PRIMARY KEY AUTOINCREMENT ," + // 0: iid
"\"ID\" TEXT," + // 1: id
"\"TITLE\" TEXT," + // 2: title
"\"SOURCE\" TEXT," + // 3: source
"\"FIRST_IMG\" TEXT," + // 4: firstImg
"\"MARK\" TEXT," + // 5: mark
"\"URL\" TEXT);"); // 6: url
}
/** Drops the underlying database table. */
public static void dropTable(Database db, boolean ifExists) {
String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"LIST_BEAN\"";
db.execSQL(sql);
}
@Override
protected final void bindValues(DatabaseStatement stmt, ListBean entity) {
stmt.clearBindings();
Long iid = entity.getIid();
if (iid != null) {
stmt.bindLong(1, iid);
}
String id = entity.getId();
if (id != null) {
stmt.bindString(2, id);
}
String title = entity.getTitle();
if (title != null) {
stmt.bindString(3, title);
}
String source = entity.getSource();
if (source != null) {
stmt.bindString(4, source);
}
String firstImg = entity.getFirstImg();
if (firstImg != null) {
stmt.bindString(5, firstImg);
}
String mark = entity.getMark();
if (mark != null) {
stmt.bindString(6, mark);
}
String url = entity.getUrl();
if (url != null) {
stmt.bindString(7, url);
}
}
@Override
protected final void bindValues(SQLiteStatement stmt, ListBean entity) {
stmt.clearBindings();
Long iid = entity.getIid();
if (iid != null) {
stmt.bindLong(1, iid);
}
String id = entity.getId();
if (id != null) {
stmt.bindString(2, id);
}
String title = entity.getTitle();
if (title != null) {
stmt.bindString(3, title);
}
String source = entity.getSource();
if (source != null) {
stmt.bindString(4, source);
}
String firstImg = entity.getFirstImg();
if (firstImg != null) {
stmt.bindString(5, firstImg);
}
String mark = entity.getMark();
if (mark != null) {
stmt.bindString(6, mark);
}
String url = entity.getUrl();
if (url != null) {
stmt.bindString(7, url);
}
}
@Override
public Long readKey(Cursor cursor, int offset) {
return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
}
@Override
public ListBean readEntity(Cursor cursor, int offset) {
ListBean entity = new ListBean( //
cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // iid
cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // id
cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2), // title
cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3), // source
cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4), // firstImg
cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5), // mark
cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6) // url
);
return entity;
}
@Override
public void readEntity(Cursor cursor, ListBean entity, int offset) {
entity.setIid(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
entity.setId(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
entity.setTitle(cursor.isNull(offset + 2) ? null : cursor.getString(offset + 2));
entity.setSource(cursor.isNull(offset + 3) ? null : cursor.getString(offset + 3));
entity.setFirstImg(cursor.isNull(offset + 4) ? null : cursor.getString(offset + 4));
entity.setMark(cursor.isNull(offset + 5) ? null : cursor.getString(offset + 5));
entity.setUrl(cursor.isNull(offset + 6) ? null : cursor.getString(offset + 6));
}
@Override
protected final Long updateKeyAfterInsert(ListBean entity, long rowId) {
entity.setIid(rowId);
return rowId;
}
@Override
public Long getKey(ListBean entity) {
if(entity != null) {
return entity.getIid();
} else {
return null;
}
}
@Override
public boolean hasKey(ListBean entity) {
return entity.getIid() != null;
}
@Override
protected final boolean isEntityUpdateable() {
return true;
}
}以上是生成greendao的文件之一
package com.example.muhanxi.myapplication.dao;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;
import org.greenrobot.greendao.AbstractDaoMaster;
import org.greenrobot.greendao.database.StandardDatabase;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseOpenHelper;
import org.greenrobot.greendao.identityscope.IdentityScopeType;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* Master of DAO (schema version 1): knows all DAOs.
*/
public class DaoMaster extends AbstractDaoMaster {
public static final int SCHEMA_VERSION = 1;
/** Creates underlying database table using DAOs. */
public static void createAllTables(Database db, boolean ifNotExists) {
ListBeanDao.createTable(db, ifNotExists);
}
/** Drops underlying database table using DAOs. */
public static void dropAllTables(Database db, boolean ifExists) {
ListBeanDao.dropTable(db, ifExists);
}
/**
* WARNING: Drops all table on Upgrade! Use only during development.
* Convenience method using a {@link DevOpenHelper}.
*/
public static DaoSession newDevSession(Context context, String name) {
Database db = new DevOpenHelper(context, name).getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
return daoMaster.newSession();
}
public DaoMaster(SQLiteDatabase db) {
this(new StandardDatabase(db));
}
public DaoMaster(Database db) {
super(db, SCHEMA_VERSION);
registerDaoClass(ListBeanDao.class);
}
public DaoSession newSession() {
return new DaoSession(db, IdentityScopeType.Session, daoConfigMap);
}
public DaoSession newSession(IdentityScopeType type) {
return new DaoSession(db, type, daoConfigMap);
}
/**
* Calls {@link #createAllTables(Database, boolean)} in {@link #onCreate(Database)} -
*/
public static abstract class OpenHelper extends DatabaseOpenHelper {
public OpenHelper(Context context, String name) {
super(context, name, SCHEMA_VERSION);
}
public OpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory, SCHEMA_VERSION);
}
@Override
public void onCreate(Database db) {
Log.i("greenDAO", "Creating tables for schema version " + SCHEMA_VERSION);
createAllTables(db, false);
}
}
/** WARNING: Drops all table on Upgrade! Use only during development. */
public static class DevOpenHelper extends OpenHelper {
public DevOpenHelper(Context context, String name) {
super(context, name);
}
public DevOpenHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
}
}以上是生成greendao的文件之一
package com.example.muhanxi.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.example.muhanxi.myapplication.adapter.IApdater;
import com.example.muhanxi.myapplication.presenter.MainPresenter;
import com.example.muhanxi.myapplication.view.IMainView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends Activity implements IMainView {
@BindView(R.id.recycleview)
RecyclerView recycleview;
private MainPresenter presenter;
private IApdater adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
presenter = new MainPresenter(this);
presenter.get();
LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
adapter = new IApdater(this);
recycleview.setLayoutManager(manager);
recycleview.setAdapter(adapter);
List<ListBean> listBeans = IApplication.session.getListBeanDao().loadAll();
for(ListBean bean : listBeans){
System.out.println(bean.toString());
}
}
@Override
public void onSuccess(Bean bean) {
adapter.addData(bean);
}
@Override
public void onFailure(Exception e) {
}
}以上是mainActivity类
package com.example.muhanxi.myapplication.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.muhanxi.myapplication.Bean;
import com.example.muhanxi.myapplication.EventBean;
import com.example.muhanxi.myapplication.ListBean;
import com.example.muhanxi.myapplication.Main2Activity;
import com.example.muhanxi.myapplication.R;
import com.facebook.drawee.view.SimpleDraweeView;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by muhanxi on 17/12/1.
*/
public class IApdater extends RecyclerView.Adapter<IApdater.IViewHolder> {
Context context;
List<ListBean> list ;
public IApdater(Context context) {
this.context = context;
}
public void addData(Bean bean){
if(list == null){
list = new ArrayList<>();
}
list.addAll(bean.getResult().getList());
notifyDataSetChanged();
}
@Override
public IApdater.IViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(context, R.layout.layout, null);
return new IViewHolder(view);
}
@Override
public void onBindViewHolder(IApdater.IViewHolder holder, final int position) {
holder.adapterSimpledraweeview.setImageURI(list.get(position).getFirstImg());
holder.adapterTextview.setText(list.get(position).getTitle());
holder.adapterTextview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EventBus.getDefault().postSticky(new EventBean(list.get(position).getFirstImg(),list.get(position).getTitle()));
context.startActivity(new Intent(context, Main2Activity.class));
}
});
}
@Override
public int getItemCount() {
return list == null ? 0 : list.size();
}
static class IViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.adapter_simpledraweeview)
SimpleDraweeView adapterSimpledraweeview;
@BindView(R.id.adapter_textview)
TextView adapterTextview;
IViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}以上是适配器的文件
package com.example.muhanxi.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
public class Main2Activity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
EventBus.getDefault().register(this);
}
@Subscribe(sticky = true)
public void event(EventBean eventBean){
Toast.makeText(this, ""+ eventBean.getUrl() + " " + eventBean.getTitle(), Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}以上是跳转之后的文件
复杂的MVP+refit+greendao
最新推荐文章于 2021-05-30 15:00:20 发布