Null Pointer exception on check if SharedPrefs is Null

I am creating an Android application that captures a user's email using the displayEmailCaptureFragment () method. If I have already registered a userโ€™s email, I donโ€™t want to prompt the user to enter their email address again.

I declare the line customerEmailAddress immediately after my MainActivity, but before the onCreate method:

public class MainActivity extends FragmentActivity implements View.OnClickListener, BillingProcessor.IBillingHandler,
    EmailCapturedListener {

private MyPagerAdapter pageAdapter;
private Button mDownloadResumeButton;
private ImageButton mRightArrow, mLeftArrow;
private static final String EMAILKEY = "email_key";
public static final String EDITSKU = "professional_editing_service_1499";
public static final String EMAILSKU = "resume_template_pro_99";
private static final String RBPEMAIL = "rbproeditor@gmail.com";
private static final String RBPPASSWORD = "Redhawks123";
public String customerEmailAddress;

Then I have the OnClick () method based on the response action of the user in the application. Essentially, I am trying to allow a specific action after onClick if the user has already entered their email address. If they have not provided their email address, I suggest that they enter their email and save it in the general settings. I use the basic if-else statement, however, I still throw a null pointer exception, even if I assign the line customerEmailAddress:

@Override
public void onClick(View v) {

    int currentPosition = pager.getCurrentItem();
    switch (v.getId()) {
        case R.id.right_arrow:
            pager.setCurrentItem(currentPosition + 1);
            break;
        case R.id.left_arrow:
            pager.setCurrentItem(currentPosition - 1);
            break;
        case R.id.download_resume_button:
                customerEmailAddress = mPrefs.getString(EMAILKEY, null);
            if (customerEmailAddress.equals(null)){
                displayEmailCaptureFragment();
            }
            else {
                showPurchaseDialog();
        }
            break;
    }
}

Any help is appreciated!

+4
source share
1 answer

This code is incorrect - you cannot call equals (...) or any other method on a null object.

...
customerEmailAddress = mPrefs.getString(EMAILKEY, null);
if (customerEmailAddress.equals(null)){
...

Do this:

customerEmailAddress = mPrefs.getString(EMAILKEY, null);
if (customerEmailAddress == null){ 
...

OR use TextUtils:

customerEmailAddress = mPrefs.getString(EMAILKEY, null);
if (TextUtils.isEmpty(customerEmailAddress)){ 
...
+4

Source: https://habr.com/ru/post/1620018/


All Articles