英文:
onClick Sign Up method includes onClick Datepicker, how to make it work?
问题
package com.example.sportsbuddyz;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
import java.util.HashMap;
public class registerPage extends AppCompatActivity implements View.OnClickListener {
EditText jEmailEt, jPasswordEt;
Button jSignUpBtn;
ProgressDialog progressDialog;
private FirebaseAuth mAuth;
TextView jAccountExist;
EditText jName, jStudentID, jPhoneNumber, jAddress;
TextView jDOB, jAutoAge;
DatePickerDialog.OnDateSetListener mDateSetListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registerpage);
jEmailEt = findViewById(R.id.emailEt);
jPasswordEt = findViewById(R.id.passwordEt);
mAuth = FirebaseAuth.getInstance();
jName = findViewById(R.id.nameEt);
jStudentID = findViewById(R.id.studentIDEt);
jPhoneNumber = findViewById(R.id.phoneEt);
jAddress = findViewById(R.id.addressEt);
jDOB = findViewById(R.id.DOB);
jAutoAge = findViewById(R.id.AgeAuto);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Sign Up Account");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Progressing User...");
findViewById(R.id.signupBtn).setOnClickListener(this);
findViewById(R.id.accountExist).setOnClickListener(this);
findViewById(R.id.DOB).setOnClickListener(this);
}
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.signupBtn:{
registerUser();
}
break;
case R.id.accountExist: {
startActivity(new Intent(registerPage.this, loginPage.class));
finish();
}
break;
}
}
private void registerUser(){
progressDialog.show();
String email = jEmailEt.getText().toString().trim();
String password = jPasswordEt.getText().toString().trim();
String name = jName.getText().toString().trim();
String studentID = jStudentID.getText().toString().trim();
String phoneNo = jPhoneNumber.getText().toString().trim();
String address = jAddress.getText().toString().trim();
if (email.isEmpty()) {
jEmailEt.setError("Email must not be empty");
jEmailEt.setFocusable(true);
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
jEmailEt.setError("Invalid Email");
jEmailEt.setFocusable(true);
return;
}
// ... (similar validation checks for other fields)
jDOB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(registerPage.this, android.R.style.Theme_Holo_Dialog_MinWidth, mDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
String dobDate = day + "/" + month + "/" + year;
jDOB.setText(dobDate);
jAutoAge.setText(getAge(year, month, day));
}
};
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
FirebaseUser user = mAuth.getCurrentUser();
// ... (storing user information in Firebase database)
Toast.makeText(registerPage.this, "Registered..\n" + user.getEmail(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(registerPage.this, dashBoard.class));
finish();
} else {
progressDialog.dismiss();
Toast.makeText(registerPage.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(registerPage.this, "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
// ... (getAge function and other methods)
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".registerPage">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!-- View components similar to the original XML layout -->
</RelativeLayout>
</ScrollView>
</RelativeLayout>
英文:
Using Firebase to save User's information by Registering/SignUp. Then I met an obstacle....
I'm using switch case for onClick, which one is for registerpage() method which in form of Button & another for going to next activity via textview. But at the registerpage() method, there is a onClick DatePicker (for selecting dateOfBirth) . But the onClick for DatePicker doesn't work. Here's my code. Thank you.
registerPage.java
package com.example.sportsbuddyz;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.tv.TvContract;
import android.nfc.Tag;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
public class registerPage extends AppCompatActivity implements View.OnClickListener {
EditText jEmailEt, jPasswordEt;
Button jSignUpBtn;
ProgressDialog progressDialog;
private FirebaseAuth mAuth;
TextView jAccountExist;
EditText jName, jStudentID, jPhoneNumber, jAddress;
TextView jDOB, jAutoAge;
DatePickerDialog.OnDateSetListener mDateSetListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registerpage);
jEmailEt = findViewById(R.id.emailEt);
jPasswordEt = findViewById(R.id.passwordEt);
//jSignUpBtn = findViewById(R.id.signupBtn);
mAuth = FirebaseAuth.getInstance();
//jAccountExist = findViewById(R.id.accountExist);
jName = findViewById(R.id.nameEt);
jStudentID = findViewById(R.id.studentIDEt);
jPhoneNumber = findViewById(R.id.phoneEt);
jAddress = findViewById(R.id.addressEt);
jDOB = findViewById(R.id.DOB);
jAutoAge = findViewById(R.id.AgeAuto);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Sign Up Account");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Progressing User...");
findViewById(R.id.signupBtn).setOnClickListener(this);
findViewById(R.id.accountExist).setOnClickListener(this);
findViewById(R.id.DOB).setOnClickListener(this);
}
@Override
public void onClick(View view){
switch (view.getId()){
//CASE 1 -- SignUp Button
case R.id.signupBtn:{
registerUser();
}
break;
//CASE 2 -- AccountExist(Text)
case R.id.accountExist: {
startActivity(new Intent(registerPage.this, loginPage.class));
finish();
}
break;
}
}
private void registerUser(){
progressDialog.show();
String email = jEmailEt.getText().toString().trim();
String password = jPasswordEt.getText().toString().trim();
String name = jName.getText().toString().trim();
String studentID = jStudentID.getText().toString().trim();
String phoneNo = jPhoneNumber.getText().toString().trim();
String address = jAddress.getText().toString().trim();
if (email.isEmpty()) {
jEmailEt.setError("Email must not be empty");
jEmailEt.setFocusable(true);
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
jEmailEt.setError("Invalid Email");
jEmailEt.setFocusable(true);
return;
}
if (password.isEmpty()) {
jPasswordEt.setError("Password must not be empty");
jPasswordEt.setFocusable(true);
return;
}
if (password.length() < 6) {
jPasswordEt.setError("Password must be at least 6 digit");
jPasswordEt.setFocusable(true);
return;
}
if (name.isEmpty()) {
jName.setError("Name must not be empty");
jName.setFocusable(true);
return;
}
if (studentID.isEmpty()) {
jStudentID.setError("Student ID must not be empty");
jStudentID.setFocusable(true);
return;
}
if (phoneNo.isEmpty()) {
jPhoneNumber.setError("Phone Number must not be empty");
jPhoneNumber.setFocusable(true);
return;
}
if (address.isEmpty()) {
jAddress.setError("Address must not be empty");
jAddress.setFocusable(true);
return;
}
jDOB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(registerPage.this, android.R.style.Theme_Holo_Dialog_MinWidth, mDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
String dobDate = day + "/" + month + "/" + year;
jDOB.setText(dobDate);
jAutoAge.setText(getAge(year, month, day));
}
};
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, dismiss dialog & start register activity
progressDialog.dismiss();
//User userDetail = new User(email, name, studentID, phoneNo, address);
FirebaseUser user = mAuth.getCurrentUser();
//Get User email and UID from auth
String email = user.getEmail();
String uid = user.getUid();
String name = jName.getText().toString().trim();
String studentID = jStudentID.getText().toString().trim();
String phoneNo = jPhoneNumber.getText().toString().trim();
String address = jAddress.getText().toString().trim();
String DOB = jDOB.getText().toString().trim();
String Age = jAutoAge.getText().toString().trim();
//User is registered store user info in Firebase realtime database also
HashMap<Object,String> hashMap = new HashMap<>();
//Put Info in HashMap
hashMap.put("email",email);
hashMap.put("uid",uid);
hashMap.put("name", name);
hashMap.put("studentID", studentID);
hashMap.put("phone",phoneNo);
hashMap.put("address",address);
hashMap.put("Date Of Birth", DOB);
hashMap.put("Age",Age);
hashMap.put("image","");
hashMap.put("cover","");
//Firebase database instance
FirebaseDatabase database = FirebaseDatabase.getInstance();
//path to store user data named "Users"
DatabaseReference reference = database.getReference("Users");
//Put data within HashMap in database
reference.child(uid).setValue(hashMap);
Toast.makeText(registerPage.this, "Registered..\n"+user.getEmail(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(registerPage.this, dashBoard.class));
finish();
} else {
// If sign in fails, display a message to the user.
progressDialog.dismiss();
Toast.makeText(registerPage.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(registerPage.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private String getAge(int year, int month, int day){
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(year, month, day);
int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)){
age--;
}
Integer ageInt = new Integer(age);
String ageS = ageInt.toString();
return ageS;
}
@Override
public boolean onSupportNavigateUp(){
onBackPressed();
return super.onSupportNavigateUp();
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
registerpage.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".registerPage">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--Confirm Sign Up Button-->
<Button
android:id="@+id/signupBtn"
style="@style/Widget.AppCompat.Button.Small"
android:layout_width="163dp"
android:layout_height="47dp"
android:layout_centerHorizontal="true"
android:background="@drawable/loginbutton"
android:text="Sign Up"
android:layout_below="@id/accountExist"
android:layout_margin="10dp"
android:textAllCaps="false"
android:textStyle="bold" />
<!--EmailAddress-->
<android.support.design.widget.TextInputLayout
android:id="@+id/emailTIL"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="120dp">
<EditText
android:id="@+id/emailEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email Address"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<!--Password-->
<android.support.design.widget.TextInputLayout
android:id="@+id/passwordTIL"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_below="@+id/emailTIL"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/passwordEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
<!--Name-->
<android.support.design.widget.TextInputLayout
android:id="@+id/nameTIL"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_below="@+id/passwordTIL"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/nameEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Full Name"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<!--Student ID-->
<android.support.design.widget.TextInputLayout
android:id="@+id/studentIDTIL"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_below="@+id/nameTIL"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/studentIDEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Student ID" />
</android.support.design.widget.TextInputLayout>
<!--Phone Number-->
<android.support.design.widget.TextInputLayout
android:id="@+id/phoneTIL"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_below="@+id/studentIDTIL"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/phoneEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone No."
android:inputType="phone" />
</android.support.design.widget.TextInputLayout>
<!--DOB-->
<TextView
android:id="@+id/DOB"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginBottom="140dp"
android:textAlignment="center"
android:hint="Date of Birth"
android:layout_below="@+id/addressTIL"
android:layout_marginTop="10dp"
android:layout_marginLeft="30dp"
android:textSize="20dp"/>
<!--Age-->
<TextView
android:id="@+id/AgeAuto"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginBottom="140dp"
android:textAlignment="center"
android:hint="Age"
android:layout_toRightOf="@+id/DOB"
android:layout_below="@id/addressTIL"
android:layout_margin="10dp"
android:layout_marginLeft="10dp"
android:textSize="20dp"/>
<!--Address-->
<android.support.design.widget.TextInputLayout
android:id="@+id/addressTIL"
android:layout_width="325dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_below="@+id/phoneTIL"
app:passwordToggleEnabled="true">
<EditText
android:id="@+id/addressEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:inputType="textShortMessage"/>
</android.support.design.widget.TextInputLayout>
<!--Already Register? Login now-->
<TextView
android:id="@+id/accountExist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="140dp"
android:textAlignment="center"
android:text="Already have account? Login now"
android:layout_below="@+id/AgeAuto"
android:layout_margin="10dp"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
答案1
得分: 0
请注意,以下是您要翻译的内容:
请尝试以下添加DatePicker的方法:
首先,在XML中以这种方式添加DatePicker:
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>
现在进入您的Activity.java文件:
//您可以使用可见性函数来显示/隐藏日期选择器。
//或者尝试创建一个包含DatePicker的弹出窗口。这样做会更容易,而且看起来更清晰。
DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker);
datePicker.setSpinnersShown(false);
在点击jDOB之后:
//jDOB.setOnClickListener:
String day = "Day = " + datePicker.getDayOfMonth();
String month = "Month = " + datePicker.getMonth();
String year = "Year = " + datePicker.getYear();
String dobDate = day + "/" + month + "/" + year;
jDOB.setText(dobDate);
<details>
<summary>英文:</summary>
Can you try this way of adding DatePicker?
First add the DatePicker in XML this way:
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>
Now go to your Activity.java:
//You can use visibility function to show/hide the datapicker.
// Or try creating a pop-up containing the DatePicker. It will be easy and look cleaner.
DatePicker datePicker = (DatePicker)findViewById(R.id.datePicker);
datePicker.setSpinnersShown(false);
Now after clicking the jDOB :
//jDOB.setOnClickListener:
String day = "Day = " + datePicker.getDayOfMonth();
String month = "Month = " + datePicker.getMonth();
String year = "Year = " + datePicker.getYear();
String dobDate = day + "/" + month + "/" + year;
jDOB.setText(dobDate);
</details>
# 答案2
**得分**: 0
```java
你注册了两次点击监听器
在xml中使用了onClick,在Java代码中使用了setOnClickListener
所以你需要移除其中一个... 在你的情况下移除onClickListener,然后将你的代码放在switch case中
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.DOB:
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(registerPage.this, android.R.style.Theme_Holo_Dialog_MinWidth, mDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
break;
}
}
英文:
You registered the click listener twice
onClick in xml and setOnClickListener in java code
So you have to remove one of them .. in your case remove onClickListener and put your code in switch case
@Override
public void onClick(View view){
switch (view.getId()){
case R.id.DOB:
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(registerPage.this, android.R.style.Theme_Holo_Dialog_MinWidth, mDateSetListener, year, month, day);
datePickerDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
break;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论