The observer remains with the old value on Android

  android, android-livedata, java, mvvm

I am a beginner in MVVM and LiveData architecture, so I am having some difficulties in solving my problem. I have a LoginActivity where I have two fields (username and password) and I click the Login button to make a request to the TMDB API.
In this activity I have an observer when I receive the answer, I keep the values returned from the api and go to my list of films.

When I close the session, it goes to the LoginActivity.
When he goes to the LoginActivity, he enters the observer and, instead of waiting for me to click the Login button again, he automatically connects. I realized that the observer still has the old value.

How can I remove this old value?

My code:

LoginActivity.class

public class LoginActivity extends AppCompatActivity {

//ViewBinding
LoginActivityBinding loginActivityBinding;

//ViewModel
AccountViewModel accountViewModel;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    loginActivityBinding= LoginActivityBinding.inflate(getLayoutInflater());
    setContentView(loginActivityBinding.getRoot());

    accountViewModel = new ViewModelProvider(this).get(AccountViewModel.class);

    //Calling the observer
    observeAccountChange();

    //click login button
    loginActivityBinding.btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            EditText edUsername = loginActivityBinding.edUsername;
            EditText edPassword = loginActivityBinding.edPassword;

            if(!edUsername.getText().toString().equals("") && !edPassword.getText().toString().equals(""))
                accountViewModel.login(edUsername.getText().toString(),edPassword.getText().toString());
        }
    });
}

//observer
private void observeAccountChange() {
    accountViewModel.getLoginResponse().observe(this, new Observer<LoginModel>() {
        @Override
        public void onChanged(LoginModel loginResponse) {
            if(loginResponse.isSucess())
                saveInfoUser(loginResponse);
            else
                Toast.makeText(getApplicationContext(),"Error signing in",Toast.LENGTH_SHORT).show();
        }
    });
}

//save info user
private void saveInfoUser(LoginModel loginResponse) {
    SharedPreferences.Editor editor = getSharedPreferences("detailsUser", MODE_PRIVATE).edit();
    editor.putString("accountId", loginResponse.getId());
    editor.putString("sessionId", loginResponse.getSessionId());
    editor.apply();

    goToListMovies();
}

//go to movie list
private void goToListMovies(){
    Intent intent = new Intent(this, MainListActivity.class);
    startActivity(intent);
}
}

AccountDetailsFragment.class

public class AccountDetailsFragment extends Fragment {

//ViewBinding
FragmentAccountDetailsBinding fragmentAccountDetailsBinding;

//ViewModel
AccountViewModel accountViewModel;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    fragmentAccountDetailsBinding = FragmentAccountDetailsBinding.inflate(inflater,container,false);

    accountViewModel = new ViewModelProvider(requireActivity()).get(AccountViewModel.class);

    //Calling the observer
    observeDetailsChange();

    //get account id
    SharedPreferences prefs = getActivity().getSharedPreferences("detailsUser", MODE_PRIVATE);
    String sessionId = prefs.getString("sessionId","");

    accountViewModel.getDetailsUser(sessionId);

    //btn logout
    fragmentAccountDetailsBinding.btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            logout();
        }
    });

    return fragmentAccountDetailsBinding.getRoot();
}

//observer
private void observeDetailsChange() {
    accountViewModel.getDetailsUser().observe(requireActivity(), new Observer<UserModel>() {
        @Override
        public void onChanged(UserModel userModel) {
            if(userModel != null)
            {
                Glide.with(fragmentAccountDetailsBinding.image).load("https://image.tmdb.org/t/p/w500/" +userModel.getAvatar() + ".jpg").placeholder(R.drawable.movie).into(fragmentAccountDetailsBinding.image);
                fragmentAccountDetailsBinding.usermane.setText(userModel.getUsername());
            }
        }
    });
}

private void logout(){
    SharedPreferences.Editor editor = getActivity().getSharedPreferences("detailsUser", MODE_PRIVATE).edit();
    editor.putString("accountId", "");
    editor.putString("sessionId", "");
    editor.apply();

    Intent intent = new Intent(getContext(),LoginActivity.class);
    startActivity(intent);
}

Source: Android Questions

LEAVE A COMMENT