Question: Context Related Problems inside MVP presenter

Question

Context Related Problems inside MVP presenter

Answers 1
Added at 2017-06-24 13:06
Tags
Question

I am new to android MVP pattern and working on my project i have some basic problem related to Android Context in the presenter. Although there are many answers related to this but i didn't get a perfect one which can solve my problem.

I have following queries:

  1. how to access shared preferences inside presenter.
  2. how to access other system services inside presenter.
  3. if i am working on SQLite Databases then during any transaction in my database which is done by call from presenter to my SQLite Helper class need context to access database.

If i will pass my activity context in presenter then it will a problem during unit testing, also it is a violation according to MVP Format. I need a perfect solution so that my code quality is not degraded.

Note: I dont want to use dagger tool so the answer should be dagger independent

Answers to

Context Related Problems inside MVP presenter

nr: #1 dodano: 2017-06-24 14:06

In MVP you dont use Context or anything else from the Android SDK/Framework in the Presenter (P) layer! This layer is for anything else than Android related stuff.

1) how to access shared preferences inside presenter.

You don't. If you need a value from a SharedPrefences in the Presenter then you could pass the value to the Presenter via a method call.

Example:

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

 }

2) how to access other system services inside presenter.

As metioned before; You don't acesss System services in the Presenter. What you can do is call the a System Service from the Presenter.

Example with Vibrator:

1 - Create an interface:

interface OnSystemServiceCaller{
  onVibratorCall();
}

2 - Implement it in a Activity

class MainActivity implements OnSystemServiceCaller{

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

  } 
}

3 - Call from presenter

class Presenter{
OnSystemServiceCaller listener;

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

}

3) if i am working on SQLite Databases then during any transaction in my database which is done by call from presenter to my SQLite Helper class need context to access database.

Some wont like this answers other will, this is just a suggestion.

You can access your SQLite by using a global ApplicationContext() in your app class (Class that extend Application; see how here since your SQLlite is global for the whole app and not just a particular Activity And when you need to pass data from SQLite to a Activity then you pass it first to the Presenter and from Presenter to your Activity the same way we send a call to our Vibrator method

Source Show
◀ Wstecz