Android MVP with Volley

Viewed 587

I have the following problem. I want to implement MVP with Android, using Volley as a model. The problem is, that Volley requestQueue need context. I know that one solution is to make a static Context, but it's a bad practice. How should I create this code with MVP.

RequestQueue queue = Volley.newRequestQueue(this);
2 Answers

I can suggest to abstract your network request entirely and create a class that handles the network request. You can then create this class when you create it. For example in the Application class where you have the application context.

class NetworkRequest(
    private val context: Context
) {
    val queue = Volley.newRequestQueue(context)

    fun doNetworkRequest() {
        val request = StringRequest(...)
        queue.add(request)
    }
}

class Presenter(
    private val networkRequest: NetworkRequest
) {
    . . .
}

In this way you can test your presenter by mocking the NetworkRequest and the implementation detail of requesting to the server is abstracted from your presentation logic.

I think I figured it out. I cannot guarantee the correctness of the answer, but it's working.

I changed my Presenter constructor and now I should implicit pass the correct view to the presenter, because in my App start I am passing a fragment, not a view. That's why I created setPresenter method in MainView interface.

 public MainPresenter(MainContract.MainView view, NetworkLayer networkLayer) {
    this.view = view;
    this.view.setPresenter(this);
    this.networkLayer = networkLayer;
}

Now I am setting the NetworkLayer on App start (in MainActivity or in Application class). There I have an access to the application context and I can pass the network layer without storing a context in presenter. To make the right connection between presenter and model I created a setter in NetworkLayer to pass the right presenter.

    MainFragment mainFragment = new MainFragment();
    //Inject view and model
    MainContract.MainPresenter mainPresenter = new MainPresenter(mainFragment, NetworkLayer.getInstance(getApplicationContext()));
    NetworkLayer.getInstance(getApplicationContext()).setPresenter(mainPresenter);
Related