Recyclerview显示数据+GreenDao数据库+跳转传值(图片圆)+MVP

来源:互联网 发布:linux命令行设置中文 编辑:程序博客网 时间:2024/05/21 20:25

build.gradle

    // Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    repositories {        google()        jcenter()        mavenCentral() // add repository    }    dependencies {        classpath 'com.android.tools.build:gradle:3.0.1'        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        google()        jcenter()    }}task clean(type: Delete) {    delete rootProject.buildDir}

build.gradle

      apply plugin: 'com.android.application'apply plugin: 'org.greenrobot.greendao' // apply pluginandroid {    compileSdkVersion 26    defaultConfig {        applicationId "zhou.bwei.com.zhou"        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 'zhou.bwei.com.zhou.dao'    schemaVersion 1}dependencies {    implementation fileTree(dir: 'libs', include: ['*.jar'])    implementation 'com.android.support.constraint:constraint-layout:1.0.2'    implementation 'com.android.support:appcompat-v7:26.1.0'    testImplementation 'junit:junit:4.12'    androidTestImplementation 'com.android.support.test:runner:1.0.1'    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'    compile 'com.squareup.retrofit2:retrofit:2.3.0'    compile 'org.greenrobot:greendao:3.2.2'    // add library    compile 'net.zetetic:android-database-sqlcipher:3.5.6'    compile 'com.squareup.retrofit2:converter-gson:2.3.0'    implementation 'com.android.support:recyclerview-v7:26.1.0'    compile 'com.jakewharton:butterknife:8.8.1'    annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'    compile 'org.greenrobot:eventbus:3.1.1'    compile 'com.facebook.fresco:fresco:1.5.0'}

清单列表

    <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="zhou.bwei.com.zhou">    <uses-permission android:name="android.permission.INTERNET" />    <application        android:name=".IApplication"        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name=".Main2Activity"></activity>    </application></manifest>

IApplication

   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();    }}

IGetDataBase

    public interface IGetDataBase {    @GET("/toutiao/index")    Call<Bean> get(@Query("key") String key);/** * post请求 * */@FormUrlEncoded    @POST("/toutiao/index")    Call<Bean> post(@Field("key") String key);}

MainModelImpl

package zhou.bwei.com.zhou.model;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import zhou.bwei.com.zhou.IApplication;import zhou.bwei.com.zhou.bean.Bean;/** * 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("2f092bd9ce76c0257052d6d3c93c11b4");        call.enqueue(new Callback<Bean>() {            @Override            public void onResponse(Call<Bean> call, Response<Bean> response) {              Bean bean =   response.body();                callBack.onSuccess(bean);                // 保存到数据库                IApplication.session.getDataBeanDao().insertInTx(bean.getResult().getData());            }            @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("2f092bd9ce76c0257052d6d3c93c11b4");       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(""));           }       });    }}

MainPresenter

import zhou.bwei.com.zhou.bean.Bean;import zhou.bwei.com.zhou.model.MainModelImpl;import zhou.bwei.com.zhou.model.ModelCallBack;import zhou.bwei.com.zhou.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);                }            }        });    }}

IApdater

    public class IApdater extends RecyclerView.Adapter<IApdater.IViewHolder> {        Context context;        List<DataBean> list ;        public IApdater(Context context) {            this.context = context;        }        public void addData(Bean bean){            if(list == null){                list = new ArrayList<>();            }            list.addAll(bean.getResult().getData());            notifyDataSetChanged();        }        @Override        public IViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {            View view = View.inflate(context, R.layout.list_item, null);            return new IViewHolder(view);        }        @Override        public void onBindViewHolder(IViewHolder holder, final int position) {            holder.adapterSimpledraweeview.setImageURI(list.get(position).getThumbnail_pic_s());            holder.adapterTextview.setText(list.get(position).getTitle());            RoundingParams roundingParams = RoundingParams.fromCornersRadius(5f);            roundingParams.setRoundAsCircle(true);            holder.adapterSimpledraweeview.getHierarchy().setRoundingParams(roundingParams);            holder.adapterSimpledraweeview.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View view) {               EventBus.getDefault().postSticky(new EventBean(list.get(position).getThumbnail_pic_s(),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);            }        }    }

MainActivity

public class MainActivity extends Activity implements IMainView{@BindView(R.id.recyclerview)RecyclerView recycleview;private MainPresenter presenter;private IApdater adapter;@Overrideprotected 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<DataBean> listBeans =  IApplication.session.getDataBeanDao().loadAll();    for(DataBean bean : listBeans){        System.out.println(bean.toString());    }}@Overridepublic void onSuccess(Bean bean) {    adapter.addData(bean);}@Overridepublic void onFailure(Exception e) {}

}

Main2Activity

    @BindView(R.id.simple)    SimpleDraweeView simple;    @BindView(R.id.text_view)    TextView textView;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main2);        ButterKnife.bind(this);        EventBus.getDefault().register(this);    }    @Subscribe(sticky = true)    public void event(EventBean eventBean) {        simple.setImageURI(eventBean.getUrl());        textView.setText(eventBean.getTitle());         Toast.makeText(this, ""+ eventBean.getUrl() + "  " + eventBean.getTitle(), Toast.LENGTH_SHORT).show();    }    @Override    protected void onDestroy() {        super.onDestroy();        EventBus.getDefault().unregister(this);    }}

bean包要用注解 点studio运行旁边的小锤子生成dao的三个包,详细见下面的github
[源代码]https://github.com/jisheng6/ZhoukaoYiDemo

阅读全文
0 0
原创粉丝点击