0

I basically have this function that validates the click of the user:

   this.btnTryAgain.setOnClickListener {
            viewModel.responsePictures.observeForever {
                manageResponse(it)
            }
            clickcount += 1
            if (clickcount == 3) {
                findNavController().navigate(R.id.errorComprovante)
            }

        }

The observer is responsible for managing the response of the service. So if the users clicks the button 3 times and it doesn't get any success response, it goes to the errorComprovante. The problem is that if i use this code with the observer, it simply doesn't work.

Is there a way i can store the number of clicks so that it doesn't get lost? Thanks

William
  • 75
  • 1
  • 8

3 Answers3

0

You could store the value in a hidden field, that way it would be kept on the client side and would stay as long the the page is not re-rendered.

Rocco_STACK
  • 16
  • 1
  • 1
  • 6
0

Shared preferences, database, files. All ways to persist data.

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106
0

Further Reading on Shared Preferences

Store the data in Shared Preferences.

public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);    
Editor editor = sharedpreferences.edit();
editor.putInt("count", clickCounter);
editor.commit();

Then get the data from the preferences using sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE)

Narendra_Nath
  • 4,578
  • 3
  • 13
  • 31
  • Thanks for you answer but i think you meant editor.puInt. Also i would like to know if the value of sharedPreferences in a if statement to check the number of clicks. – William May 26 '21 at 12:22
  • Yeah yeah i'll change it .. And yes you can use it just like a normal variable.I'll make the answer a bit more elaborate. make sure to accept the answer if it helps you.:) – Narendra_Nath May 26 '21 at 12:25
  • For some reason i put the clickcount++ inside the observer and now it's working. But i think sharedPreferences could work too. – William May 27 '21 at 13:02
  • Yeah, you're right that's a much better implementation. – Narendra_Nath May 27 '21 at 13:12