Работаю в AndroidStudioи, у меня есть форма регистрации. Подключена база данных FireBase. Когда пользователь входит, его переносит на другую активити. Но при повторном заходе в приложение, опять выскакивает вход. Как сделать так, чтобы программа проверяла, вошёл ли пользователь в приложение, и,если вошёл, сразу перекидывала его на вторую активити? А так же как сделать выход?
package com.example.homeworkhelper;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.example.homeworkhelper.Models.User;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.rengwuxian.materialedittext.MaterialEditText;
public class MainActivity extends AppCompatActivity {
Button btnSignIn, btnRegister;
FirebaseAuth auth;
FirebaseDatabase db;
DatabaseReference users;
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
String phonePattern = "[+]+[0-9]";
RelativeLayout root;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
btnSignIn = findViewById(R.id.ci);
btnRegister = findViewById(R.id.perreg);
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
users = db.getReference("Users");
root = findViewById(R.id.root_element);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showRegisterWindow();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showSingInWindow();
}
});
}
private void showSingInWindow() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Login");
dialog.setMessage("Enter data");
LayoutInflater inflater = LayoutInflater.from(this);
View sign_in_window = inflater.inflate(R.layout.sign_in_window, null);
dialog.setView(sign_in_window);
final MaterialEditText email = sign_in_window.findViewById(R.id.email);
final MaterialEditText pass = sign_in_window.findViewById(R.id.pass);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
}
});
dialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
if(TextUtils.isEmpty(email.getText().toString())) {
Snackbar.make(root, "Enter your E-mail", Snackbar.LENGTH_SHORT).show();
return;
}
if(pass.getText().toString().length() < 6) {
Snackbar.make(root, "Password must not be shorter than 6 characters\n", Snackbar.LENGTH_SHORT).show();
return;
}
auth.signInWithEmailAndPassword(email.getText().toString(), pass.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Snackbar.make(root, "Authorisation Error. "+ e.getMessage(), Snackbar.LENGTH_SHORT).show();
}
});
}
});
dialog.show();
}
private void showRegisterWindow() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Check in");
dialog.setMessage("Enter data");
LayoutInflater inflater = LayoutInflater.from(this);
View register_window = inflater.inflate(R.layout.register_window, null);
dialog.setView(register_window);
final MaterialEditText email = register_window.findViewById(R.id.email);
final MaterialEditText pass = register_window.findViewById(R.id.pass);
final MaterialEditText phone = register_window.findViewById(R.id.phone);
final MaterialEditText login = register_window.findViewById(R.id.login);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
}
});
dialog.setPositiveButton("Check in", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
if(TextUtils.isEmpty(email.getText().toString())) {
Snackbar.make(root, "Enter your E-mail", Snackbar.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(login.getText().toString())) {
Snackbar.make(root, "Enter your login", Snackbar.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(phone.getText().toString())) {
Snackbar.make(root, "Enter your phone number", Snackbar.LENGTH_SHORT).show();
return;
}
if(pass.getText().toString().length() < 6) {
Snackbar.make(root, "Password must not be shorter than 6 characters\n", Snackbar.LENGTH_SHORT).show();
return;
}
if (email.getText().toString().matches(emailPattern))
{
Toast.makeText(getApplicationContext(),"Valid email address",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Invalid email address", Toast.LENGTH_SHORT).show();
}
if (phone.getText().toString().matches(phonePattern))
{
Toast.makeText(getApplicationContext(),"Valid phone number",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(),"Invalid phone number", Toast.LENGTH_SHORT).show();
}
auth.createUserWithEmailAndPassword(email.getText().toString(), pass.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
@Override
public void onSuccess(AuthResult authResult) {
User user = new User();
user.setEmail((email.getText().toString()));
user.setLogin((login.getText().toString()));
user.setPass((pass.getText().toString()));
user.setPhone((phone.getText().toString()));
users.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Snackbar.make(root, "Registration Error. "+ e.getMessage(), Snackbar.LENGTH_SHORT).show();
}
});
}
});
dialog.show();
}
}