Dagger 2 field injection is not working in Android - java

The issue is that I try to use field injection with Dagger 2, but at runtime field, that should be injected, always is null. Also I try to use MVVM pattern. Here is my code:
ProfileActivity.java:
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "ProfileActivity: onStart: ");
final ProfileViewModel profileViewModel
= ViewModelProviders.of(this).get(ProfileViewModel.class);
profileViewModel.init();
profileViewModel.getUser().observe(this, new Observer<User>() {
#Override
public void onChanged(#Nullable User user) {
if (user != null) {
Log.d(TAG, "ProfileActivity: onStart: " + user.toString());
} else {
Log.d(TAG, "ProfileActivity: onStart: user == null");
}
}
});
}
ProfileViewModel.java:
public class ProfileViewModel extends ViewModel {
private LiveData<User> user;
#Inject
UserRepository userRepository;
public ProfileViewModel() {
Log.d(TAG, "ProfileViewModel: Constructor: ");
}
public void init() {
Log.d(TAG, "ProfileViewModel: init: ");
user = userRepository.getUser();
}
public LiveData<User> getUser() {
Log.d(TAG, "ProfileViewModel: getUser: ");
return user;
}
}
UserRepository.java:
#Singleton
public class UserRepository {
private LiveData<User> user;
#Inject
public UserRepository() {
Log.d(TAG, "UserRepository: Constructor: ");
}
public LiveData<User> getUser() {
Log.d(TAG, "UserRepository: getUser: ");
if (user != null) {
return user;
} else {
// There should be userDao.load() call,
// but it had been omitted for brevity.
MutableLiveData<User> user = new MutableLiveData<>();
user.setValue(DB.getUser());
return user;
}
}
}
MyApplication.java:
public class MyApplication extends MultiDexApplication implements HasActivityInjector {
#Inject
DispatchingAndroidInjector<Activity> dispatchingAndroidInjector;
#Override
public void onCreate() {
super.onCreate();
DaggerMyApplicationComponent.create().inject(this);
}
#Override
public DispatchingAndroidInjector<Activity> activityInjector() {
return dispatchingAndroidInjector;
}
}
MyApplicationModule.java:
#Module
public abstract class MyApplicationModule {
#ContributesAndroidInjector
abstract ProfileActivity contributeActivityInjector();
}
MyApplicationComponent.java:
#Component(modules = { AndroidInjectionModule.class, MyApplicationModule.class})
#Singleton
public interface MyApplicationComponent extends AndroidInjector<MyApplication> {
void inject(ProfileActivity profileActivity);
}
At runtime I can see the next logs:
ProfileActivity: onStart:
ProfileViewModel: Constructor:
ProfileViewModel: init:
And the app crashes on user = userRepository.getUser(); inside ProfileViewModel's init() method.
It means that UserRepository had not been injected. Also it is indicated by missing UserRepository: Constructor: log.
Where is my mistake? Thank you.

Basically what you need to do is to use ViewModel Factory to pass injected UserRepository into your ViewModels constructor, initialize it and then you will be able to use it. You cannot use field or parameter injections in ViewModels.
I would suggest you to follow this article: Add the new ViewModel to your MVVM
It provides enough sufficient information to begin using Dagger 2 with Architecture Components.
Hope it helps.

Related

Java classes and interface combination

I'm trying to create couple of Java class to perform certain work. Let's say I want to get the task done by calling my classes like this:
FirebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = task.getResult().getUser();
// ...
} else {
// Sign in failed, display a message and update the UI
Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
}
}
}
});
I could understand up to signInWithCredential(). I can't figure out how to implement addOnCompleteListener() and have a interface as argument.
I've currently create my top class like FirebaseAuth with methods like getInstance () and signInWithCredential(). Also, I tried creating an interface but I am getting error that result of the interface is never used. How can I implement the style of addOnCompleteListener(parameter 1, interface 2).
Here, addOnCompleteListener is getting parameters of activity and interface and in my case, I will be using the activity parameter for some work.
P.S: I found out this is called interface callback. If it's right, any guidance to it's structure will be great
You can do it like this:
Create an interface:
public interface onCompleteListener {
void onComplete(MyTask object);
}
Define your MyTask class:
public abstract class MyTask {
public abstract boolean someFunc1();
public abstract String someFunc2();
public abstract String someFunc3();
}
In your main class:
public class MainClass{
public static MainClass instance;
private static Activity mActivity;
public onCompleteListener onCompleteListener;
private MainClass(Activity activity) {
mActivity = activity;
}
public static synchronized MainClass getInstance(Activity activity) {
if (instance == null) {
instance = new MainClass(activity);
}
return instance;
}
public void addOnCompleteListener(#NonNull onCompleteListener var2) {
onCompleteListener = var2;
//Call your task function
doTask();
}
public void doTask(){
MyTask o = new MyTask() {
#Override
public boolean someFunc1() {
return true;
}
#Override
public String someFunc2() {
return "";
}
#Override
public String someFunc3 {
return "";
}
};
//Once done, pass your Task object to the interface.
onCompleteListener.onComplete(o);
}
}
Usage:
MainClass.getInstance(MainActivity.this).addOnCompleteListener(new onCompleteListener() {
#Override
public void onComplete(MyTask object) {
doYourWork(object);
}
});

How to get values from an AsyncTask when it is in another class

I need to get the result from my AsyncTask. I can actually get the result from the task but I just don't know how to get it from the method that needs it. As will see, the AsyncTask is in a different class. If you have a question so I can clarify, please tell me so I can edit the post. See my code below:
public class UserRepository {
private UserDao userDao;
private User user;
private LiveData<List<User>> allUsers;
public UserRepository(Application application) {
AtsDatabase database = AtsDatabase.getInstance(application);
userDao = database.userDao();
allUsers = userDao.getUsers();
}
private MutableLiveData<User> userSearched = new MutableLiveData<>();
private void asyncFinished(User userResult) {
if(userResult == null) return;
Log.i("TAG", "asyncFinished: " + userResult.getLastName());
userSearched.setValue(userResult);
}
public LiveData<User> getUserByUserName(String userName) {
new GetUserByUserNameAsyncTask(userDao).execute(userName); ===> I NEED THE RESULT HERE SO I CAN PASS IT TO MY VIEW MODEL
}
public LiveData<List<User>> getAllUsers() { return allUsers; }
private static class InsertUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDao;
private InsertUserAsyncTask(UserDao userDao) { this.userDao = userDao; }
#Override
protected Void doInBackground(User... users) {
userDao.insert(users[0]);
return null;
}
}
private static class GetUserByUserNameAsyncTask extends AsyncTask<String, Void, User> {
private LiveData<User> user;
private UserDao userDao;
private GetUserByUserNameAsyncTask(UserDao userDao) { this.userDao = userDao; }
#Override
protected User doInBackground(String... strings) {
user = userDao.getUserByUserName(strings[0]); ======> I GET RESULT HERE
return null;
}
#Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
Log.i("TAG", "onPostExecute: "+user.getLastName());
delegate.asyncFinished(user);
}
}
}
How do I make this right? Thank you.
First of all, AsyncTask is now deprecated.
If you still want to use it, create a MutableLiveData and
return it as a LiveData in the exposed function, then pass it through the constructor of the AsyncTask.
Use the postValue method of the MutableLiveData to set the result after you get it.

command pattern, why does this not work

I am implementing a command pattern in android.
This is what I have right now. For some reason this does not run. It is like the AddUserRequest is getting garbage collected for some reason.
RequestManager.java:
public class RequestManager extends BroadcastReceiver {
private static final RequestManager instance = new RequestManager();
private boolean isConnected = false;
private static ArrayList<Request> requestQueue = new ArrayList<Request>();
private RequestManager() {
}
/* singleton class */
public static RequestManager getInstance() {
return instance;
}
public void invokeRequest(Request request) {
request.execute(); // only to test this, this will change
return;
}
}
AddUserRequest.java
public class AddUserRequest extends InsertionRequest {
User user;
public AddUserRequest(User user) {
this.user = user;
}
public void execute() {
System.out.println("TEST!!!");
}
}
Request.java:
public abstract class Request {
public abstract void execute();
}
}
InsertionRequest.java
public abstract class InsertionRequest extends Request {
}
RequestManagerTest.java
public class RequestManagerTest extends ActivityInstrumentationTestCase2 {
public RequestManagerTest(){
super(MainActivity.class);
}
public void testAddUserRequest() {
User user = new User();
user.setName("Tester12345");
AddUserRequest request = new AddUserRequest(user);
RequestManager.getInstance().invokeRequest(request);
}
}
For some reason this does not print "TEST!!!" and for the life of me I cannot figure out why. I looked in the debug log and everytime request.execute() in RequestManager.java gets called there is a "GC Explicit..." which I suspect has to do with garbage collection. What is the proper way to do what I am trying to do?

How to properly use Dagger2 with the new Android Architecture Components

I'm trying to use the new Architecture Components, but I'm also still new to dagger and I'm missing stuff.
With the below code, I'm getting a NullPointerException, can't locate where.
Also if there's something else I need to fix or improve, please suggest.
CODE :
ViewModel
public class PostsVM extends ViewModel {
private LiveData<StoryPost> post;
private Repository repository;
#Inject
public PostsVM(Repository repository) {
this.repository = repository;
}
public void init() {
if (this.post != null) {
return;
}
post = repository.getPosts();
}
public LiveData<StoryPost> getPost() {
return post;
}
}
Repository
#Singleton
public class Repository {
private final MutableLiveData<StoryPost> data = new MutableLiveData<>();
public LiveData<StoryPost> getPosts() {
//
new GetUser(post.getUid()) {
#Override
public void onSuccess(#NonNull User user) {
// this is where I setValue//
data.setValue(post);
}
#Override
public void onError() {
}
#Override
public void userNotFound() {
}
};
return data;
}
}
Singleton Factory
#Singleton
public class ViewModelFactory implements ViewModelProvider.Factory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;
#Inject
public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
this.creators = creators;
}
#SuppressWarnings("unchecked")
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
Provider<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("unknown model class " + modelClass);
}
try {
return (T) creator.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
DAO
#Dao
public interface PostDao {
#Query("SELECT * FROM posts ORDER by time DESC")
LiveData<List<StoryPost>> getAll();
#Query("SELECT * FROM posts WHERE id = :id")
LiveData<List<StoryPost>> getPost(String id);
#Insert(onConflict = OnConflictStrategy.REPLACE)
#NonNull
void insert(StoryPost... posts);
#Delete
void delete(StoryPost post);
#Update
void update(StoryPost post);
}
Then in MainActivity:
#Inject public ViewModelFactory factory;
//...
//*onCreate*
PostsVM model = ViewModelProviders.of(this, factory).get(PostsVM.class);
model.init();
final Observer<StoryPost> observer = post -> storyAdapter.insert(post);
model.getPost().observe(this, observer);
Logcat :
... java.lang.NullPointerException: Attempt to invoke interface method
'android.arch.lifecycle.ViewModel android.arch.lifecycle.ViewModelProvider
$Factory.create(java.lang.Class)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2479)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
at android.app.ActivityThread.access$900(ActivityThread.java:168)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1378)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:150)
at android.app.ActivityThread.main(ActivityThread.java:5665)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:689)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.arch.lifecycle.ViewModel android.arch.lifecycle.ViewModelProvider$Factory.create(java.lang.Class)' on a null object reference
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:128)
at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:96)
at com.aollay.smartpaper.MainActivity.bindDatabase(MainActivity.java:238)
at com.aollay.smartpaper.MainActivity.populateNews(MainActivity.java:233)
at com.aollay.smartpaper.MainActivity.config(MainActivity.java:159)
at com.aollay.smartpaper.MainActivity.onCreate(MainActivity.java:74)
at android.app.Activity.performCreate(Activity.java:6372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2432)
The issue is caused by the ViewModelFactory instance being null inside your MainActivity, as the NPE suggests. This itself is most probably caused by the fact that the ViewModelFactory is not being injected properly, thus remaining null. As Orest suggests inside the comments, you need to make sure that the MainActivity is properly injected from your AppModule:
MainActivity:
public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
AndroidInjection.inject(activity);
super.onCreate(savedInstanceState);
}
// if your Activity also has Fragments which need to be injected
#Inject
DispatchingAndroidInjector<Fragment> androidInjector;
#Override
public DispatchingAndroidInjector<Fragment> supportFragmentInjector()
{
return androidInjector;
}
}
You can take a look at most of the DI classes being used in a related question I posted earlier over at AndroidInjector<android.app.Activity> cannot be provided without an #Provides- or #Produces-annotated method and see if that setup helps you out.

Dagger 2 not injecting in interface type

I an trying to inject a field in an interface type which is implemented by a class.
Here is what i have done so far.
These are view interface:
public interface PostView extends View, ListView<Post>, EmptyView<String> {
}
public interface View {
public void showProgressIndicator();
public void hideProgressIndicator();
public void onSuccess();
public void onFailure();
public void onFailure(String message);
}
public interface ListView<E> {
public void onListItems(List<E> items,
int pageNum,
int pageSize,
boolean next);
}
public interface EmptyView<E> {
public void onEmpty(E e);
public void onEmpty(String message);
}
Components:
#Singleton
#Component(modules = ApiModule.class)
public interface ApiComponent {
Api provideApi();
}
#UserScope
#Component(dependencies = ApiComponent.class, modules = PostModule.class)
public interface PostComponent {
PostPresenter providePostPresenter();
void inject(NetworkTest networkTest);
}
Modules:
#Module
public class ApiModule {
private static final Logger logger = Logger.getLogger(ApiModule.class.getSimpleName());
private final String baseUrl;
public ApiModule(String baseUrl) {
this.baseUrl = baseUrl;
}
#Provides
#Singleton
boolean provideIsLoggerEnabled() {
logger.info("proviedIsLoggerEnabled()");
return true;
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient(boolean logEnabled) {
logger.info(" provideOkHttpClient(logEnabled)");
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
Interceptor requestInterceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(chain.request());
}
};
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addInterceptor(requestInterceptor)
.addNetworkInterceptor(interceptor);
return builder.build();
}
#Provides
#Singleton
Api provideApi(OkHttpClient okHttpClient) {
logger.info("provideApi");
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(Api.class);
}
}
#Module
public class PostModule {
private static final Logger logger = Logger.getLogger(PostModule.class.getSimpleName());
private final PostView postView;
public PostModule(PostView postView) {
this.postView = postView;
}
#Provides
#UserScope
PostService providePostService(Api api) {
logger.info("Provider post with api now");
return new PostService(api);
}
#Provides
#UserScope
PostPresenter providePostPresenter(PostService service) {
logger.info("Providing presenter with service now");
return new PostPresenter(postView, service);
}
}
Presenter:
public class PostPresenter extends AbstractPresenter {
private static final Logger logger = Logger.getLogger(PostPresenter.class.getSimpleName());
private PostView postView;
private PostService postService;
public PostPresenter(PostView postView, PostService postService) {
this.postView = postView;
this.postService = postService;
}
#Override
protected View getView() {
logger.info("Getting view");
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public void getPosts() {
logger.info("Getting posts ");
Call<List<Post>> posts = this.postService.getPosts();
postView.showProgressIndicator();
posts.enqueue(new Callback<List<Post>>() {
#Override
public void onResponse(Call<List<Post>> call, Response<List<Post>> rspns) {
postView.onListItems(rspns.body(), 1, 25, true);
postView.hideProgressIndicator();
postView.onSuccess();
}
#Override
public void onFailure(Call<List<Post>> call, Throwable thrwbl) {
onApiCallError(thrwbl);
postView.hideProgressIndicator();
}
});
}
}
public abstract class AbstractPresenter {
private static final Logger logger = Logger.getLogger(AbstractPresenter.class.getSimpleName());
protected abstract View getView();
/*
* General indication whether api call stated or not.
*/
protected void onApiCallStart() {
logger.info("Api call started");
View v = getView();
if (v != null) {
v.showProgressIndicator();
}
}
protected void onApiCallEnd() {
logger.info("Api call finished");
View v = getView();
if (v != null) {
v.hideProgressIndicator();
}
}
/*
* General error handling
*/
protected void onApiCallError(Throwable e) {
logger.info("Api call terminated with error");
View v = getView();
if (v != null && e != null) {
v.onFailure(e.getMessage());
}
}
}
NetworkTest:
public class NetworkTest implements PostView {
private static final Logger logger = Logger.getLogger(NetworkTest.class.getSimpleName());
private PostComponent component;
#Inject
PostPresenter presenter;
public NetworkTest(ApiComponent apiComponent) {
component = DaggerPostComponent.builder()
.apiComponent(apiComponent)
.postModule(new PostModule(this))
.build();
}
public void init() {
component.inject(this);
}
void showPosts() {
if (presenter != null) {
logger.info("Hurray it worked");
presenter.getPosts();
} else {
logger.warning("Alas it failed");
}
}
#Override
public void showProgressIndicator() {
logger.info("Show progress indicator here");
}
#Override
public void hideProgressIndicator() {
logger.info("Hide progress indicator here");
}
#Override
public void onSuccess() {
logger.info("Api calls successfull");
System.exit(0);
}
#Override
public void onFailure() {
logger.warning("Api call failure");
System.exit(0);
}
#Override
public void onFailure(String message) {
logger.warning(message);
System.exit(0);
}
#Override
public void onListItems(List<Post> items, int pageNum, int pageSize, boolean next) {
logger.info("List received is: " + new Gson().toJson(items));
}
#Override
public void onEmpty(String e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public static void main(String[] args) {
ApiComponent apiComponent = DaggerApiComponent.builder()
.apiModule(new ApiModule("https://jsonplaceholder.typicode.com/"))
.build();
NetworkTest networkTest = new NetworkTest(apiComponent);
networkTest.init();
networkTest.showPosts();
}
}
My Problem is when i try to use
void inject(NetworkTest networkTest); //It works
void inject(PostView postView); //Doesn't work
I want that PostPresenter should get Injected in any class who is implementing PostView.
But when i do this #Inject field return null.
Does anyone have any clue about this.
NetworkTest has an #Inject field that Dagger can detect at compile time. PostView does not. Dagger 2 can perform injection on both NetworkTest and PostView, but because PostView has no #Inject-annotated methods, there's nothing for Dagger 2 to inject.
If you want to express that arbitrary implementors of PostView can be injected, you should add an #Inject-annotated initialize or injectPresenter method (et al); otherwise, just get/inject concrete types from Dagger so all of their dependencies can be injected at once.
As stated in the Dagger 2 user's guide (emphasis mine), "Dagger is a fully static, compile-time dependency injection framework for both Java and Android." Unlike with Guice or Spring, Dagger 2 performs no runtime reflection, so (for instance) a generated Component method inject(PostView) can only inject fields and methods defined on PostView or its supertypes, and not anything defined on a subtype.
In a general sense, I don't think it's reasonable for you to expect (or constrain) your PostView interface implementors to require the injection of a Presenter a certain way; if you want to make an explicit presenter-providing lifecycle method, you can do that on PostView without involving Dagger, and that way your classes can be more specific with their dependencies rather than mixing the necessary deps with the "unnecessary-but-included" deps you prescribe.

Categories

Resources