Retrofit+Rxjava的資料請求

Castertonone發表於2018-06-30

一.Api
1.
GetDataInterface
 
public interface GetDataInterface {
     @GET("/toutiao/index")
     Call<UserBean> get(@Query("key") String key);

    @FormUrlEncoded
    @POST("/toutiao/index")
    Call<UserBean> post(@Field("key") String key);

}

2.
MyApi



 
public class MyApi extends Application{
    //設定公共變數
    public static DaoSession session;
    public static GetDataInterface request;
    @Override
    public void onCreate() {
        super.onCreate();
        //1.  用於全域性配置初始化Fresco 圖片載入
        Fresco.initialize(this);
        //2.  用於全域性配置初始化Retrofit 網路請求
        //構建Retrofit類,初始化引數
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpUtils.goods_url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        //建立網路請求介面例項
        request = retrofit.create(GetDataInterface.class);
        //3.  用於全域性配置初始化GreenDao資料庫

//        DaoMaster.DevOpenHelper database = new DaoMaster.DevOpenHelper(this, "database");
//        Database db = database.getWritableDb();             //獲取能讀能寫的資料庫
//        session = new DaoMaster(db).newSession();

    }
}

3.HttpUtils

 
public class HttpUtils {
    public static String goods_url = "http://v.juhe.cn";
}

二.Model
1.
ModelCallBack
 public interface ModelCallBack {
    public void onSuccess(UserBean bean);
    public void onError(Exception e);
}
2.
MyModel
 
public class MyModel {
    /**
     * get請求
     * @param callBack
     */
    public void getData(final ModelCallBack callBack){
        //設定介面請求的key值
        Call<UserBean> call = MyApi.request.get("c4479ad58f41e7f78a8fa073d0b1f1b5");
        call.enqueue(new Callback<UserBean>() {
            @Override
            public void onResponse(Call<UserBean> call, Response<UserBean> response) {
                //獲取響應的資料,儲存在資料庫中
               UserBean bean = response.body();
             // MyApi.session.getUserDao().insertInTx(bean.getResult().getData());
               callBack.onSuccess(bean);
            }

            @Override
            public void onFailure(Call<UserBean> call, Throwable t) {
                //請求失敗時返回資料
                callBack.onError(new Exception(""));

            }
        });
    }

    /**
     * post請求
     * @param callBack
     */
    public void postData(final ModelCallBack callBack){
        //設定介面請求的key值
        Call<UserBean> call = MyApi.request.post("c4479ad58f41e7f78a8fa073d0b1f1b5");

        //發起非同步請求
        call.enqueue(new Callback<UserBean>() {
            @Override
            public void onResponse(Call<UserBean> call, Response<UserBean> response) {
                UserBean bean= response.body();
                //MyApi.session.getUserDao().insertInTx(bean.getResult().getData());
                callBack.onSuccess(bean);
            }

            @Override
            public void onFailure(Call<UserBean> call, Throwable t) {
                 callBack.onError(new Exception(""));
            }
        });
    }


}

三.Presenter
1.
MyPresenter
public class MyPresenter {
    private MyView myView;
    private MyModel myModel;

    public MyPresenter(MyView myView) {
        this.myView = myView;
        this.myModel = new MyModel();
    }
    public void get(){
       myModel.getData(new ModelCallBack() {
           @Override
           public void onSuccess(UserBean bean) {
                if(myView != null){
                    myView.onSuccess(bean);
                }
           }

           @Override
           public void onError(Exception e) {
               if(myView != null){
                   myView.onError(e);
               }
           }
       });
    }

    /**
     * post請求資料互動
     */
    public void post() {
        myModel.postData(new ModelCallBack() {
            @Override
            public void onSuccess(UserBean bean) {
                //資料互動時,為防止記憶體洩露,設定view層資料為空
                if (myView != null){
                    myView.onSuccess(bean);
                }

            }

            @Override
            public void onError(Exception e) {
                //資料互動時,為防止記憶體洩露,設定view層資料為空
                if (myView != null){
                    myView.onError(e);
                }

            }
        });
    }
    }

四.View
1.MyView
 
public interface MyView {
    public void onSuccess(UserBean bean);
    public void onError(Exception e);
}

2.MainActivity

 
public class MainActivity extends AppCompatActivity implements MyView{

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    private MyPresenter presenter;
    private MyAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        //建立Presenter層例項,與view層互動
        presenter = new MyPresenter(this);
        //get請求方式
        presenter.get();

        //設定佈局管理器以及佈局介面卡
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        adapter = new MyAdapter(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(adapter);

        //遍歷查詢資料庫中的所有資料
        //List<UserBean> list = MyApi.session.getUserDao().loadAll();
        //for (DataBean listBean : list){
          //  System.out.println("查詢:"+listBean.toString());
        //}

    }

    @Override
    public void onSuccess(UserBean bean) {
       adapter.addData(bean);
    }

    @Override
    public void onError(Exception e) {
        System.out.println("資料出錯:"+e);
    }
}

2.5  activity_main
<LinearLayout
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v7.widget.RecyclerView> </LinearLayout>
3.MyAdapter

 
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
    private Context context;
    private List<UserBean.ResultBean.DataBean> list;

    public MyAdapter(Context context) {
        this.context = context;
    }

    //新增資料
    public void addData(UserBean bean) {
        if (list == null) {
            list = new ArrayList<>();
        }
        list.addAll(bean.getResult().getData());
        notifyDataSetChanged();
    }


    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //新增布局檢視
        View view = View.inflate(context, R.layout.adapter, null);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
          holder.title.setText(list.get(position).getTitle());
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(list.get(position).getThumbnail_pic_s())
                .setOldController(holder.draweeView.getController())//記憶體優化  
                .setAutoPlayAnimations(true)
                .build();
        holder.draweeView.setController(controller);
    }

    @Override
    public int getItemCount() {
        return list == null ?0:list.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        @BindView(R.id.draweeView)
        SimpleDraweeView draweeView;
        @BindView(R.id.title)
        TextView title;
        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
}

3.5  adapter
<LinearLayout 
    android:orientation="horizontal"
    android:padding="6dp"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.facebook.drawee.view.SimpleDraweeView
        android:id="@+id/draweeView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="6dp"
        fresco:placeholderImage="@drawable/app_default"
        fresco:placeholderImageScaleType="fitCenter"
        fresco:actualImageScaleType="focusCrop"
        fresco:failureImage="@drawable/load_error_image"
        fresco:failureImageScaleType="fitCenter"
        fresco:roundAsCircle="true"/>
    <TextView
        android:id="@+id/title"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginLeft="6dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"/>

</LinearLayout>
五.許可權與依賴
1.依賴

project的
dependencies { classpath 'com.android.tools.build:gradle:2.3.0' classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'//greenDao生產程式碼外掛 // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }
Module的

apply plugin: 'com.android.application' apply plugin: 'com.jakewharton.butterknife' apply plugin: 'org.greenrobot.greendao'//greendao外掛

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' compile 'com.squareup.retrofit2:adapter-rxjava2:2.2.0' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' //greendao兩個依賴 compile 'org.greenrobot:greendao:3.2.2' compile 'net.zetetic:android-database-sqlcipher:3.5.7@aar' //recyclerview依賴 compile 'com.android.support:recyclerview-v7:25.3.1'
greendao { schemaVersion 1 daoPackage 'com.example.lenovo.retrofit_ceshi0629.dao'//自己的包名+.dao targetGenDir 'src/main/java' }

//版本
configurations.all { resolutionStrategy.eachDependency { DependencyResolveDetails details -> def requested = details.requested if (requested.group == 'com.android.support') { if (!requested.name.startsWith("multidex")) { details.useVersion '25.2.0' } } } }
2.許可權

<uses-permission android:name="android.permission.INTERNET"/>

   
<application    
android:name=".api.MyApi"
></application>
六.GreenDao

1.User
@Entity//必須寫的 public class User { @Id(autoincrement =true)//自增 private Long tid;//自己加的欄位
}

之後Make Project就會自動建立Dao包

相關文章