Я использую Model View Presenter в своем приложении, и я пытаюсь сохранить токен значения в SharedPreferences. Но, я получил SharedPreferences null, ошибка SharedPreferences.edit() - это ссылки на нулевые объекты. Пожалуйста, помогите мне решить эту проблему. СпасибоMy SharedPreferences - null. Это ошибка SharedPreferences.edit() является ссылкой на нулевой объект
Это мой фрагмент
public class SignUpFragment extends BaseFragment {
@NotEmpty(messageResId = R.string.rules_no_empty)
@Bind(R.id.Name)
EditText etName;
@NotEmpty(messageResId = R.string.rules_no_empty)
@Bind(R.id.email)
EditText etEmail;
@NotEmpty(messageResId = R.string.rules_no_empty)
@Bind(R.id.phone)
EditText etPhone;
@Bind(R.id.btnSignUp)
Button btnSignUp;
public static final String TAG = SignUpFragment.class.getSimpleName();
private SignUpPresenter presenter;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static void showFragment(BaseActivity sourceActivity) {
if (!sourceActivity.isFragmentNotNull(TAG)) {
FragmentTransaction fragmentTransaction = sourceActivity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_question, new SignUpFragment(), TAG);
fragmentTransaction.commit();
}
}
@Override
protected int getLayout() {
return R.layout.activity_sign_up;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = new SignUpPresenter(this);
sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initview();
}
@Override
public void onResume() {
super.onResume();
}
private void initview(){
btnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!validate()) {
onSignupFailed();
return;
} else {
presenter.signup();
}
}
});
}
@Override
public void onValidationSucceeded() {
super.onValidationSucceeded();
presenter.signup();
}
public void onSignupFailed() {
Toast.makeText(getContext(), "Login failed", Toast.LENGTH_LONG).show();
btnSignUp.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String name = etName.getText().toString();
String email = etEmail.getText().toString();
String password = etPhone.getText().toString();
if (name.isEmpty() || name.length() < 3) {
etName.setError("at least 3 characters");
valid = false;
} else {
etName.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
etEmail.setError("enter a valid email address");
valid = false;
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
etPhone.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
etPhone.setError(null);
}
return valid;
}
public void gotoQuestionActivity(String email, String name, String phone) {
QuestionActivity.startActivity((BaseActivity) getActivity(), email, name, phone);
getActivity().finish();
}
}
и это мой Presenter
public class SignUpPresenter {
private SignUpFragment fragment;
public String token = "token";
SharedPreferences sharedpreferences;
private Context mContext;
public static final String MyPREFERENCES = "MyPrefs" ;
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();
}
public SharedPreferences getSharedPreferences() {
return sharedpreferences;
}
void signup(){
this.register(constructSignUpRequest());
}
void register(final SignUpRequest signUpRequest) {
fragment.showProgressDialog(fragment.loading);
fragment.getApi().regsiterCustomer(constructSignUpRequest())
.observeOn(AndroidSchedulers.mainThread())
.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 signUpResponse) {
fragment.dismissProgressDialog();
Toast.makeText(fragment.getContext(), signUpResponse.getInfo(), Toast.LENGTH_SHORT).show();
if (signUpResponse.getCode() == fragment.successCode) {
/*fragment.gotoActivationCodeActivity(SignUpRequest.getEmail(), SignUpRequest.get());*/
fragment.gotoQuestionActivity(signUpRequest.getEmail(), signUpRequest.getName(), signUpRequest.getMobile());
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(token, signUpResponse.getData().getToken());
editor.commit();
}
}
});
}
}
Вы никогда не инициализировать 'sharedpreferences' в' SignUpPresenter'. –