使用RxJava和Retrofit进行null对象引用[Android]

时间:2017-01-29 15:57:26

标签: android retrofit observable mvp

我正在构建一个简单的Android应用程序,当我尝试向API发送数据时出现此错误。我使用RxJava和Retrofit,并使用Model View Presenter。

我收到此错误“btnservice是一个空对象引用” 我总是得到btnservice null,请帮忙解决这个问题。 谢谢

这是JSON

request:
    {
     name: '',
     mobile: '',
     email: ''
    }

这是我的BaseActivtiy

public abstract class BaseActivity extends AppCompatActivity {

    @BindString(R.string.loading)
    public String loading;
    @BindInt(R.integer.success_code)
    public int successCode;
    @BindInt(R.integer.success_activication_code)
    public  int activicationSuccessCode;


    protected BTNService btnService;
    protected abstract int getLayout();
    private ProgressDialog progressDialog;
    private CompositeSubscription subscriptions;
    protected RxBus bus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        Icepick.restoreInstanceState(this, savedInstanceState);
        ButterKnife.bind(this);
        this.progressDialog = new ProgressDialog(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Icepick.saveInstanceState(this, outState);
    }


    @Override
    protected void onStart() {
        super.onStart();
        this.subscriptions = new CompositeSubscription();
    }


    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.progressDialog.dismiss();
    }

    public BTNService getBTNService() {
        return btnService;
    }

    public RxBus getBus() {
        return bus;
    }

    public void showProgressDialog(String message) {
        if (progressDialog != null) {
            progressDialog.setMessage(message);
            progressDialog.show();
        }
    }

    public void dismissProgressDialog() {
        progressDialog.hide();
    }

    public boolean isFragmentNotNull(String tag) {
        if (getSupportFragmentManager().findFragmentByTag(tag) != null) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isFragmentVisible(String tag) {
        if (isFragmentNotNull(tag)
                && getSupportFragmentManager().findFragmentByTag(tag).isVisible()) {
            return true;
        } else {
            return false;
        }
    }

}

这是我的BaseFragment

public abstract class BaseFragment extends Fragment implements Validator.ValidationListener {

    @BindString(R.string.loading)
    public String loading;
    @BindInt(R.integer.success_code)
    public int successCode;
    @BindInt(R.integer.success_activication_code)
    public  int activicationSuccessCode;
    @BindString(R.string.connection_error)
    public String connectionError;

    protected abstract int getLayout();
    protected Validator validator;
    private CompositeSubscription subscriptions;
    protected RxBus bus;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.bus = ((BaseActivity) getActivity()).getBus();
    }

    @Override
    public void onStart() {
        super.onStart();
        this.subscriptions = new CompositeSubscription();
/*        this.subscriptions
                .add(bus.toObserverable()
                        .subscribe(new Action1<Object>() {
                            @Override
                            public void call(Object event) {
                                if (event instanceof RxBusObject) {
                                    RxBusObject busObject = (RxBusObject) event;
                                    busHandler();
                                }
                            }
                        })
                );*/
    }

    @Override
    public void onStop() {
        super.onStop();
        this.subscriptions.clear();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayout(), container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    public RxBus getBus() {
        return this.bus;
    }

    @Override
    public void onValidationSucceeded() {

    }

    @Override
    public void onValidationFailed(List<ValidationError> errors) {
        for (ValidationError error : errors) {
            View view = error.getView();
            String message = error.getCollatedErrorMessage(getActivity());
            if (view instanceof EditText) {
                EditText et = ((EditText) view);
                et.setError(message);
                et.requestFocus();
            } else {
                Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
            }
        }
    }



    public void showSuccessDialog(String message, final Boolean isFinishActivity) {
        new MaterialDialog.Builder(getActivity())
                .iconRes(R.mipmap.ic_launcher)
                .title(getString(R.string.success).toUpperCase())
                .titleColor(Color.WHITE)
                .content(message)
                .contentColor(Color.WHITE)
                .positiveText(R.string.ok)
                .positiveColor(Color.WHITE)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog dialog, DialogAction which) {
                        if (isFinishActivity) {
                            getActivity().finish();
                        }
                    }
                })
                .cancelable(false)
                .show();
    }



    public void showProgressDialog(String message) {
        ((BaseActivity) getActivity()).showProgressDialog(message);
    }



    public Validator getValidator() {
        return validator;
    }

    public BTNService.Api getApi() {
        return ((BaseActivity) getActivity()).getBTNService().getApi();
    }

    public void dismissProgressDialog() {
        ((BaseActivity) getActivity()).dismissProgressDialog();
    }


}

这是我的改造类

public BTNService(Context context) {
        if (retrofit==null) {
        Retrofit retrofit = new Retrofit.Builder()
                .client(provideOkHttpClient(context))
                .baseUrl(BASE_URL)
                .build();
        this.api = retrofit.create(Api.class);
        }
    }

    private OkHttpClient provideOkHttpClient(final Context context) {
        HttpLoggingInterceptor httpLoggingInterceptorinterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptorinterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(httpLoggingInterceptorinterceptor);
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Response response = chain.proceed(request);
                return response;
            }
        });
        return httpClient.build();
    }

    public Api getApi() {
        return api;
    }

    public interface Api {

   @POST(PORTAL_URL + "customer/register")
   Observable<SignUpResponse> regsiterCustomer(@Path("email") String Email,
                                               @Path("name") String Name,
                                               @Path("mobile") String PhoneNumber);
}

这是我的演讲者

public class SignUpPresenter {

    private SignUpFragment fragment;

    public SignUpPresenter(SignUpFragment fragment) {
        this.fragment = fragment;
    }

    public SignUpRequest constructSignUpRequest() {
        SignUpRequest request = new SignUpRequest();
        request.setName(getAndTrimValueFromEditText(fragment.etName));
        request.setEmail(getAndTrimValueFromEditText(fragment.etEmail));
        request.setMobile(getAndTrimValueFromEditText(fragment.etPhone));
        return request;
    }

    private String getAndTrimValueFromEditText(EditText e) {
        return e.getText().toString().trim();
    }

    void signup (){
        this.register(constructSignUpRequest());
    }

    void register(final SignUpRequest signUpRequest) {
        fragment.showProgressDialog(fragment.loading);
        fragment.getApi().regsiterCustomer(
                signUpRequest.getName(),
                signUpRequest.getEmail(),
                signUpRequest.getMobile())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<GenericResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        fragment.dismissProgressDialog();
                        Timber.e(e.getLocalizedMessage());
                        Toast.makeText(fragment.getContext(), fragment.connectionError, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(GenericResponse genericResponse) {
                        fragment.dismissProgressDialog();
                        Toast.makeText(fragment.getContext(), genericResponse.getInfo(), Toast.LENGTH_SHORT).show();
                        if (genericResponse.getCode() == fragment.successCode) {
                            /*fragment.gotoActivationCodeActivity(SignUpRequest.getEmail(), SignUpRequest.get());*/
                            fragment.gotoQuestionActivity(signUpRequest.getEmail(), signUpRequest.getEmail(), signUpRequest.getMobile());
                        }
                    }
                });
    }

1 个答案:

答案 0 :(得分:0)

Global symbol "$fileName" requires explicit package name (did you forget to declare "my $fileName"?) at

我正在使用Rxjava 2,也许对您有用。