Android设备中的BottomNavigation活动崩溃

时间:2018-11-19 07:34:51

标签: android bottomnavigationview

成功登录后,家庭活动无法在设备中启动,并且应用程序将崩溃。我能够很好地开展其他活动。因此,我相信这里的问题在于我的Home活动(以及所有其他包含BottomNavigation的活动)。

有人可以指出我的错误吗?谢谢!

Home.java

public class Home extends AppCompatActivity implements AdapterView.OnItemSelectedListener{

    private TextView mTextMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);


        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Creating the instance of PopupMenu
                final PopupMenu popup = new PopupMenu(Home.this, fab);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                        .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                                Home.this,
                                "You Clicked : " + item.getTitle(),
                                Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }

        });


        final ImageButton ib = (ImageButton) findViewById(R.id.ib);
        ib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Creating the instance of PopupMenu
                final PopupMenu popup = new PopupMenu(Home.this, ib);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                        .inflate(R.menu.popup_switchgrp, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                                Home.this,
                                "You Clicked : " + item.getTitle(),
                                Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }

        });





        Spinner spinner = findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.DeviceLocation, android.R.layout.simple_spinner_dropdown_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    return true;
                case R.id.navigation_scenes:
                    mTextMessage.setText(R.string.title_scenes);
                    openScenesPage();
                    return true;
                case R.id.navigation_security:
                    mTextMessage.setText(R.string.title_security);
                    openSecurityPage();
                    return true;
                case R.id.navigation_myinfo:
                    mTextMessage.setText(R.string.title_myinfo);
                    openMyInfoPage();
                    return true;
            }
            return true;
        }
    };

    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String text = parent.getItemAtPosition(position).toString();
        Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
    }

    public void onNothingSelected(AdapterView<?> parent) {

    }

    private void openScenesPage(){
        Intent intent = new Intent(this, Home.class);
        startActivity(intent);
    }

    private void openSecurityPage(){
        Intent intent = new Intent(this, Home.class);
        startActivity(intent);
    }

    private void openMyInfoPage(){
        Intent intent = new Intent(this, Home.class);
        startActivity(intent);
    }
}

LOGCAT:

2018-11-19 16:46:30.953 1778-1778/? E/adTracker: Value 60172784179-1477976237@g.us of type java.lang.String cannot be converted to JSONObject

    --------- beginning of system
2018-11-19 16:46:36.789 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:46:45.009 751-751/? E/cnss-daemon: gateway mac address: %02x:%02x:%02x:%02x:%02x:%02x
    : 00:00:00:00:00:00
2018-11-19 16:46:45.010 751-751/? E/cnss-daemon: Invalid mac address: 0x555555f110M
2018-11-19 16:46:49.000 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:46:50.046 16022-16022/? E/ResourcesFlusher: Could not retrieve ResourcesImpl#mDrawableCache field
    java.lang.NoSuchFieldException: No field mDrawableCache in class Landroid/content/res/MiuiResourcesImpl; (declaration of 'android.content.res.MiuiResourcesImpl' appears in /system/framework/framework.jar)
        at java.lang.Class.getDeclaredField(Native Method)
        at android.support.v7.app.ResourcesFlusher.flushNougats(Twttr:141)
        at android.support.v7.app.ResourcesFlusher.flush(Twttr:46)
        at android.support.v7.app.AppCompatDelegateImplV14.updateForNightMode(Twttr:221)
        at android.support.v7.app.AppCompatDelegateImplV14.applyDayNight(Twttr:93)
        at android.support.v7.app.AppCompatActivity.onCreate(Twttr:73)
        at com.twitter.app.common.base.BaseFragmentActivity.onCreate(Twttr:66)
        at com.twitter.app.common.inject.InjectedFragmentActivity.onCreate(Twttr:46)
        at com.twitter.app.common.abs.AbsFragmentActivity.onCreate(Twttr:129)
        at com.twitter.app.common.base.TwitterFragmentActivity.onCreate(Twttr:158)
        at android.app.Activity.performCreate(Activity.java:6875)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2694)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2802)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1549)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6379)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
2018-11-19 16:46:55.228 16022-16022/? E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
2018-11-19 16:46:55.715 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:46:55.862 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.storeANWBufferInMetadata not implemented
2018-11-19 16:46:55.870 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.storeANWBufferInMetadata not implemented
2018-11-19 16:46:55.870 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.configureVideoTunnelMode not implemented
2018-11-19 16:46:55.870 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.useAndroidNativeBuffer is supported
2018-11-19 16:46:55.872 738-2028/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:46:55.873 738-2028/? E/OMXNodeInstance: getConfig(2e200ba:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:46:55.930 738-2028/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:46:55.930 738-2028/? E/OMXNodeInstance: getConfig(2e200ba:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:46:55.964 738-2028/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:46:55.964 738-2028/? E/OMXNodeInstance: getConfig(2e200ba:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:47:00.810 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:47:00.817 2685-2897/? E/WtProcessController: Error pid or pid not exist
2018-11-19 16:47:00.824 2685-2897/? E/WtProcessController: Error pid or pid not exist
2018-11-19 16:47:00.856 15173-15173/? E/SearchServiceClient: SearchServiceClient disposed and cannot be reused.
2018-11-19 16:47:00.861 15173-15173/? E/SearchServiceClient: SearchServiceClient disposed and cannot be reused.
2018-11-19 16:47:00.862 15173-15173/? E/SearchServiceClient: SearchServiceClient disposed and cannot be reused.
2018-11-19 16:47:01.566 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:47:01.572 733-16282/? E/ACDB-LOADER: Error: ACDB AudProc vol returned = -19
2018-11-19 16:47:01.573 733-16282/? E/ACDB-LOADER: Error: ACDB AFE returned = -19
2018-11-19 16:47:01.685 2035-12645/? E/ctxmgr: [ProducerStatusImpl]updateStateForNewContextData: inactive, contextName=7
2018-11-19 16:47:01.888 2035-2035/? E/BeaconBle: Scan couldn't start for Places
2018-11-19 16:47:11.151 15173-16305/? E/DoodleDataUtils: Doodle: bad search_url: 
2018-11-19 16:47:11.166 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:47:11.172 733-16322/? E/ACDB-LOADER: Error: ACDB AudProc vol returned = -19
2018-11-19 16:47:11.173 733-16322/? E/ACDB-LOADER: Error: ACDB AFE returned = -19
2018-11-19 16:47:12.121 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:47:12.360 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.storeANWBufferInMetadata not implemented
2018-11-19 16:47:12.366 738-738/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.storeANWBufferInMetadata not implemented
2018-11-19 16:47:12.366 738-738/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.configureVideoTunnelMode not implemented
2018-11-19 16:47:12.366 738-738/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.useAndroidNativeBuffer is supported
2018-11-19 16:47:12.368 738-2028/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:47:12.368 738-2028/? E/OMXNodeInstance: getConfig(2e200bb:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:47:12.405 738-2028/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:47:12.406 738-2028/? E/OMXNodeInstance: getConfig(2e200bb:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:47:12.410 15173-16368/? E/ACodec: Unexpected command completion in ExecutingToIdleState: PortDisable(2) Loaded(1)
2018-11-19 16:47:12.411 15173-16368/? E/ACodec: signalError(omxError 0x80001001, internalError -2147483646)
2018-11-19 16:47:12.411 15173-16367/? E/MediaCodec: Codec reported err 0x80000002, actionCode 0, while in state 10
2018-11-19 16:47:17.581 2035-16289/? E/NetworkScheduler: Invalid component specified.
2018-11-19 16:47:17.602 2035-15450/? E/NetworkScheduler: Invalid component specified.
2018-11-19 16:47:17.631 2035-15450/? E/NetworkScheduler: Invalid component specified.
2018-11-19 16:47:23.592 16342-16342/com.abc.def E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.abc.def, PID: 16342
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
        at com.abc.def.LoginActivity.showProgress(LoginActivity.java:245)
        at com.abc.def.LoginActivity.attemptLogin(LoginActivity.java:206)
        at com.abc.def.LoginActivity.access$000(LoginActivity.java:41)
        at com.abc.def.LoginActivity$2.onClick(LoginActivity.java:92)
        at android.view.View.performClick(View.java:5647)
        at android.view.View$PerformClick.run(View.java:22462)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6379)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
2018-11-19 16:47:23.713 1527-1669/? E/InputDispatcher: channel '272b664 com.abc.def/com.abc.def.LoginActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2018-11-19 16:47:23.714 477-2464/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
2018-11-19 16:47:23.742 2414-2450/? E/octvm_klo: read: Unexpected EOF!
2018-11-19 16:47:23.921 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.storeANWBufferInMetadata not implemented
2018-11-19 16:47:23.928 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.storeANWBufferInMetadata not implemented
2018-11-19 16:47:23.928 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.configureVideoTunnelMode not implemented
2018-11-19 16:47:23.928 738-2028/? E/OMX-VDEC-1080P: Extension: OMX.google.android.index.useAndroidNativeBuffer is supported
2018-11-19 16:47:23.930 738-946/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:47:23.930 738-946/? E/OMXNodeInstance: getConfig(2e200bc:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:47:23.965 15173-15173/? E/SrpContentController: Attach/Detach events sent when controller is already destroyed
2018-11-19 16:47:23.966 15173-15173/? E/SrpContentController: Show/Hide events sent when controller is already destroyed
2018-11-19 16:47:23.982 2035-16290/? E/ctxmgr: [ProducerStatusImpl]updateStateForNewContextData: inactive, contextName=7
2018-11-19 16:47:24.014 15173-15173/? E/SrpContentController: Show/Hide events sent when controller is already destroyed
2018-11-19 16:47:24.026 15173-15173/? E/SrpContentController: Show/Hide events sent when controller is already destroyed
2018-11-19 16:47:24.048 738-946/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:47:24.048 738-946/? E/OMXNodeInstance: getConfig(2e200bc:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:47:24.154 738-2028/? E/OMX-VDEC-1080P: Does not handle dataspace request
2018-11-19 16:47:24.154 738-2028/? E/OMXNodeInstance: getConfig(2e200bc:qcom.decoder.avc, ??(0x7f000062)) ERROR: UnsupportedSetting(0x80001019)
2018-11-19 16:47:24.180 733-16422/? E/ACDB-LOADER: Error: ACDB AudProc vol returned = -19
2018-11-19 16:47:24.181 733-16422/? E/ACDB-LOADER: Error: ACDB AFE returned = -19
2018-11-19 16:47:24.364 2035-2035/? E/BeaconBle: Scan couldn't start for Places

Login.java

  public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {

    private static final int REQUEST_READ_CONTACTS = 0;

    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };

    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private Button mSignInButton;
    private Button mForgotPasswordButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mSignInButton = (Button) findViewById(R.id.sign_in_button);
        mSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
                mLoginFormView = findViewById(R.id.login_form);
                mProgressView = findViewById(R.id.login_progress);
            }
        });

        final Button mForgotPasswordButton = (Button) findViewById(R.id.forgot_password_button);
        mForgotPasswordButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openForgotPassword();
            }
        });


    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }

        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, new View.OnClickListener() {
                        @Override
                        @TargetApi(Build.VERSION_CODES.M)
                        public void onClick(View v) {
                            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                        }
                    });
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        else if (TextUtils.isEmpty(password)) {
            mPasswordView.setError("Password is empty");
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, password);
            mAuthTask.execute((Void) null);
        }

    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@") && email.contains(".");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    private void openForgotPassword(){
        Intent intent = new Intent(this, ForgotPasswordActivity.class);
        startActivity(intent);
    }

    public void startHome(){
        Intent intent = new Intent(this, Home.class);
        startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }

            });
        } else {
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},


                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(LoginActivity.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mEmailView.setAdapter(adapter);
    }


    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }

            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the password matches.
                    return pieces[1].equals(mPassword);
                }
            }

            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                startHome();
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

实际上,您可以在mProgressView单击中初始化mLoginFormViewmSignInButton。这是一种不好的做法,会使NPE失效,所以我建议像下面这样添加两个视图onCreate()的移动初始化并从onClickListener中删除。

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    mLoginFormView = findViewById(R.id.login_form);
    mProgressView = findViewById(R.id.login_progress);

     //other codes
}

希望有帮助

答案 1 :(得分:0)

在使用mProgressView和mLoginFormView之前,先给它们赋值。

        @Override
        public void onClick(View view) {
            attemptLogin();
            mLoginFormView = findViewById(R.id.login_form);
            mProgressView = findViewById(R.id.login_progress);
        }

从崩溃日志中可以明显看出,尝试登录将使用仅在之后设置的mProgressView。所以可能会起作用:

        @Override
        public void onClick(View view) {
            mLoginFormView = findViewById(R.id.login_form);
            mProgressView = findViewById(R.id.login_progress);
            attemptLogin();
        }

Radesh的答案也可能有用。