Show Toast in a non-Activity class

Asked

Viewed 560 times

0

I’d like to exhibit a Toastwhen the user does logout.

I have this structure:

inserir a descrição da imagem aqui

Within ConexaoFirebase, I have a method called logOut:

public static void logOut() {
    firebaseAuth.signOut();
}

and within the class PerfilActivity, I have a method that calls the logOut():

private void eventoClicks(){
    btnLogOut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ConexaoFirebase.logOut();
            finish();
        }
    });
}

I wish every time it was done logout, were displayed a Toast, then I tried the following:

Within ConexãoFirebase, I created a method called alert:

private void alert(String s) {
    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}

and within logOut called the alert passing the message that I want to be displayed, but my code got error:

inserir a descrição da imagem aqui

What is the correct way to display the message?

I know I could do the Toast inside CadastrarActivity, but would like to do within the class ConexaoFirebase.

  • Pass the context for the methods logOut and alert: Ex: ConexaoFirebase.logOut(context);. and also alert(context, "Mensagem");

  • Could you give me a better example? not yet manjo programming.

  • 1

    The point is that the Toast will be shown in a Activity even if the starting point in it is not a Activty. So you just have to get past the context of that Activity where you want to launch the Toast

1 answer

1

public static void logout(Context ctx) {
    auth.signOut();
    alert(ctx, "...");
}

private void alert(Context ctx, String s) {
    Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
}

The logout method receives the parameter Context and then moves on to the Alert method that will display your Toast. Basically all Toast will need a Context to be shown.

ConexaoFirebase.logout(getApplicationContext());

Browser other questions tagged

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