簡體   English   中英

單擊注冊按鈕后,應用程序停止工作

[英]App stops working when register button is clicked

我要注冊,然后單擊“注冊”按鈕時,將驗證電子郵件發送到該電子郵件地址。單擊電子郵件中的鏈接。該電子郵件即通過驗證。用戶現在可以從登錄屏幕登錄。

RegisterActivity.java

public class RegisterActivity extends AppCompatActivity {

private static final String TAG = "RegisterActivity";
private Context mContext;
private String email, username, password;
private EditText mEmail, mPassword, mUsername;
private TextView loadingPleaseWait;
private Button btnRegister;
private ProgressBar mProgressBar;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseMethods firebaseMethods;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String append = "";


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    mContext = RegisterActivity.this;
    //mAuth = FirebaseAuth.getInstance();
    firebaseMethods = new FirebaseMethods(mContext);
    Log.d(TAG, "onCreate: started.");
    initWidgets();
    setupFirebaseAuth();
    init();
}

private void init(){
    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            email = mEmail.getText().toString();
            username = mUsername.getText().toString();
            password = mPassword.getText().toString();
            if(checkInputs(email, username, password)){
                mProgressBar.setVisibility(View.VISIBLE);
                loadingPleaseWait.setVisibility(View.VISIBLE);
                firebaseMethods.registerNewEmail(email, password, username);
            }
        }
    });
}

private boolean checkInputs(String email, String username, String password){
    Log.d(TAG, "checkInputs: checking inputs for null values.");
    if(email.equals("") || username.equals("") || password.equals("")){
        Toast.makeText(mContext, "All fields must be filled out.", Toast.LENGTH_SHORT).show();
        return false;
    }
    return true;
}

private void initWidgets(){
    Log.d(TAG, "initWidgets: Initializing Widgets.");
    mEmail = (EditText) findViewById(R.id.input_email);
    mUsername = (EditText) findViewById(R.id.input_username);
    btnRegister = (Button) findViewById(R.id.btn_register);
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    loadingPleaseWait = (TextView) findViewById(R.id.loadingPleaseWait);
    mPassword = (EditText) findViewById(R.id.input_password);
    mContext = RegisterActivity.this;
    mProgressBar.setVisibility(View.GONE);
    loadingPleaseWait.setVisibility(View.GONE);

}

private boolean isStringNull(String string){
    Log.d(TAG, "isStringNull: checking string if null.");

    if(string.equals("")){
        return true;
    }
    else{
        return false;
    }
}


private void setupFirebaseAuth(){
    Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");

    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();

            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());

                myRef.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        //1st check: Make sure the username is not already in use
                        if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
                            append = myRef.push().getKey().substring(3,10);
                            Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
                        }
                        username = username + append;

                        //add new user to the database
                        firebaseMethods.addNewUser(email, username, "", "", "");

                        Toast.makeText(mContext, "Signup successful. Sending verification email.", Toast.LENGTH_SHORT).show();

                        mAuth.signOut();
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

                finish();

            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };
}

@Override
public void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);
}

@Override
public void onStop() {
    super.onStop();
    if (mAuthListener != null) {
        mAuth.removeAuthStateListener(mAuthListener);
    }
}
}

這是Firebase的方法,例如注冊新電子郵件,添加新用戶,發送驗證電子郵件等...

FirebaseMethods.java

public class FirebaseMethods {

private static final String TAG = "FirebaseMethods";

//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String userID;

private Context mContext;

public FirebaseMethods(Context context) {
    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    mContext = context;

    if(mAuth.getCurrentUser() != null){
        userID = mAuth.getCurrentUser().getUid();
    }
}

public boolean checkIfUsernameExists(String username, DataSnapshot datasnapshot){
    Log.d(TAG, "checkIfUsernameExists: checking if " + username + " already exists.");

    User user = new User();

    for (DataSnapshot ds: datasnapshot.child(userID).getChildren()){
        Log.d(TAG, "checkIfUsernameExists: datasnapshot: " + ds);

        user.setUsername(ds.getValue(User.class).getUsername());
        Log.d(TAG, "checkIfUsernameExists: username: " + user.getUsername());

        if(StringManipulation.expandUsername(user.getUsername()).equals(username)){
            Log.d(TAG, "checkIfUsernameExists: FOUND A MATCH: " + user.getUsername());
            return true;
        }
    }
    return false;
}

/**
 * Register a new email and password to Firebase Authentication
 * @param email
 * @param password
 * @param username
 */
public void registerNewEmail(final String email, String password, final String username){
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());

                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(mContext, R.string.auth_failed,Toast.LENGTH_SHORT).show();

                    }
                    else if(task.isSuccessful()){
                        //send verification email
                        sendVerificationEmail();

                        userID = mAuth.getCurrentUser().getUid();
                        Log.d(TAG, "onComplete: Authstate changed: " + userID);
                    }

                }
            });
}

public void sendVerificationEmail(){
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    if (user != null){
        user.sendEmailVerification()
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        if (task.isSuccessful()){

                        }else{
                            Toast.makeText(mContext,"Couldn't send verification email.",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}

public void addNewUser(String email, String username, String description, String website, String profile_photo){

    User user = new User( userID,  1,  email,  StringManipulation.condenseUsername(username) );

    myRef.child(mContext.getString(R.string.dbname_users))
            .child(userID)
            .setValue(user);


    UserAccountSettings settings = new UserAccountSettings(
            description,
            username,
            0,
            0,
            0,
            profile_photo,
            username,
            website
    );

    myRef.child(mContext.getString(R.string.dbname_user_account_settings))
            .child(userID)
            .setValue(settings);

}

}

這是日志行。

01-09 13:16:06.014 21548-21548 / com.example.vishal.myinstagram D / RegisterActivity:onAuthStateChanged:signed_out

01-09 13:16:06.015 21548-21588 / com.example.vishal.myinstagram D / FA:已連接到遠程服務

01-09 13:16:06.015 21548-21588 / com.example.vishal.myinstagram V / FA:處理排隊的服務任務:4

01-09 13:16:06.017 21548-21994 / com.example.vishal.myinstagram W / System:ClassLoader引用的未知路徑:/data/data/com.google.android.gms/app_chimera/m/0000003a/n/arm64 -v8a

01-09 13:16:11.043 21548-21588 / com.example.vishal.myinstagram V / FA:處於不活動狀態,與服務斷開連接

01-09 13:16:21.029 21548-21548 / com.example.vishal.myinstagram W / Settings:設置device_provisioned已從android.provider.Settings.Secure移至android.provider.Settings.Global。

01-09 13:16:21.957 21548-21548 / com.example.vishal.myinstagram W / InputEventReceiver:嘗試完成輸入事件,但輸入事件接收器已被處置。

01-09 13:16:32.737 21548-21548 / com.example.vishal.myinstagram D / RegisterActivity:checkInputs:檢查輸入是否為空值。

01-09 13:16:32.743 21548-21548 / com.example.vishal.myinstagram W / BiChannelGoogleApi:[FirebaseAuth:] getGoogleApiForMethod()返回了Gms

01-09 13:16:34.088 21548-21548 / com.example.vishal.myinstagram D / FirebaseMethods:createUserWithEmail:onComplete:false

提前致謝...

因此,在可以在視圖上設置任何OnClickListener之前,必須首先使用findViewById(R.id.button_register)初始化變量。 例如,

private Button registerButton;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    ...
    registerButton = (Button) findViewById(R.id.button_register);
    registerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //handle click event
        }
    });
    ...
}

值得一提的是,如果您使用支持庫> 26,則不再需要強制轉換視圖,並且可以在registerButton的初始化中省略(Button) Android Studio甚至會提示您不再需要強制轉換。 https://stackoverflow.com/a/44903372/7900721

現在, R.id是在布局XML文件中的視圖上設置的內容。

 <Button
 android:id="@+id/button_register"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="@string/my_button_text"/>

在文檔中搜索findViewById以獲取更多信息https://developer.android.com/reference/android/view/View.html

只是對一些更易讀的代碼的建議,我建議創建一個View.OnClickListener私有變量,您將其作為偵聽器傳遞,如下所示。

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    fab.setOnClickListener(clickListener);
}

/**
 * Handle click listeners
 */
private View.OnClickListener clickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //handle click event here
    }
};

因此,如果您開始處理多個點擊事件,則可以在一個部分中處理它們。 就其他人維護代碼的可讀性而言,它使諸如onCreate()更簡潔,以處理每個動作為目的,而不是掃描需要為每個setOnClickListener實例化的多個匿名類。

我的問題解決了...他們在我的jason文件中有問題...無論如何感謝大家...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM