Check if user is logged in to Mainactivity Android Studio

Asked

Viewed 375 times

-1

I have an app that successfully logs in, but when you log in to Mainactivity it simply disconnects from firebase auth, Listener is 0, how can I keep the user logged in after logging in too activitys?

Loginactivity

public class LoginActivity extends AppCompatActivity {

    private EditText emailTV, passwordTV;
    private Button loginBtn;
    private ProgressBar progressBar;

    private FirebaseAuth mAuth;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        mAuth = FirebaseAuth.getInstance();

        initializeUI();

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUserAccount();
            }
        });
        Button registrar = (Button)findViewById(R.id.registrar);

        registrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginActivity.this, RegistroActivity.class));
            }
        });
    }

    private void loginUserAccount() {
        progressBar.setVisibility(View.VISIBLE);

        String email, password;
        email = emailTV.getText().toString();
        password = passwordTV.getText().toString();

        if (TextUtils.isEmpty(email)) {
            Toast.makeText(getApplicationContext(), "INSIRA E-MAIL...", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(getApplicationContext(), "INSIRA SENHA!", Toast.LENGTH_LONG).show();
            return;
        }

        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            Toast.makeText(getApplicationContext(), "LOGADO COM SUCESSO!", Toast.LENGTH_LONG).show();
                            progressBar.setVisibility(View.GONE);

                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        }
                        else {
                            Toast.makeText(getApplicationContext(), "FALHA AO LOGAR TENTE NOVAMENTE", Toast.LENGTH_LONG).show();
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                });
    }

    private void initializeUI() {
        emailTV = (EditText) findViewById(R.id.email);
        passwordTV = (EditText) findViewById(R.id.password);

        loginBtn = (Button) findViewById(R.id.login);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
    }
}

Mainactivity

public class MainActivity extends AppCompatActivity {
    private FirebaseAuth mAuth;
    Button btn_send;
    EditText et_contact;
    TextView et_message;
    TextView textView52;
    private FirebaseAuth auth;
    private User usuario = new User();
    private DatabaseReference firebaseDatabase;
    private ValueEventListener valueEventListener;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();




        btn_send = (Button)findViewById(R.id.btn_send);
        et_contact = (EditText)findViewById(R.id.et_contact);
        et_message = (TextView) findViewById(R.id.et_message);



        PermissionToConnect();

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = et_contact.getText().toString();
                String message = et_message.getText().toString();

                try{
                    SmsManager smsManager = SmsManager.getDefault();
                    smsManager.sendTextMessage(number, null, message, null, null);
                    Toast.makeText(MainActivity.this, "Sent", Toast.LENGTH_SHORT).show();
                }catch (Exception e){
                    Toast.makeText(MainActivity.this, "Sending Failed", Toast.LENGTH_SHORT).show();
                }

            }
        });

        DatabaseReference databaseRef= FirebaseDatabase.getInstance()
                .getReference();

        databaseRef.child("Users").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()){
                    String data = ds.child("name").getValue(String.class);
                    et_message.setText(data);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }




    private void PermissionToConnect(){
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED){
            if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.SEND_SMS)){
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1);
            }else{
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.SEND_SMS}, 1);
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
      if(requestCode == 1) {
          if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
              if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
                  Toast.makeText(this, "Access", Toast.LENGTH_SHORT).show();
              }
          } else {
              Toast.makeText(this, "Denied", Toast.LENGTH_SHORT).show();
          }
      }
    }
}
  • I didn’t quite understand your question. But I think what you’re looking for is to log in 1 times just to browse the app. And to have to log in again the user has to log out is this?

  • Yes actually the login works, but when redirecting to mainactivity it is disconnected. wanted to keep the user logged in.

  • thank you for your reply. OBS it disconnects from firebase listerner auth main Activity works normally, only without firebase authentication running.

  • A tip I can give is the following, when logging in you can save a string as tolken in the SharedPreference to symbolize that the login was done. Then just log out and clear the SharedPreference to go to login screen again.

  • Use the method FirebaseAuth::getCurrentUser to check if the user is logged in

1 answer

1

I believe the firebase will not drop the user unless you do... to check if the user is logged in try:

public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser mUser;

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

    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();

     if(mUser == null)
      {
         Toast.makeText(this, "Usuário não logado", Toast.LENGTH_LONG).show();
      }
     else
      {
         Toast.makeText(this, "Usuário logado", Toast.LENGTH_LONG).show();
      }


   } }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.