Firebase: App restarting by itself

0

I'm developing an android app, and I'm using the Firebase Realtime Database to store the data. There I have a users node, with all the users I registered through my App. When I make some changes in the user data that is logged in (eg add an item in your book list), it's as if my app reboot quickly by 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 returns to the main screen and shows the toast it has in the Login function: "Login done successfully!" As if it were calling login function again. This is sounding like Firebase itself, does anyone know what this is going on and why? Is there any way to change this? I want to be able to make a change and continue in the Activity that I am without my app restarting.

This is my LoginActivity (When I change some information in the user that is logged in, it is as if the app quickly restarts calling this function validityLogin (), then returns to the MainAcativity and shows Toast "Login done successfully!" so as in this 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 from my MainActivity, where I register a book in Firebase, I am registering a book in the firebase book node, and I also add the id of that book in the "myBooks" property of the logged-in user. by adding this id in the user's book list, the app mysteriously restarts the MainActivity and shows the Toast "Login done successfully!" 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 in the list of user books manually in the firebase site, the same thing happens, MainActivity is restarted and the toast "Login done successfully!" appears.

    
asked by anonymous 12.12.2017 / 00:29

1 answer

0

This is happening because the snippet below is within 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 on the node changes, since you have used addValueEventListener .

Rosário Pereira Fernandes suggested that 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 change to Activity that will show the data, only then request the data to Firebase.

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

link

    
19.01.2018 / 16:24