Android – context sensitive issues within MVP presenters

I am a novice in Android MVP mode and work on my project. I have some basic questions related to Android context in the presenter. Although there are many answers related to this, I haven't got a perfect answer that can solve my problem

I have the following questions:

>How to access shared preferences in the presenter. > how to access other system services in the presenter. > If I am using the SQLite database, the context of accessing the database is completed through a call from the presenter to my SQLite helper class during any transaction in my database

If I pass my activity context in the presenter, there will be problems during unit testing, and it is also a violation according to the MVP format. I need a perfect solution so that the quality of my code will not degrade

Note: I don't want to use dagger tool, so the answer should be dagger independent

resolvent:

In MVP, you should not use context or any other content in Android SDK / framework in presenter (P) layer! This layer is not Android related

1) How to access shared preferences in presenters

You don't. If you need the value of sharedprefence in presenter, you can pass the value to presenter through method call

Example:

class MainActivity{
 String birthday = SharedPrefence.getString(..);
 presenter.setSavedBirtday(birthday);

 }

2) How to access other system services within the presenter

As mentioned earlier; You do not access system services in presenter. All you can do is call system services from presenter

Vibrator example:

1 – create an interface:

interface OnSystemServiceCaller{
  onVibratorCall();
}

2 – implement it in activity

class MainActivity implements OnSystemServiceCaller{

@Override
onVibratorCall(){
  Vibrator v = (Vibrator) getSystemService(VIBRATOR);
  v.vibrate(50);

  } 
}

3 – phone call from presenter

class Presenter{
OnSystemServiceCaller listener;

  public void ifButtonClicked(){
    listener.onVibrateCall();
  }

}

3) If I am using the SQLite database, the context of accessing the database is completed through a call from the presenter to my SQLite helper class during any transaction in my database

Some people won't like the answer. It's just a suggestion

You can access your SQLite by using global ApplicationContext () in the app class (extend the class of application; see how here, because your sqllite is the global of the whole application, not just a specific activity. When you need to transfer data from SQLite to activity, you first pass it to the presenter and from the presenter to your activity, just as we send a call to the vibrator method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>