How to use the androidx.lifecycle.ViewModelProvider in Java - java

I'm recently learning about the architectural components and was following the old tutorial where they used the old method:
mainActivityViewModel =
new ViewModelProvider(this).get(MainActivityViewModel.class);
But in the documentation for the ViewModelProvider, the only constructors available are
ViewModelProvider(ViewModelStoreOwner, Factory) &
ViewModelProvider(ViewModelStore, Factory).
So I did something like this but I'm not sure what to do in the overridden method and it currently returns null that crashes the program.
public class MainActivity extends AppCompatActivity {
private NoteViewModel noteViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteViewModel = new ViewModelProvider(this, new ViewModelProvider.Factory() {
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
return null;
}
}).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, new Observer<List<NoteEntity>>() {
#Override
public void onChanged(List<NoteEntity> noteEntities) {
Toast.makeText(MainActivity.this,"Changed",Toast.LENGTH_LONG).show();
}
});
}
}
Is my approach correct? I'm absolutely lost right now. What am I supposed to return from the overridden method?

Use this
noteViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(NoteViewModel.class;
We use custom factory, when we pass param to the constructor of ViewModel (apart from Application param).
and gradle dependency in case,
def lifecycle_version = "2.2.0"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
//
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"

First you need to initialize viewmodel in activity class like :
noteViewModel = ViewModelProvider(this).get(NoteViewModel.class);
In NoteViewModel.java
You need to define livedata variable for storing updated data provided by model and update post to view model
NoteViewModel.java file look like :
public class NoteViewModel extends AndroidViewModel {
AppRepository appRepository;
MediatorLiveData<List<NoteEntity>> mediatorData;
public NoteViewModel (#NonNull Application application) {
super(application);
mediatorData=new MediatorLiveData<>();
appRepository=new AppRepository((MyApplication).apiService, application.retrofit);
}
public MediatorLiveData<List<NoteEntity>> getMediatorLiveData() {
return mediatorVideoData;
}
public void getNoteEntry()
{
try {
mediatorData.addSource(appRepository.getNoteEntry(), new Observer<List<NoteEntity>>() {
#Override
public void onChanged(#Nullable List<NoteEntity> data) {
mediatorData.postValue(data);
}
});
}catch (Exception e)
{
}
}
}
In onCreate() of Mainactivity register observer like and call the API from view model like
noteViewModel.getMediatorLiveData().observe(this, new Observer<List<NoteEntity>>() {
#Override
public void onChanged(List<NoteEntity> noteEntities) {
Toast.makeText(MainActivity.this,"Changed",Toast.LENGTH_LONG).show();
}
});
noteViewModel.getNoteEntry();
AppRepository.java file look like
class AppRepository() {
ApiService apiService;
Retrofit retrofit;
public AppRepository(ApiService apiService ,Retrofit retrofit){
this.apiService = apiService;
this.retrofit = retrofit;
}
public MediatorLiveData<List<NoteEntity>> getNotes() {
MediatorLiveData<List<NoteEntity>> data = new MediatorLiveData<List<NoteEntity>>()
apiService.getNotes()
.enqueue(new Callback<List<NoteEntity>> {
#Override
void onResponse(
Call<List<NoteEntity>> call,
Response<List<NoteEntity>> response
) {
if (response.isSuccessful()) {
if(response.body()!=null){
data.postValue(response.body()); //successfull data
}else{
data.postValue(null); //error
}
} else {
data.postValue(null); //error
}
}
#Override
fun onFailure(
Call<List<NoteEntity>> call,
Throwable t
) {
data.postValue(null); //error
}
})
return data;
}
}

Kotlin Code.
In build.gradle add
implementation "androidx.activity:activity-ktx:1.1.0"
then
val noteViewModel by viewModels<NoteViewModel>()

Figured it out after 4 hours.
noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
Also these dependencies should be added to the gradle file.
def room_version = "2.2.5"
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
Not sure if the error was caused because I missed the annotation dependency. But everything works now.

Related

Passing query parameters to LiveData/Viewmodel in Android app

Since I'm new to programming Android apps I followed a tutorial on how to use the Android Architecture Components and Firebase for implementing the MVVM (using LiveData, ViewModel, etc.).
The tutorial I followed can be found here:
Part 1
Part 2
Part 3
I'm now left with what I think is a decent implementation of the MVVM, but I can not wrap my head around how I am supposed to pass query parameters to it. Right now I need to hardcode the ID of the document I want to retrieve:
public class AlarmDAO {
private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
public AlarmLiveData getFirestoreLiveData() {
DocumentReference documentReference = firebaseFirestore.collection(Collection.ALARMS.name).document("5RxJNuNyhDJlz49wpBkw");
return new AlarmLiveData(documentReference);
}
}
That then gets called by a class extending ViewModel.
public class AlarmViewModel extends ViewModel {
private AlarmDAO DAO = new AlarmDAO();
private AlarmLiveData liveData = null;
public LiveData<Alarm> getAlarmLiveData() {
liveData = DAO.getFirestoreLiveData();
return liveData;
}
public LiveData<Alarm> getAlarm() {
return liveData.alarm;
}
}
And then I observe that data in my activity:
model.getAlarmLiveData().observe(this, Observable -> {});
model.getAlarm().observe(this, alarm -> {
if (alarm != null) {
alarmTextView.setText(alarm.getTest());
else {
Log.d(TAG, "Waiting for data");
}
});
My problem is that I do not see a way of querying for a specific alarm. For instance model.getAlarm("someId"). I am under the impression that it should be done in the DAO and/or the ViewModel, but I can't figure out how. Another thing I do not understand is why I need to observe both model.getAlarmLiveData() and model.getAlarm() in my activity, as using only one does not work. The answer to both of those questions is most likely very simple, but thus far I haven't been able to figure it out.
For completeness: the Alarm class is nothing besides a getter and setter for two strings, and the AlarmLiveData class is below.
public class AlarmLiveData extends LiveData<Alarm> implements EventListener<DocumentSnapshot> {
private static final String TAG = AlarmLiveData.class.getSimpleName();
private Alarm alarmTemp = new Alarm();
private DocumentReference documentReference;
private ListenerRegistration listenerRegistration = () -> {};
public MutableLiveData<Alarm> alarm = new MutableLiveData<>();
public AlarmLiveData(DocumentReference documentReference) {
this.documentReference = documentReference;
}
#Override
protected void onActive() {
listenerRegistration = documentReference.addSnapshotListener(this);
super.onActive();
}
#Override
protected void onInactive() {
listenerRegistration.remove();
super.onInactive();
}
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null && documentSnapshot.exists()) {
alarmTemp = new Alarm();
alarmTemp.setId(documentSnapshot.getId());
alarmTemp.setTest(documentSnapshot.get("test").toString());
alarm.setValue(alarmTemp);
} else {
Log.d(TAG, "ERROR");
}
}
}
Thank you for reading, I'm looking forward to the answer(s)!
The reason you have to use both model.getAlarmLiveData() and model.getAlarm() looks to be that your AlarmLiveData class extends LiveData but sets a value for the contained MutableLiveData member variable instead of setting its own class value.
Inside your AlarmLiveData class:
// Comment out/Remove your 'public MutableLiveData<alarm> alarm' member variable from the top.
// You're going to want to set the value of the AlarmLiveData class itself instead.
// ...
// Then inside of your onEvent callback
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null && documentSnapshot.exists()) {
alarmTemp = new Alarm();
alarmTemp.setId(documentSnapshot.getId());
alarmTemp.setTest(documentSnapshot.get("test").toString());
// Set the value for the AlarmLiveData class directly
setValue(alarmTemp);
} else {
Log.d(TAG, "ERROR");
}
}
I'm not sure why you're creating a DAO class and I would most likely move that code directly into the AlarmViewModel class.
But, here is how you can alter your current DAO class if you don't want to remove it:
// Pass in the document id you want to create a document reference for
public AlarmLiveData getFirestoreLiveData(String documentId) {
DocumentReference documentReference = firebaseFirestore.collection(Collection.ALARMS.name).document(documentId);
return new AlarmLiveData(documentReference);
}
Your AlarmViewModel class would look something like this:
public class AlarmViewModel extends ViewModel {
private AlarmDAO DAO = new AlarmDAO();
private AlarmLiveData liveData = null;
// Make sure to take in the document id so you can create the corresponding LiveData
public LiveData<Alarm> getAlarmLiveData(String documentId) {
// Only create a new LiveData instance if the current one is null.
// This is helpful if you intend to use this as a Shared ViewModel.
if(liveData == null){
liveData = DAO.getFirestoreLiveData(documentId);
}
return liveData;
}
}
Finally, in your Activity:
// Pass in the document id and observe the ViewModel
model.getAlarmLiveData("MY_DOCUMENT_ID").observe(this, alarm -> {
if (alarm != null) {
alarmTextView.setText(alarm.getTest());
}else{
Log.d(TAG, "Waiting for data");
}
});

How can I refresh viewModel livedata from another activity

I am developing android application and I want to refresh viewModel livedata from second activity. When I get back to first activity data is not refreshed.
FirstActivity:
mViewModel = ViewModelProviders.of(this).get(MenuViewModel.class);
mViewModel.getMenus().observe(this, menuResponse -> {
if (menuResponse != null) {
resMenus.addAll(menuResponse.getMenus());
progressBar.setVisibility(View.GONE);
mAdapter.notifyDataSetChanged();
}
});
MenuViewModel:
public class MenuViewModel extends AndroidViewModel {
private MutableLiveData<MenuResponse> restMenuData;
private MenusRepository mRepository;
public MainActivityViewModel(#NonNull Application application) {
super(application);
mRepository = MenusRepository.getInstance(application);
restMenuData = mRepository.getMenus();
}
public LiveData<MenuResponse> getMenus() {
return restMenuData;
}
}
MenusRepository
private MenusRepository(Context context) {
apiRequest= RetrofitInstance.getInstance(context).getApiRequest();
}
public synchronized static MenusRepository getInstance(Context context) {
if (projectRepository == null) {
projectRepository = new MenusRepository(context);
}
return projectRepository;
}
public MutableLiveData<MenuResponse> getMenus() {
final MutableLiveData<MenuResponse> data = new MutableLiveData<>();
apiRequest.getMenus().enqueue(new Callback<MenuResponse>() {
#Override
public void onResponse(#NonNull Call<MenuResponse> call, #NonNull Response<MenuResponse> response) {
if (response.isSuccessful() && response.body() != null) {
data.setValue(response.body());
}
}
#Override
public void onFailure(#NonNull Call<MenuResponse> call, #NonNull Throwable t) {
data.setValue(null);
}
});
return data;
}
SecondActivity:
MenuViewModel mViewModel = ViewModelProviders.of(Objects.requireNonNull(SecondActivity.this)).get(MenuViewModel.class);
mViewModel.getMenus();
// This line not refresh menus
I except to refresh data from viewmodel, but it return old data.
How can I refresh viewmodel data in best practices?
MenusRepository.getMenus() methods creates a new instance of LiveData for every call. This is not the correct way to go about it.
You should have only one instance of LiveData and different objects subscribe to it (activity, viewModel, etc).
What you could do is - create a singleton of MenusRepository (which I think you have already done). Create one instance of MutableLiveData only and use it to update the data.
class MenusRepository {
private val liveData = MutableLiveData<MenuResponse>()
fun getMenus() {
// Your api call. Do not create a new instance of the livedata.
}
fun menus(): LiveData<MenuResponse> {
return liveData
}
fun update(data: MenuResponse) {
liveData.post(data)
}
This code is in Kotlin, but it applies similarly to Java as well.
You can update method to post an update to liveData. When you update it, all the observers will receive the new data. Use MenusRepository.menus() to access LiveData in your ViewModel.
Update
Your MenuRepository class could be like this.
private final MutableLiveData<MenuResponse> liveData = new MutableData<>();
private MenusRepository(Context context) {
apiRequest= RetrofitInstance.getInstance(context).getApiRequest();
}
public synchronized static MenusRepository getInstance(Context context) {
if (projectRepository == null) {
projectRepository = new MenusRepository(context);
}
return projectRepository;
}
public MutableLiveData<MenuResponse> loadMenus() {
apiRequest.getMenus().enqueue(new Callback<MenuResponse>() {
#Override
public void onResponse(#NonNull Call<MenuResponse> call, #NonNull Response<MenuResponse> response) {
if (response.isSuccessful() && response.body() != null) {
liveData.setValue(response.body());
}
}
#Override
public void onFailure(#NonNull Call<MenuResponse> call, #NonNull Throwable t) {
liveData.setValue(null);
}
});
}
public LiveData<MenuResponse> getMenus() {
return liveData;
}
public void updateData(response: MenuResponse) {
liveData.postValue(response);
}
When you want to update the data manually (from another activity),
use menuRepository.update() method. This will post the data to your LiveData which will update all its observers, ie. the ViewModel.
Call menuRepository.loadMenu() when you want to get the data using API.
Use menuRepository.getMenus() to get the LiveData and attach your observers.
Since MenuRepository is a singleton, there's only one instance of LiveData. When you will post an update to this instance of LiveData, all the observers will receive the new data.
public class MenuViewModel extends AndroidViewModel {
private MutableLiveData<MenuResponse> restMenuData;
private MenusRepository mRepository;
public MainActivityViewModel(#NonNull Application application) {
super(application);
mRepository = MenusRepository.getInstance(application);
restMenuData = mRepository.getMenus();
}
public LiveData<MenuResponse> getMenus() {
restMenuData = new MutableLiveData<>();
return restMenuData;
}
}
Change the View model code as above.
So that the live data is always cleared before returning to activity.

java.lang.ClassCastException Unsure of implications of a cast I made

Following a brilliant tutorial I've come stuck with a casting issue .
The app is basically a stackoverflow api which uses retrofit and makes calls to retrieve questions and question details etc...
This all said and done I'm lost why it longer launches.
Something is wrong with the cast inn the base activity:
BaseActivity
public class BaseActivity extends AppCompatActivity {
private ControllerCompositionRoot mControllerCompositionRoot;
protected ControllerCompositionRoot getCompositionRoot() {
if(mControllerCompositionRoot == null) {
mControllerCompositionRoot = new ControllerCompositionRoot(
((CustomApplication) getApplication()).getCompositionRoot(),
this
);
}
return mControllerCompositionRoot;
}
}
which gets called inn this class activity
public class QuestionsListActivity extends BaseActivity implements QuestionsListViewMvcImpl.Listener {
private StackoverflowApi mStackoverflowApi;
private QuestionsListViewMvc questionsListViewMvc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
questionsListViewMvc = getCompositionRoot().getViewMvcFactory().getQuestionListViewMvc(null);
questionsListViewMvc.registerListener(this);
mStackoverflowApi = getCompositionRoot().getStackoverflowApi();
setContentView(questionsListViewMvc.getRootView());
}
#Override
protected void onStart() {
super.onStart();
fetchQuestions();
}
private void fetchQuestions() {
mStackoverflowApi.fetchLastActiveQuestions(Constants.QUESTIONS_LIST_PAGE_SIZE)
.enqueue(new Callback<QuestionsListResponseSchema>() {
#Override
public void onResponse(Call<QuestionsListResponseSchema> call, Response<QuestionsListResponseSchema> response) {
if (response.isSuccessful()) {
bindQuestions(response.body().getQuestions());
} else {
networkCallFailed();
}
}
#Override
public void onFailure(Call<QuestionsListResponseSchema> call, Throwable t) {
networkCallFailed();
}
} );
}
private void bindQuestions(List<QuestionSchema> questionSchemas) {
List<Question> questions = new ArrayList<>(questionSchemas.size());
for (QuestionSchema questionSchema : questionSchemas) {
questions.add(new Question(questionSchema.getId(), questionSchema.getTitle()));
}
questionsListViewMvc.bindQuestions(questions);
}
private void networkCallFailed() {
Toast.makeText(this, R.string.error_network_call_failed, Toast.LENGTH_SHORT).show();
}
#Override
public void onQuestionClicked(Question question) {
QuestionDetailsActivity.start(this, question.getId());
}
}
I would understand first why the cast has to be made which is what I was following in the tutorial buttheres little way I can keep plugging at this wiithout understanding the whole concept of MVC etc..and the implications of how to implement that in an android app.
Any help would be greatly welcome and elaborations as well also.
repo - github
Register the custom application class in manifest.
I checked the repo and found the custom class is not registered. So your custom class is not used as application class.

How to properly reload liveData manually in Android?

My app is a basic news app which fetches data from JSON provided by Guardian API.
I parsed the values from JSON using raw java code (not using retrofit).
Then I get the LiveData in NewsFeedViewModel class which extends as AndroidViewModel.
And then in the fragment, I submit list to adapter.
These are the issues I'm facing:
1) at first, if the articles to show is set to 10, then if i go to settings and change it to 2, then the last 8 articles are disappearing but the white space /gap is not going. I can still scroll through the empty gap.
2) if i change the number of articles value constantly, then app is becoming un-scrollable.
And i have a few more doubts, how to refresh the data manually when swipeToRefresh is happened?
This is my project github link: https://github.com/sdzshn3/News24-7-RV
Video sample of the issue happening in app: https://drive.google.com/file/d/1gr_fabS2rqREuyecvGSG3IQ_jXOowlW7/view?usp=drivesdk
In kotlin style:
class RefreshableLiveData<T>(
private val source: () -> LiveData<T>
) : MediatorLiveData<T>() {
private var liveData = source()
init {
this.addSource(liveData, ::observer)
}
private fun observer(data: T) {
value = data
}
fun refresh() {
this.removeSource(liveData)
liveData = source()
this.addSource(liveData, ::observer)
}
}
Example:
class MainActivity : AppCompatActivity() {
private val viewModel: MyViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.goals.observe(this) { result ->
// update UI
}
// refresh
viewModel.refresh()
}
}
class MyViewModel(useCase: MyUseCase): ViewModel() {
private val _goals = RefreshableLiveData {
useCase.getGoals()
}
val goals: LiveData<Result<List<GoalItem>>>
get() = _goals.map(GoalItem::fromEntity)
fun refresh() {
_goals.refresh()
}
}
class MyUseCase {...}
...
You need to do exactly what I did in this Reddit post:
public class RefreshLiveData<T> extends MutableLiveData<T> {
public interface RefreshAction<T> {
private interface Callback<T> {
void onDataLoaded(T t);
}
void loadData(Callback<T> callback);
}
private final RefreshAction<T> refreshAction;
private final Callback<T> callback = new RefreshAction.Callback<T>() {
#Override
public void onDataLoaded(T t) {
postValue(t);
}
};
public RefreshLiveData(RefreshAction<T> refreshAction) {
this.refreshAction = refreshAction;
}
public final void refresh() {
refreshAction.loadData(callback);
}
}
Then you can do
public class YourViewModel extends ViewModel {
private final GithubRepository githubRepository;
public YourViewModel(GithubRepository githubRepository, SavedStateHandle savedStateHandle) {
this.githubRepository = githubRepository;
}
private final LiveData<String> userId = savedStateHandle.getLiveData("userId"); // from args
private final RefreshLiveData<List<Project>> refreshLiveData = Transformations.switchMap(userId, (uId) -> {
return githubRepository.getProjectList(uId);
});
public void refreshData() {
refreshLiveData.refresh();
}
public LiveData<List<Project>> getProjects() {
return refreshLiveData;
}
}
And then repository can do:
public RefreshLiveData<List<Project>> getProjectList(String userId) {
final RefreshLiveData<List<Project>> liveData = new RefreshLiveData<>((callback) -> {
githubService.getProjectList(userId).enqueue(new Callback<List<Project>>() {
#Override
public void onResponse(Call<List<Project>> call, Response<List<Project>> response) {
callback.onDataLoaded(response.body());
}
#Override
public void onFailure(Call<List<Project>> call, Throwable t) {
}
});
});
return liveData;
}

How to call Activity method from Presenter in Clean architecture?

I am developing an app where I am using clean architecture. In presenter, when something comes to method onCompleted then I must call function from Main activity.
this is my Presenter:
public class CheckInPresenter implements Presenter {
UseCase postCheckInUseCase;
Context context;
#Inject
CheckInPresenter(#Named("putCheckIn") UseCase postCheckInUseCase){
this.postCheckInUseCase = postCheckInUseCase;
}
public void initialize(){this.initializeCheckIn();}
public void initializeCheckIn(){this.putCheckIn();}
public void putCheckIn(){
this.postCheckInUseCase.execute(new CheckInSubscriber());
}
#Override
public void resume() {
}
#Override
public void pause() {
}
#Override
public void destroy() {
}
private final class CheckInSubscriber extends DefaultSubscriber<EventEntity>{
#Override
public void onCompleted() {
Log.d("onCompleted", "OnCompleted");
}
#Override
public void onError(Throwable e) {
Log.d("onError", "OnError: " + e.getMessage());
}
#Override
public void onNext(EventEntity eventEntity) {
Log.d("onNext", "OnNext");
}
}
}
And this is my function from MainActivity that I have to call:
public void getDataForToolbar() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.Account_json), Context.MODE_PRIVATE);
final String account = sharedPreferences.getString(getResources().getString(R.string.account_json), null);
if (account != null) {
Gson gson = new Gson();
mAccount = gson.fromJson(account, AccountModel.class);
for (CompanyModel com : mAccount.getCompanies()) {
String name = com.getName();
company_name.setText(name);
logo_url = com.getLogo_url();
}
if (logo_url == null || logo_url.isEmpty()) {
Picasso
.with(this)
.load(R.drawable.default_company)
.resize(70, 58)
.transform(new RoundedTransformation(8, 0))
.into(toolbarImage);
} else {
picassoLoader(this, toolbarImage, logo_url);
}
String username = mAccount.getUsername();
if(mAccount.getStatus()){
aUsername.setText(username + "/" + getResources().getString(R.string.on_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorGreen));
}else{
aUsername.setText(username + "/" + getResources().getString(R.string.off_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorWhite));
}
}
}
Could someone helps me how to call this function into my onCompleted method in Presenter? Thanks in advance.
If you want to call some Activity's function from another object, you'll have to pass Activity's reference to that object. This means that you need to add Activity parameter to presenter's constructor.
Side note
I know that what you're implementing is called a "clean architecture" in many places (including the official MVP tutorials by Google), but you might want to read my posts on the subject in order to get an alternative view on what "clean" on Android should look like.
Why activities in Android are not UI elements
MVC and MVP architectural patterns in Android
Create interface IView and make your Activity to implement it.
In IView create method void getDataForToolbar();
I see #Inject annotation in your CheckInPresenter, so if you are using Dagger 2, update you Dagger module's constructor with IView, create a provider method for it and provide it for CheckInPresenter in this module.
Place IView in constructor of CheckInPresenter and update provider method for CheckInPresenter in Dagger module and Dagger component initialization in your Activity.
For example, it might look like this:
public class YourActivity implements IView {
...
}
#Module
public class YourModule {
private IView view;
public YourModule(IView view) {
this.view = view;
}
#Provides
public IView provideView() {
return view;
}
#Provides
#YourScope
public Presenter providePresenter() {
return new YourPresenter(view);
}
}
Just complete your existing Presenter and Module with IView.
After that call in your onCompleted method view.getDataForToolbar().

Categories

Resources