效果图
首页RecycierView 点击条目 Eventbus传值给第二个activity,吐司展示
Retrofit的post方式展示recyclerview,fresco加载图片,添加到数据库greendao,
点击条目发送Eventbus黏性事件给SecondActivity,吐司展示字段
涉及到了greendao,在工程的gradle里面加入两行(蓝色的)
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
}
}
在项目的gradle里面做更改,并且导入依赖(标红的)
apply plugin: 'com.android.application' apply plugin: 'org.greenrobot.greendao' // apply plugin android { compileSdkVersion 26 defaultConfig { applicationId "com.example.exercise_05_retrofit_greendao_eventbus_fresco" minSdkVersion 19 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.exercise_05_retrofit_greendao_eventbus_fresco.dao'// 自己的包名.dao schemaVersion 1 } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' 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' //butterknife两个依赖 compile 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' //retrofit的两个依赖 compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:converter-gson:2.3.0' //eventbus的依赖 compile 'org.greenrobot:eventbus:3.1.1' //fresco的依赖 compile 'com.facebook.fresco:fresco:1.5.0' //greendao两个依赖 compile 'org.greenrobot:greendao:3.2.2' compile 'net.zetetic:android-database-sqlcipher:[email protected]' //recyclerview依赖 compile 'com.android.support:recyclerview-v7:25.3.1' }新建IApplication 继承Application ,并在清单文件中配置
- public class IApplication extends Application
- <application
- android:name=".appli.IApplication"
清单文件中加入权限
- <uses-permission android:name="android.permission.INTERNET" />
请求网络获得的数据生成实体类bean(标红的需要写)
@Entity//必须写的 public class ListBean { @Id(autoincrement =true)//自增privateLong id;//自己加的字段
private String icon; private String name; private int pcid; private int pscid;点击锤子按钮
新建接口GetDataService ,这里提供了两种方法,get传参 post传参
- public interface GetDataService {
- /**
- * post请求
- * https://www.zhaoapi.cn/product/getProductCatagory?cid=1
- */
- @FormUrlEncoded
- @POST("/product/getProductCatagory")
- Call<OldBean> post(@Field("cid") String cid);
- /**
- * get请求
- * https://www.zhaoapi.cn/product/getProductCatagory?cid=1
- */
- @GET("/product/getProductCatagory")
- Call<OldBean> get(@Query("cid") String cid);
- }
IApplication里面的一系列初始化配置
- public class IApplication extends Application{
- public static GetDataService service;
- public static DaoSession session;
- @Override
- public void onCreate() {
- super.onCreate();
- //一系列的初始化配置
- //1.fresco的初始化配置
- Fresco.initialize(this);
- //2.retrofit的初始化
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://www.zhaoapi.cn")
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- //操作网络请求的对象
- service = retrofit.create(GetDataService.class);
- //3.初始化greendao
- DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"tablename");
- Database database = helper.getWritableDb();
- //new出session
- session = new DaoMaster(database).newSession();
- }
- }
- public class MyModel {
- //请求网络数据
- public void getData(final ModelCallBack modelCallBack) {
- //调用application里面的请求网络的对象
- //传接口后面拼接的参数 key的值 ,,,post
- /* Call<OldBean> call = IApplication.service.post("1");
- call.enqueue(new Callback<OldBean>() {
- @Override
- public void onResponse(Call<OldBean> call, Response<OldBean> response) {
- //response.body 就是一个bean对象了,不需要解析了
- OldBean oldBean = response.body();
- modelCallBack.success(oldBean);
- *//* //在这里 就已经添加到了数据库,在view层查询数据库展示recyview
- //调用iapplication里面的数据库的对象
- IApplication.session.getListBeanDao().insertInTx(oldBean.getResult().getList());*//*
- }
- @Override
- public void onFailure(Call<OldBean> call, Throwable t) {
- modelCallBack.failure(new Exception(""));
- }
- });*/
- //-------------------------
- //传接口后面拼接的参数 key的值 ,,,get
- Call<OldBean> call = IApplication.service.get("2");
- call.enqueue(new Callback<OldBean>() {
- @Override
- public void onResponse(Call<OldBean> call, Response<OldBean> response) {
- //response.body 就是一个bean对象了,不需要解析了
- OldBean oldBean = response.body();
- modelCallBack.success(oldBean);
- /* //在这里 就已经添加到了数据库,在view层查询数据库展示recyview
- //调用iapplication里面的数据库的对象
- IApplication.session.getListBeanDao().insertInTx(oldBean.getResult().getList());*/
- }
- @Override
- public void onFailure(Call<OldBean> call, Throwable t) {
- modelCallBack.failure(new Exception(""));
- }
- });
- }
- }
回调到view层MainActivity
- public class MainActivity extends AppCompatActivity implements ViewCallBack{
- @BindView(R.id.recy_view)
- RecyclerView recyView;
- private MyPresenter myPresenter;
- private RecyAdapter recyAdapter;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- ButterKnife.bind(this);
- myPresenter = new MyPresenter(this);
- myPresenter.getData();
- recyView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
- recyAdapter = new RecyAdapter(this);
- recyView.setAdapter(recyAdapter);
- }
- @Override
- public void success(OldBean oldBean) {
- //在这里 就已经添加到了数据库,在view层查询数据库展示recyview
- //调用iapplication里面的数据库的对象
- IApplication.session.getListBeanDao().insertInTx(oldBean.getData().get(0).getList());
- //添加完查询
- List<ListBean> list = IApplication.session.getListBeanDao().loadAll();
- //查询打印出来
- for(ListBean bean:list){
- System.out.println(bean.toString());
- }
- recyAdapter.addData(list);//将从数据库里查询出的数据展示出来
- // recyAdapter.addData(oldBean.getData().get(0).getList());//直接展示
- }
- @Override
- public void failure(Exception e) {
- }
- }
- <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"
- tools:context="com.example.exercise_05_retrofit_greendao_eventbus_fresco.MainActivity">
- <android.support.v7.widget.RecyclerView
- android:id="@+id/recy_view"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
- </LinearLayout>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:orientation="horizontal"
- android:gravity="center_vertical"
- android:layout_height="match_parent">
- <com.facebook.drawee.view.SimpleDraweeView
- android:id="@+id/recy_simple_view"
- android:layout_width="100dp"
- android:layout_height="100dp" />
- <TextView
- android:layout_marginLeft="20dp"
- android:textSize="23sp"
- android:id="@+id/recy_text"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
- public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.MyViewHolder> {
- private List<ListBean> listDa;
- Context context;
- public RecyAdapter(Context context) {
- this.context = context;
- }
- //添加数据的方法
- public void addData(List<ListBean> list) {
- if (listDa == null) {
- listDa = new ArrayList<>();
- }
- listDa.addAll(list);
- notifyDataSetChanged();
- }
- @Override
- public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
- View view = View.inflate(context, R.layout.recy_item, null);
- MyViewHolder myViewHolder = new MyViewHolder(view);
- return myViewHolder;
- }
- @Override
- public void onBindViewHolder(MyViewHolder holder, final int position) {
- holder.recySimpleView.setImageURI(listDa.get(position).getIcon());
- holder.recyText.setText(listDa.get(position).getName());
- //条目点击事件
- holder.itemView.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- //eventbus传递黏性事件给mainactivity2
- //传一个eventbusbean对象过去
- EventBusBean eventBusBean = new EventBusBean(listDa.get(position).getName());
- EventBus.getDefault().postSticky(eventBusBean);
- //跳转
- context.startActivity(new Intent(context, SecondActivity.class));
- }
- });
- }
- @Override
- public int getItemCount() {
- return listDa == null ? 0 : listDa.size();
- }
- static class MyViewHolder extends RecyclerView.ViewHolder{
- @BindView(R.id.recy_simple_view)
- SimpleDraweeView recySimpleView;
- @BindView(R.id.recy_text)
- TextView recyText;
- MyViewHolder(View view) {
- super(view);
- ButterKnife.bind(this, view);
- }
- }
- }
Eventbus新建EventBusBean类传值
- public class EventBusBean {
- private String name;
- public EventBusBean(String name) {
- this.name = name;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
recyadapter的itemView点击事件里面,Eventbus发布一个黏性事件
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.recySimpleView.setImageURI(listDa.get(position).getIcon());
holder.recyText.setText(listDa.get(position).getName());
//条目点击事件
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//eventbus传递黏性事件给mainactivity2
//传一个eventbusbean对象过去
EventBusBean eventBusBean = new EventBusBean(listDa.get(position).getName());
EventBus.getDefault().postSticky(eventBusBean);
//跳转
context.startActivity(new Intent(context, SecondActivity.class));
}
});
SecondActivity里面注册黏性事件,并吐司,取消注册
- public class SecondActivity extends AppCompatActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_second);
- //这里面注册eventbus
- EventBus.getDefault().register(this);
- }
- //接收订阅 ,,参数是bean
- @Subscribe(sticky=true)
- public void event(EventBusBean eventBusBean){
- Toast.makeText(this,eventBusBean.getName(),Toast.LENGTH_LONG).show();
- }
- @Override
- protected void onDestroy() {
- super.onDestroy();
- EventBus.getDefault().unregister(this);
- }
- }