我想在我的安卓应用中实现多用户登录。

huangapple go评论81阅读模式
英文:

i want to create a multiple user login to my android app

问题

public class MainActivity extends AppCompatActivity {

    // ... (other imports and variable declarations)

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

        // ... (other initialization code)

        Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                validate(Name.getText().toString().trim(), Password.getText().toString().trim());
            }
        });

        // ... (other click listeners)
    }

    private void validate(String userName, String userPassword) {
        progressDialog.setMessage("Please wait till you are verified!");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        firebaseAuth.signInWithEmailAndPassword(userName, userPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    progressDialog.dismiss();
                    checkEmailVerification();
                } else {
                    Toast.makeText(MainActivity.this, "Login Failed", Toast.LENGTH_SHORT).show();
                    counter--;
                    Info.setText("No of attempts remaining: " + counter);
                    progressDialog.dismiss();
                    if (counter == 0) {
                        Login.setEnabled(false);
                    }
                }
            }
        });
    }

    private void checkEmailVerification() {
        FirebaseUser firebaseUser = firebaseAuth.getInstance().getCurrentUser();
        Boolean emailflag = firebaseUser.isEmailVerified();

        if (emailflag) {
            if (isAdmin(firebaseUser.getUid())) {
                // Start the admin activity
                startActivity(new Intent(MainActivity.this, AdminHome.class));
            } else {
                // Start the user activity
                startActivity(new Intent(MainActivity.this, UserHome.class));
            }
        } else {
            Toast.makeText(this, "Verify your email", Toast.LENGTH_SHORT).show();
            firebaseAuth.signOut();
        }
    }

    private boolean isAdmin(String uid) {
        // Implement your logic to check if the user with the given UID is an admin
        // This could involve querying your database or using a certain property to mark admins
        // Return true if the user is an admin, false otherwise
        return false; // Placeholder, replace with your logic
    }

    // ... (other code)
}

In the code above, I've added a method isAdmin() that you need to implement. This method checks whether the user with the given UID is an admin or not. You should replace the placeholder return false; with your actual logic to determine if the user is an admin.

Regarding the error you're encountering when the user clicks the login button without entering anything, the error message indicates that the signInWithEmailAndPassword() method is receiving an empty or null string as an argument. You should add a validation check before calling this method to ensure that both the email and password are not empty or null.

英文:

i have a created a registration page for user. if user enter the details it will save in database. when user want to login user will identify from the firebase auth. if i click user name and password it will only identify the user. i have create a admin part in database without register from the app and i want to create a seperate UI for admin.

i want to know how to identify the admin and user from database and give a separate intent function for user and admin
This is how its display in Database i have create a admin part seperately.

And this is the code to login to the app

public class MainActivity extends AppCompatActivity {
private EditText Name;
private EditText Password;
private Button Login;
private TextView Info;
private int counter = 5;
private TextView userRegistartion;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private TextView forgotPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
Name = (EditText) findViewById(R.id.etName);
Password = (EditText) findViewById(R.id.etPassword);
Login = (Button) findViewById(R.id.btnLogin);
Info = (TextView) findViewById(R.id.tvInfo);
userRegistartion = (TextView) findViewById(R.id.tvRegister);
forgotPassword = (TextView) findViewById(R.id.tvForgotPassword);
Info.setText(&quot;No of attempts remaining: 5&quot;);
//Instance for Firebase authentication forApp
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
//checking in database if user already login or not
FirebaseUser user = firebaseAuth.getCurrentUser();
//if user already logged in move to next activity
if(user != null){
finish();
startActivity(new Intent(MainActivity.this, AdminHome.class));
}
Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validate(Name.getText().toString().trim(), Password.getText().toString().trim());
}
});
userRegistartion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, Registration.class));
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, PasswordActivity.class));
}
});
}
//Declaring User name and Password
private void validate (String userName, String userPassword){
progressDialog.setMessage(&quot;Please wait till you are verified!&quot;);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(userName, userPassword).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
@Override
public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
if (task.isSuccessful()){
progressDialog.dismiss();
checkEmailVerification();
}else{
Toast.makeText(MainActivity.this, &quot;Login Failed&quot;, Toast.LENGTH_SHORT).show();
counter--;
Info.setText(&quot;No of attempts remaining: &quot; + counter);
progressDialog.dismiss();
if (counter == 0){
Login.setEnabled(false);
}
}
}
});
}
//verifying email
private void checkEmailVerification(){
FirebaseUser firebaseUser = firebaseAuth.getInstance() .getCurrentUser();
Boolean emailflag = firebaseUser.isEmailVerified();
startActivity(new Intent(MainActivity.this, AdminHome.class));
/*if (emailflag){
finish();
startActivity(new Intent(MainActivity.this, Hone.class));
}else{
Toast.makeText(this, &quot;Verify your email&quot;, Toast.LENGTH_SHORT).show();
firebaseAuth.signOut();
}*/
}
@Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(&quot;Are you sure you want to Exit?&quot;)
.setCancelable(false)
.setPositiveButton(&quot;Yes&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
MainActivity.super.onBackPressed();
}
})
.setNegativeButton(&quot;No&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}

}

i want to create a intent for admin to how can i create it on this code and where should i want to change it??<br>

And ther's a bug too when user click the login button without entering anything the application will close whats the error??

This is how it display when the button clicks<br>

E/AndroidRuntime: FATAL EXCEPTION: main&lt;br&gt;
Process: com.example.lms, PID: 14769&lt;br&gt;
java.lang.IllegalArgumentException: Given String is empty or null&lt;br&gt;
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown Source:5)&lt;br&gt;
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(com.google.firebase:firebase-auth@@19.3.0:205)&lt;br&gt;
at com.example.lms.MainActivity.validate(MainActivity.java:98)&lt;br&gt;
at com.example.lms.MainActivity.access$200(MainActivity.java:25)&lt;br&gt;
at com.example.lms.MainActivity$1.onClick(MainActivity.java:70)&lt;br&gt;
at android.view.View.performClick(View.java:6597)&lt;br&gt;
at android.view.View.performClickInternal(View.java:6574)&lt;br&gt;
at android.view.View.access$3100(View.java:778)&lt;br&gt;
at android.view.View$PerformClick.run(View.java:25885)&lt;br&gt;
at android.os.Handler.handleCallback(Handler.java:873)&lt;br&gt;
at android.os.Handler.dispatchMessage(Handler.java:99)&lt;br&gt;
at android.os.Looper.loop(Looper.java:193)&lt;br&gt;
at android.app.ActivityThread.main(ActivityThread.java:6669)&lt;br&gt;
at java.lang.reflect.Method.invoke(Native Method)&lt;br&gt;
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)&lt;br&gt;
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)&lt;br&gt;

答案1

得分: 0

Sure, here's the translated code:

Login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (Name.getText().toString().equals("")) {
            Email.setError("请输入电子邮件");
        } else if (Password.getText().toString().equals("")) {
            Password.setError("请输入密码");
        } else {
            validate(Name.getText().toString().trim(), Password.getText().toString().trim());
        }
    }
});

Please note that I've translated the error messages for "Please Enter Email" and "Please Enter Password" into Chinese.

英文:

Change

 Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validate(Name.getText().toString().trim(), Password.getText().toString().trim());
}
});

to

 Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Name.getText().toString().equals(&quot;&quot;)){
Email.setError(&quot;Please Enter Email&quot;);   
}else if (Password.getText().toString().equals(&quot;&quot;)){
Password.setError(&quot;Please Enter Password&quot;);
}else {
validate(Name.getText().toString().trim(), Password.getText().toString().trim());
}
}
});

答案2

得分: 0

希望这段代码能对你有所帮助。
你需要添加验证检查。

Login.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (Name.getText().toString().equals("")) {
            Email.setError("请输入有效的电子邮件地址");
        } else if (Password.getText().toString().equals("")) {
            Password.setError("请输入密码");
        } else {
            validate(Name.getText().toString().trim(), Password.getText().toString().trim());
        }
    }
});
英文:

May this code help you.
You have to put the validation checks.

Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Name.getText().toString().equals(&quot;&quot;)){
Email.setError(&quot;Please Enter Vaild Email&quot;);   
}else if (Password.getText().toString().equals(&quot;&quot;)){
Password.setError(&quot;Please Enter Password&quot;);
}else {
validate(Name.getText().toString().trim(), Password.getText().toString().trim());
}
}
});

huangapple
  • 本文由 发表于 2020年5月3日 15:47:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/61571186.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定