0

i'm developing an android app using MVP pattern.

I'd like to have different presenters, and each one implements getItems, that call a getAll static method of the associated model. I thought to use generics, ended up like this:

public class BasePresenter<T> {
   protected T mModel;

   List getItems() {
       mModel.getAll();
   }
}

public class Presenter extends BasePresenter<Model> {
}

but i cannot access getAll methods using generics, because is not an Object's method.

Since for me would be dumb to write the same boring method getAll() for all presenter, changing only the model, is there there any way to accomplish that?

I'm asking because even in Google's official MVP guide, it use always the same method to retrive data, overriding it on each presenter, and i'm hoping that there is a better way.

I thought to "cast" the superclass mModel, but i don't know how and if it's possible to do, though.

SHRLY
  • 241
  • 2
  • 14
stefano capra
  • 159
  • 5
  • 13

2 Answers2

0

Maybe this can help you:

List getItems(){
    if(mModel instanceof TheSuperClassOrInterface){
        return ((TheSuperClassOrInterface)mModel).getAll();
    }else{
        return null;
    }
} 
0

Try this

public class BasePresenter<M extends BaseModel<M>> {

    @Nullable
    private M mModel;

    @Nullable List<M> getItems() {
        if (mModel != null) {
            return mModel.getModelList();
        }
        return null;
    }
}

And the BaseModel is

 public abstract class BaseModel<M> {

        private List<M> modelList;

        public List<M> getModelList() {
            return modelList;
        }

        public void setModelList(List<M> modelList) {
            this.modelList = modelList;
        }
    }

Sub model

public class LoginModel extends BaseModel<LoginModel> {

    @Override
    public List<LoginModel> getModelList() {
        return super.getModelList();
    }

    @Override
    public void setModelList(List<LoginModel> modelList) {
        super.setModelList(modelList);
    }
}

And finally presenter is like this

public class LoginPresenter extends BasePresenter<LoginModel> {
        //do your code
}

Hope it helps you.

Pradeep Kumar
  • 586
  • 3
  • 19