Android retrofit2使用rxjava2

时间:2018-01-09 08:51:44

标签: java android retrofit2 rx-java2

这是我的onCreate方法: -

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dept);
        mAPIService = ApiUtils.getAPIService();
    }

First Api call method:-
  public void sendPost() {
        mAPIService.savePost(params).enqueue(new Callback<Example>() {
            @Override
            public void onResponse(Call<Example> call, Response<Example> response) {

                if(response.isSuccessful()) {
                   Example ex =response.body();
                    Log.e(TAG, "post submitted to API." + ex.toString());

                    Userdata us=ex.getUserdata();
                    Log.e(TAG,"Result:"+ex.getResult()+"\nUserData:"+ex.getUserdata());
                    Log.e(TAG,"\nemployee_ID:"+us.getEmployeeId()+"\neng_name:"+us.getEngName()+"\ndesg:"+us.getDesignation()+"\nemail:"+us.getEmail()+"\nlfa_office_id:"+us.getLfaofficeid()+"\nlfa_office_name:"+us.getLfaOfficeName());
                    Log.e(TAG,"\n message"+ex.getMessage());
                    Toast.makeText(getApplicationContext(), ""+ ex.getMessage(), Toast.LENGTH_SHORT).show();
                    if(ex.getMessage().contains("Successful")){
                        **datadump();**
                    }
                    else{
                        Toast.makeText(getApplicationContext(),"Something went wrong! Try again later!",Toast.LENGTH_SHORT).show();
                    }
                }

            }

            @Override
            public void onFailure(Call<Example> call, Throwable t) {
                t.printStackTrace();
                Log.e(TAG, "Unable to submit post to API.");
            }
        });
    }

在datadump之后,调用一些函数从不同的apis获取数据并将其保存在Sqlite数据库中。以下是被调用的函数: -

public void gedistrict() {
        mAPIService = ApiUtils.getAPIService();

        Observable<Dsitrict_result> call= mAPIService.savedistrict().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        call.subscribe(new Observer<Dsitrict_result>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Dsitrict_result ex) {



                dist=ex.getDistricts();
                Log.e(TAG,"Result:"+ ex.getResult());
                Log.e(TAG,"District:"+ex.getDistricts());
                Log.e(TAG,"Message:"+ex.getMessage());
                //Every district.
                for(int i=0;i<dist.size();i++) {
                    Log.e(TAG, "\nState id:" + dist.get(i).getStateId() + "\nDistrict id:" + dist.get(i).getDistrictId()  + "\nEng_name:" + dist.get(i).getEngName() + "\nMar_name:" + dist.get(i).getMarName());
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {
                Log.e(TAG, "DONE RE BABA");
            }
        });

    }
    public void gettaluka() {
        mAPIService = ApiUtils.getAPIService();
        Observable<Taluka_result> call= mAPIService.savetaluka().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        call.subscribe(new Observer<Taluka_result>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Taluka_result ex) {

                taluk=ex.getTaluka();
                Log.e(TAG,"Result:"+ ex.getResult());
                Log.e(TAG,"District:"+ex.getTaluka());
                Log.e(TAG,"Message:"+ex.getMessage());

                for(int i=0;i<taluk.size();i++) {
                    Log.e(TAG, "\nState id:" + taluk.get(i).getStateId() + "\nDistrict id:" + taluk.get(i).getDistrictId() +"\nTaluka Id:"+taluk.get(i).getTalukaId() + "\nEng_name:" + taluk.get(i).getEngName() + "\nMar_name:" + taluk.get(i).getMarName());
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                Log.e(TAG, "DONE RE BABA");
            }
        }) ;


    }
    public void getvillage() {
        mAPIService = ApiUtils.getAPIService();

        Observable<Village_result> call= mAPIService.savevillage().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        call.subscribe(new Observer<Village_result>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Village_result ex) {


                villa=ex.getVillage();
                Log.e(TAG,"Result:"+ ex.getResult());
                Log.e(TAG,"District:"+ex.getVillage());
                Log.e(TAG,"Message:"+ex.getMessage());

                for(int i=0;i<villa.size();i++) {
                    Log.e(TAG, "\nState id:" + villa.get(i).getStateId() + "\nDistrict id:" + villa.get(i).getDistrictId() +"\nTaluka Id:"+villa.get(i).getTalukaId() +"\nVillage id: " +villa.get(i).getVillageId() + "\nEng_name:" + villa.get(i).getEngName() + "\nMar_name:" + villa.get(i).getMarName());
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                Log.e(TAG, "DONE RE BABA");
            }
        }) ;


    }
    public void getofficetype() {
        mAPIService = ApiUtils.getAPIService();

        Observable<Office_type_result> call= mAPIService.saveofficetype().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        call.subscribe(new Observer<Office_type_result>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Office_type_result ex) {


                oft=ex.getOfficeType();
                Log.e(TAG,"Result:"+ ex.getResult());
                Log.e(TAG,"District:"+ex.getOfficeType());
                Log.e(TAG,"Message:"+ex.getMessage());
                .
                for(int i=0;i<oft.size();i++) {

                    Log.e(TAG, "\noffice_type:"+oft.get(i).getOfficeType()+"\neng_office_type_name:"+oft.get(i).getEngOfficeTypeName()+"\nmar_office_type_name:"+oft.get(i).getMarOfficeTypeName());
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                Log.e(TAG, "DONE RE BABA");
            }
        }) ;

    }

以下是我的改造创建者及其不同端点的界面Retrofit Client Builder

public class RetrofitClient {

    private static Retrofit retrofit = null;
    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                  .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

API服务接口

public interface APIService {

    @POST("Login/checkUser/")
    @FormUrlEncoded
    Call <Example> savePost(params);
    @POST("District")

    Observable<Dsitrict_result> savedistrict();
    @POST("Taluka")
    Observable<Taluka_result> savetaluka();
    @POST("Village")
    Observable<Village_result> savevillage();
    @POST("OfficeType")
    Observable<Office_type_result> saveofficetype();

}

保存数据库

private void savetodb(){

        //District Table
                for(int i=0;i<dist.size();i++)
                    mydb.insertdataindistrictdb(dist.get(i).getStateId(),dist.get(i).getDistrictId(),dist.get(i).getEngName(),dist.get(i).getMarName());
        //Taluka Table
                for(int i=0;i<taluk.size();i++)
                    mydb.insertdataintalukadb(taluk.get(i).getStateId(),taluk.get(i).getDistrictId(),taluk.get(i).getTalukaId(),taluk.get(i).getEngName(),taluk.get(i).getMarName());
        //Village Table
                for(int i=0;i<villa.size();i++)
                    mydb.insertdatainvillagedb(villa.get(i).getStateId(),villa.get(i).getDistrictId(),villa.get(i).getTalukaId(),villa.get(i).getVillageId(),villa.get(i).getEngName(),villa.get(i).getMarName());
        //Office Type Table
                for(int i=0;i<oft.size();i++)
                    mydb.insertdatainofficetypedb(oft.get(i).getOfficeType(),oft.get(i).getEngOfficeTypeName(),oft.get(i).getMarOfficeTypeName());
            Log.e(TAG,"Database Create");
        }

我的错误 //错误为斜体和粗体的行。

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.trng18.myapplication, PID: 2424
                  java.lang.NullPointerException
                      at com.example.trng18.myapplication.Dept_login.savetodb(Dept_login.java:144)
                      at com.example.trng18.myapplication.Dept_login.datadump(Dept_login.java:138)
                      at com.example.trng18.myapplication.Dept_login.access$100(Dept_login.java:42)
                      at com.example.trng18.myapplication.Dept_login$1.onResponse(Dept_login.java:93)
                      at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                      at android.os.Handler.handleCallback(Handler.java:733)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5017)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                      at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

错误发生时的代码:

setOnClickListener