如何在“onActivityCreated”之前实现匕首注入

时间:2015-10-13 17:59:38

标签: android dagger

当我想在“onViewCreated”中使用注入对象时:

@Inject
ItemsManager itemsManager;

private RecyclerView mRecyclerView;
private ExercisesAdapter mAdapter;
private List<ExerciseModel> mModels;

public static ExercisesFragment newInstance() { return new ExercisesFragment(); }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_exercises, container, false);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.exercises_list);
    mModels = new ArrayList<>();
    itemsManager.getExercises();

    return view;
}

我有例外:

java.lang.RuntimeException: Unable to start activity ComponentInfo{fitmate.gorzala.com.fitmate_android/fitmate.gorzala.com.fitmate.activities.ExerciseActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5146)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at fitmate.gorzala.com.fitmate.activities.fragments.ExercisesFragment.onCreateView(ExercisesFragment.java:51)
        at android.app.Fragment.performCreateView(Fragment.java:1700)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
        at android.app.BackStackRecord.run(BackStackRecord.java:684)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)

也许有人知道如何解决这个问题? 我有任何必要的模块。 在另一个视图中,当我在“onActivityCreated”中使用注入对象时,一切正常

1 个答案:

答案 0 :(得分:2)

由于您正在活动的onCreate方法中进行Dagger注射,注入的字段可用的第一个生命周期将在片段的onActivityCreated中。在onCreateView中膨胀您的视图,但在onActivityCreated中设置您的绑定和变量。