androidmvpandroid-mvp

Android MVP, same old context problem when getting clipboard data?


So I need to get clipboard data in presenter. This means I need context. Unfortunately I don't have any knowledge of dependency injection if it is the only standard way. I studied some solutions but they are stated as faulty solutions.

public class MainActivityPresenter implements MainActivityInterfaces.MainToPresenter {

MainActivityInterfaces.PresenterToMain main;


public MainActivityPresenter (MainActivityInterfaces.PresenterToMain main) {
    this.main = main;
}


@Override
public void processUrl() {
    String url = Utils.getClipboardData(context);
    if (url.isEmpty()) {

    } else {

    }
}


}

And this is the method in Utils class

public static String getClipboardData (Context context) {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager cm = (android.text.ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        String result = cm.getText().toString();
        return result==null?"":result;
    } else {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
        ClipData.Item item = cm.getPrimaryClip().getItemAt(0);
        if (item != null)
            return item.getText().toString();
        else
            return "";
    }
}

Solution

  • At MVP, when the View propagates an event to the Presenter, it is very common for certain information to be sent to the Presenter. In your case, it would be quite logical to rename your method as follows:

    @Override
    public void processUrl(String url) {
      if (url.isEmpty()) {
    
      } else {
    
      }
    }
    

    In this way, the View will be in charge of propagating the information along with the event. And you also keep in the Presenter the ignorance about the peculiarities of the View (Android things), something very important in the MVP pattern.

    Good luck!