应用程序运行时会自动崩溃

时间:2018-06-13 04:49:41

标签: android nullpointerexception

Shutting down VM
06-13 10:08:20.934 27283-27283/design.nxn.login_template_01 E/AndroidRuntime: FATAL EXCEPTION: main
Process: design.nxn.login_template_01, PID: 27283
    java.lang.RuntimeException: Unable to start activity ComponentInfo{design.nxn.login_template_01/design.nxn.login_template_01.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534)
        at android.app.ActivityThread.access$900(ActivityThread.java:164)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:159)
        at android.app.ActivityThread.main(ActivityThread.java:5461)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.common.SignInButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at design.nxn.login_template_01.LoginActivity.initializeControls(LoginActivity.java:63)
        at design.nxn.login_template_01.LoginActivity.onCreate(LoginActivity.java:56)
        at android.app.Activity.performCreate(Activity.java:6093)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534) 
        at android.app.ActivityThread.access$900(ActivityThread.java:164) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:159) 
        at android.app.ActivityThread.main(ActivityThread.java:5461) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759) 

这是我的build.gradle(app)文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.3'
    defaultConfig {
        applicationId "design.nxn.login_template_01"
        minSdkVersion 21
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    } }

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    implementation 'com.android.support:appcompat-v7:27.+'


    implementation 'com.google.android.gms:play-services-auth:15.0.1'

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.github.bumptech.glide:glide:3.7.0'

}

这是我的 LoginActivity.java 文件

package design.nxn.login_template_01;

import android.app.ProgressDialog;

导入android.content.Intent;

导入android.os.Bundle;

import android.support.annotation.NonNull;

import android.support.v4.app.Fragment;

import android.util.Log;

导入android.view.View;

导入android.widget.Toast;

导入com.google.android.gms.auth.api.Auth;

导入com.google.android.gms.auth.api.signin.GoogleSignInAccount;

导入com.google.android.gms.auth.api.signin.GoogleSignInClient;

导入com.google.android.gms.auth.api.signin.GoogleSignInOptions;

导入com.google.android.gms.auth.api.signin.GoogleSignInResult;

导入com.google.android.gms.common.ConnectionResult;

导入com.google.android.gms.common.SignInButton;

导入com.google.android.gms.common.api.GoogleApiClient;

导入com.google.android.gms.tasks.Task;

import java.util.Objects;

import design.nxn.login_template_01.Tools.CustomViewPager;

import design.nxn.login_template_01.Tools.ViewPagerAdapter;

公共类LoginActivity扩展BaseActivity实现了GoogleApiClient.OnConnectionFailedListener

{

private static final String TAG = BaseActivity.class.getSimpleName();

private static final int RC_SIGN_IN = 420;

private GoogleApiClient mGoogleApiClient;

private ProgressDialog mProgressDialog;

private SignInButton btnSignIn;

private GoogleSignInClient mGoogleSignInClient;

private String personPhotoUrl;


private static final int LOGIN_FRAGMENT = 0;

private static final int SIGNUP_FRAGMENT = 1;

private static final int RESET_PASSWORD_FRAGMENT = 2;

private Fragment newFragment;

private CustomViewPager viewPager;

private ViewPagerAdapter viewPagerAdapter;



@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_login);


    btnSignIn = (SignInButton)findViewById(R.id.sign_in_button);

    initializeGPlusSettings();

    initializeControls();


    viewPager = findViewById(R.id.viewpager);

    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

    viewPager.setAdapter(viewPagerAdapter);

    viewPager.setPagingEnabled(false);

    changeFragment(LOGIN_FRAGMENT);



}

private void initializeControls() {

    btnSignIn.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            Intent signInIntent = 

Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);

            startActivityForResult(signInIntent, RC_SIGN_IN);


        }

    });

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) 

{

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RC_SIGN_IN) {

        GoogleSignInResult result = 

Auth.GoogleSignInApi.getSignInResultFromIntent(数据);

        handleGPlusSignInResult(result);

    }

}

private void handleGPlusSignInResult(GoogleSignInResult result) {

    Log.d(TAG,"handleSignInResult:" +result.isSuccess());

    if (result.isSuccess()){

        GoogleSignInAccount acct = result.getSignInAccount();

        String personname = acct.getDisplayName();

        personPhotoUrl = Objects.requireNonNull(acct.getPhotoUrl()).toString();

        String personEmail = acct.getEmail();

        Intent intent = new 

意图(LoginActivity.this,SecondActivity.class);

        intent.putExtra("personname",personname);

        intent.putExtra("email",personEmail);

        intent.putExtra("personphotoUrl",personPhotoUrl);

        startActivity(intent);

        finish();

    }

}

private void handleSignInResult(Task<GoogleSignInAccount> task) {

}

private void initializeGPlusSettings() {
    // Configure sign-in to request the user's ID, email address, and basic

//个人资料。 ID和基本配置文件包含在DEFAULT_SIGN_IN中。

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
    // Build a GoogleSignInClient with the options specified by gso.

   mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();

    btnSignIn.setSize(SignInButton.SIZE_STANDARD);



}

private void changeFragment(int fragmentType) {

    switch (fragmentType) {

        case LOGIN_FRAGMENT:

            viewPager.setCurrentItem(LOGIN_FRAGMENT);

            break;

        case SIGNUP_FRAGMENT:

            viewPager.setCurrentItem(SIGNUP_FRAGMENT);

            break;

        case RESET_PASSWORD_FRAGMENT:

            viewPager.setCurrentItem(RESET_PASSWORD_FRAGMENT);

            break;

        default:

            viewPager.setCurrentItem(LOGIN_FRAGMENT);

            break;

    }


}

public void signUpClick(View view) {

    changeFragment(SIGNUP_FRAGMENT);

}

public void signInClick(View view) {

    changeFragment(LOGIN_FRAGMENT);

}

public void resetPasswordClick(View view) {

    changeFragment(RESET_PASSWORD_FRAGMENT);

}

public void backClick(View view){

    changeFragment(LOGIN_FRAGMENT);

}

@Override

public void onBackPressed() {

    if (viewPager.getCurrentItem() == LOGIN_FRAGMENT)

        super.onBackPressed();

    else {

        changeFragment(LOGIN_FRAGMENT);

    }

}

public void logInButtonClicked() {

    Toast.makeText(this, R.string.login_button_click, Toast.LENGTH_SHORT).show();

}

public void signUpButtonClicked() {

    Toast.makeText(this, R.string.signup_button_click, Toast.LENGTH_SHORT).show();

}

public void resetPasswordButtonClicked() {

    Toast.makeText(this, R.string.reset_password_button_clicked, Toast.LENGTH_SHORT).show();

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)  

{


 }

}

这是我的 fragment_login.xml 代码

android:id="@+id/content_login"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@drawable/login_bg"

android:orientation="vertical">


<RelativeLayout

    android:layout_width="match_parent"

    android:layout_height="0dp"

    android:layout_weight="1">

    <ImageView

        android:layout_width="98dp"

        android:layout_height="99dp"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="62dp"

        android:padding="10dp"

        android:src="@drawable/vidya" />


</RelativeLayout>


<RelativeLayout

    android:layout_width="match_parent"

    android:layout_height="100dp"

    android:layout_weight="1">

    <RelativeLayout

        android:id="@+id/email_layout"

        android:layout_width="match_parent"

        android:layout_height="50dp">

        <ImageView

            android:id="@+id/user_icon"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerVertical="true"

            android:layout_marginLeft="20dp"

            android:layout_marginRight="20dp"

            android:src="@drawable/ic_email" />

        <design.nxn.login_template_01.customfonts.MyEditText

            android:id="@+id/email_edittext"

            android:layout_width="304dp"

            android:layout_height="match_parent"

            android:layout_centerVertical="true"

            android:layout_marginRight="20dp"

            android:layout_toRightOf="@+id/user_icon"

            android:background="@android:color/transparent"

            android:hint="@string/email"

            android:inputType="textEmailAddress"

            android:singleLine="true"

            android:textColor="@color/white"

            android:textColorHint="@color/light_text"

            android:textSize="@dimen/text_size_medium" />


        <View

            android:layout_width="match_parent"

            android:layout_height="1dp"

            android:layout_alignParentBottom="true"

            android:background="@color/divider" />


    </RelativeLayout>

    <RelativeLayout

        android:id="@+id/password_layout"

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_below="@+id/email_layout">



        <ImageView

            android:id="@+id/password_icon"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerVertical="true"

            android:layout_marginLeft="20dp"

            android:layout_marginRight="20dp"

            android:src="@drawable/ic_password" />


        <design.nxn.login_template_01.customfonts.MyEditText

            android:id="@+id/password_edittext"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:layout_centerVertical="true"

            android:layout_marginRight="20dp"

            android:layout_toRightOf="@+id/password_icon"

            android:background="@android:color/transparent"

            android:hint="@string/password"

            android:inputType="textPassword"

            android:singleLine="true"

            android:textColor="@color/white"

            android:textColorHint="@color/light_text"

            android:textSize="@dimen/text_size_medium" />


        <View

            android:layout_width="match_parent"

            android:layout_height="1dp"

            android:layout_alignParentBottom="true"

            android:background="@color/divider" />

    </RelativeLayout>

    <TextView

        android:id="@+id/forgotpassword"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginLeft="250dp"

        android:layout_marginTop="105dp"

        android:text="@string/forgot_password"

        android:onClick="resetPasswordClick"

        android:textColor="@color/white" />




    <com.google.android.gms.common.SignInButton

        android:id="@+id/sign_in_button"

        android:layout_width="150dp"

        android:layout_height="wrap_content"

        android:layout_marginTop="150dp"

        android:layout_marginLeft="220dp"/>



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="or"


        android:textColor="@color/white"

        android:layout_marginTop="160dp"

        android:layout_marginLeft="180dp"

        android:gravity="center_vertical"/>




    <RelativeLayout

        android:id="@+id/button_layout"

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:layout_above="@+id/signup_layout"

        android:background="@color/navyblue">



        <LinearLayout

            android:id="@+id/login_button"

            style="@style/Widget.AppCompat.Button.Borderless"

            android:layout_width="match_parent"

            android:layout_height="match_parent"

            android:layout_alignParentStart="true"

            android:layout_alignParentTop="true"

            android:clickable="true"

            android:onClick="logInButtonClicked"

            android:text="@string/forgot_password">



            <design.nxn.login_template_01.customfonts.MyTextView

                android:layout_width="wrap_content"

                android:layout_height="40dp"

                android:gravity="center"

                android:text="@string/sign_in"

                android:backgroundTintMode="multiply"

                android:textColor="@color/white"

                android:textSize="@dimen/text_size_big" />
        </LinearLayout>

    </RelativeLayout>

    <RelativeLayout

        android:id="@+id/signup_layout"

        android:layout_width="match_parent"

        android:layout_height="50dp"

        android:layout_alignParentBottom="true">


        <LinearLayout

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerInParent="true"

            android:gravity="center"

            android:orientation="horizontal">


            <design.nxn.login_template_01.customfonts.MyTextView

                android:layout_width="wrap_content"

                android:layout_height="30dp"

                android:background="@android:color/transparent"

                android:gravity="center"

                android:text="@string/dont_have_account"

                android:textColor="@color/light_text"

                android:textColorHint="@color/white"

                android:textSize="@dimen/text_size_medium" />


            <LinearLayout

                style="@style/Widget.AppCompat.Button.Borderless"

                android:layout_width="wrap_content"

                android:layout_height="40dp"

                android:layout_marginLeft="-10dp"

                android:clickable="true"

                android:onClick="signUpClick"

                android:text="@string/forgot_password">


                <design.nxn.login_template_01.customfonts.MyTextView

                    android:layout_width="wrap_content"

                    android:layout_height="40dp"

                    android:gravity="center"

                    android:text="@string/sign_up"

                    android:textColor="@color/white"

                    android:textSize="@dimen/text_size_medium" />


            </LinearLayout>

        </LinearLayout>
    </RelativeLayout>


</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

调用initializeControls();在initializeGPlusSettings()之后;您的mGoogleApiClient未初始化,您正在将其用于onClickListener()

第二件事

你在你的两个函数中使用了你的按钮(btnSignIn),它初始化为一个函数initializeControls(),所以问题进入另一个函数,将你的按钮初始化为onCreate()。

更改您的代码,如

 btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);

 initializeGPlusSettings();

 initializeControls();

}

private void initializeControls() {

btnSignIn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(**mGoogleApiClient**);
        startActivityForResult(signInIntent, RC_SIGN_IN);

    }
});

}