2
votes

I have a view(Activity) with imageView and textView. When I click on imageView then in the textView show how many time I click on the image. I use pattern MVP to solve this task.

And as result, all work fine. OK. Nice.

But have one more task - to restore view state after rotate screen.

To solve this task I use the next approach: 1. Create Presenter as Singleton 2. I Presenter I have variable

private int countClick;
  1. When clicking ImageView on the View I call presenter.clickLike(), increment it and call View method

    showCountOfClick()

  2. In the Presenter

    public void clickLike() { countClick++; view.showCountOfClick(countClick + ""); }

  3. Also in Presenter I have method

    @Override
    public void viewIsReady() {
    view.showCountOfClick(countClick + "");
    }
    

This method call from View in onCreate() method()

  1. In the View set text in TextView with the count of clicks.

    public void showCountOfClick(String text) { textView.setText(text) }

Done.

So as result the count of click shows correct when rotating screen. And a bonus I do not need in View to override method protected void onSaveInstanceState(Bundle outState) because all work is done in Presenter.

Question: Is it a good solution?

1

1 Answers

-1
votes

Your Activity (normally) is going to be destroyed and recreated by the system on configuration changes. So it is not a good idea to hold a reference to it in a singleton. There are multiple solutions I prefere in this case:

  • Use the onSaveInstanceState, you can forward this call to your Presenter for handling
  • Use SharedPreferences to store data in your Presenter
  • Use Architecture Components