Firebase: App rebooting alone

Asked

Viewed 112 times

0

I’m developing an android app, and I’m using Firebase’s Realtime Database to store the data. There I have a user node, with all the users I have registered through my App. When I make a change to the data of the user who is logged in (for example, adding an item to your book list), it’s as if my app quickly restarts calling the login function again and returning to the main screen, something very strange. The strange thing is that this also happens if I make this change manually in Firebase itself, the app also goes back to the main screen and shows the Toast you have in the login function: "Login successfully!" as if calling the login function again. This seems to me to be Firebase’s own thing, does anyone know what this is and why? Is there any way to change this? I want to be able to make a change and continue in Activity I am without my app restarting.

This is my Loginactivity (When I change some information on the user who is logged in, it’s as if the app restarts quickly calling this function validatedLogin(), then goes back to Mainacativity and shows the Toast "Successfully logged in!" as well as in that function):

public class LoginActivity extends AppCompatActivity {

private EditText userInput;
private EditText passwordInput;
private Button btLogin;
private TextView btSignUp;
private FirebaseAuth auth;
private User user;
private LinearLayout layoutLogin;
private ProgressDialog progressDialog;
private DatabaseReference firebase;
private User currentUser;
private Preferences preferences;

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

    auth = FirebaseAuth.getInstance();
    preferences = new Preferences(LoginActivity.this);
    user = new User();

    if(auth.getCurrentUser() != null){
        progressDialog = new ProgressDialog(LoginActivity.this);
        progressDialog.setMessage("Entrando como " + preferences.getName());
        progressDialog.show();
        user.setEmail(preferences.getEmail());
        user.setPassword(preferences.getPassword());
        validateLogin();
    }

    userInput = (EditText) findViewById(R.id.userInputLogin);
    passwordInput = (EditText) findViewById(R.id.passwordInputLogin);
    layoutLogin = (LinearLayout) findViewById(R.id.linearLayoutLogin);

    progressDialog = new ProgressDialog(LoginActivity.this);
    progressDialog.setMessage("Entrando...");

    btLogin = (Button) findViewById(R.id.btLogin);
    btLogin.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View view) {

            if (!Objects.equals(userInput.getText().toString(), "") && !Objects.equals(passwordInput.getText().toString(), "")){

                user.setEmail(userInput.getText().toString());
                user.setPassword(passwordInput.getText().toString());

                progressDialog.show();

                validateLogin();

            }
            else {
                Toast.makeText(LoginActivity.this, "Preencha os campos de e-mail e senha", Toast.LENGTH_SHORT).show();
            }
        }
    });

    btSignUp = (TextView) findViewById(R.id.btSignUp);
    btSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(LoginActivity.this, SignUpPersonalDataActivity.class);
            startActivity(intent);
        }
    });
}

private void validateLogin(){
    auth = FirebaseConfig.getFirebaseAuth();
    auth.signInWithEmailAndPassword(user.getEmail(), user.getPassword()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {

            if (task.isSuccessful()){

                FirebaseUser userFirebase = task.getResult().getUser();
                firebase = FirebaseConfig.getFirebase().child("user").child(userFirebase.getUid());

                firebase.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        currentUser = dataSnapshot.getValue(User.class);

                        String myBooksIds = "";
                        if(currentUser.getMyBooks() != null) {
                            StringBuilder stringBuilder = new StringBuilder(myBooksIds);
                            for (int i = 0; i < currentUser.getMyBooks().size(); i++) {
                                stringBuilder.append(currentUser.getMyBooks().get(i) + " ");
                            }
                            myBooksIds = stringBuilder.toString();
                        }

                        String myListIds = "";
                        if(currentUser.getMyList() != null) {
                            StringBuilder stringBuilderMyList = new StringBuilder(myListIds);
                            for (int i = 0; i < currentUser.getMyList().size(); i++) {
                                stringBuilderMyList.append(currentUser.getMyList().get(i) + " ");
                            }
                            myListIds = stringBuilderMyList.toString();
                        }

                        preferences.saveUserPreferences(currentUser.getId(), currentUser.getName(), currentUser.getEmail(), currentUser.getPassword(), myBooksIds, myListIds);

                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        progressDialog.cancel();
                        finish();
                        startActivity(intent);
                        Toast.makeText(LoginActivity.this, "Login efetuado com sucesso!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Toast.makeText(LoginActivity.this, "Erro desconhecido", Toast.LENGTH_SHORT).show();
                        Log.w("ERRO", "loadUser:onCancelled", databaseError.toException());
                    }
                });

            }
            else {
                progressDialog.cancel();
                Toast.makeText(LoginActivity.this, "E-mail ou senha inválidos!", Toast.LENGTH_SHORT).show();
            }

        }
    });
}

}

This is a fragment of my Mainactivity, where I register a book in Firebase, I am registering a book in the "book' node of firebase, and I also add this book id in the "myBooks" property of the logged-in user. By adding this id to the user’s book list, the app mysteriously restarts Mainactivity and shows Toast "Successfully logged in!" as if it had called the login function.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment3, container, false);

    userPreferences = new Preferences(getContext());

    firebase = FirebaseConfig.getFirebase().child("user").child(userPreferences.getID()).child("myBooks");

    if (firebase != null){
        firebase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                myBooks.clear();

                for (DataSnapshot data : dataSnapshot.getChildren()){
                    String myBooksCurrent = data.getValue().toString();

                    myBooks.add(myBooksCurrent);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    bookNameInput = (EditText) view.findViewById(R.id.bookNameInput);
    bookAuthorInput = (EditText) view.findViewById(R.id.bookAuthorInput);
    bookPublishingCompanyInput = (EditText) view.findViewById(R.id.bookPublishingCompanyInput);
    bookSynopsisInput = (EditText) view.findViewById(R.id.bookPublishingCompanyInput);

    genresSpinner = (Spinner) view.findViewById(R.id.bookGenreSpinner);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getContext(), R.array.genres_spinner, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    genresSpinner.setAdapter(adapter);

    btAddBook = (Button) view.findViewById(R.id.btAddBook);
    btAddBook.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View view) {

            if (Objects.equals(bookNameInput.getText().toString(), "")){
                Toast.makeText(getContext(), "Informe o nome do livro", Toast.LENGTH_LONG).show();
            }
            else if (Objects.equals(bookAuthorInput.getText().toString(), "")){
                Toast.makeText(getContext(), "Informe o autor do livro", Toast.LENGTH_LONG).show();
            }
            else if (Objects.equals(genresSpinner.getSelectedItem().toString(), "Selecione o gênero")){
                Toast.makeText(getContext(), "Informe o gênero do livro", Toast.LENGTH_LONG).show();
            }
            else if (Objects.equals(bookPublishingCompanyInput.getText().toString(), "")){
                Toast.makeText(getContext(), "Informe a editora do livro", Toast.LENGTH_LONG).show();
            }
            else if (Objects.equals(bookSynopsisInput.getText().toString(), "")){
                Toast.makeText(getContext(), "Informe a sinopse do livro", Toast.LENGTH_LONG).show();
            }
            else {

                book = new Book();
                book.setName(bookNameInput.getText().toString());
                book.setAuthor(bookAuthorInput.getText().toString());
                book.setPublishingCompany(bookPublishingCompanyInput.getText().toString());
                book.setGenre(genresSpinner.getSelectedItem().toString());
                book.setSynopsis(bookSynopsisInput.getText().toString());
                book.setAvaliable(true);
                book.setOwnerID(userPreferences.getID());

                String idBook = Base64Custom.base64Encoding(book.getName() + userPreferences.getID());
                book.setId(idBook);

                registerBook(book);
            }
        }
    });

    return view;
}

private boolean registerBook(Book book) {
    try{

        firebase = FirebaseConfig.getFirebase().child("book");
        firebase.child(book.getId()).setValue(book);
        myBooks.add(book.getId());

        firebase = FirebaseConfig.getFirebase().child("user");
        firebase.child(userPreferences.getID()).child("myBooks").setValue(myBooks);

        Toast.makeText(getContext(), "Livro cadastrado com sucesso!", Toast.LENGTH_LONG).show();
        return true;
    }
    catch (Exception e){
        e.printStackTrace();
        return false;
    }
}

But as I mentioned, I add this id to the user’s book list manually on the firebase site, the same thing happens, Mainactivity is restarted and Toast appears "Login successfully!".

  • post the code used. without code is difficult.

  • Without the code it really gets hard to understand the problem, but from your description, and not stating for sure, you have some problem in your firebase Valuelisteners. Post the code and we’ll look real quick.

  • It’s because I don’t really know in what part of the code there might be a problem, not even the file. As I said, even a manual edition on the firebase site itself causes this to happen. But I’m going to put in a few excerpts that I think might be involved.

  • Done! I added the code of my Loginactivity and a Fragment where I am changing a user property that is logged in as example.

  • Try using addListenerForSingleValueEvent instead of addValueEventListener in the method validateLogin()

1 answer

0

This is happening because the section below is inside onDataChange:

Intent intent = new Intent(LoginActivity.this, MainActivity.class);
progressDialog.cancel();
finish();
startActivity(intent);
Toast.makeText(LoginActivity.this, "Login efetuado com sucesso!

The onDataChange function is called every time the data in the node is changed, since you used addValueEventListener.

Rosario Pereira Fernandes suggested you use addListenerForSingleValueEvent, this would solve the problem but it is not recommended to load data while you are completing the login.

The ideal in this case is to complete the login and switch to the Activity which will display the data, only then request the data from Firebase.

Here is a link to the Firebase documentation on recovering data, which can help this case and other issues you have:

https://firebase.google.com/docs/database/admin/retrieve-data?hl=pt-br

Browser other questions tagged

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