简体   繁体   English

在片段中使用Butterknife时的java.lang.NullPointerException

[英]java.lang.NullPointerException in using Butterknife in a Fragment

I am getting java.lang.NullPointerException when trying to use Butterknife in a FRAGMENT. 尝试在FRAGMENT中使用Butterknife时,我得到了java.lang.NullPointerException What am I missing? 我错过了什么?

@Bind(R.id.tv_detail_startTime) TextView tv_detail_startTime;

@Override
public View onCreateView(LayoutInflater inflater,
                         @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    v = inflater.inflate(R.layout.fragment_detail_expanlv,
            container, false);
    ButterKnife.bind(getActivity());

    //THIS IS THE LINE WHERE 
    tv_detail_startTime.setText("Trying Butterknife out in Android");

}

If I use boiler plate code to declare tv_detail_startTime , it works. 如果我使用锅炉板代码声明tv_detail_startTime ,它可以工作。 Just using the Bind gives the error. 只使用Bind出错。

Complete Stacktrace: 完成Stacktrace:

10-29 04:30:28.971 24953-24953/com.mavdev.focusoutfacebook E/AndroidRuntime:   FATAL EXCEPTION: main
Process: com.mavdev.focusoutfacebook, PID: 24953
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at     com.mavdev.focusoutfacebook.fragments.scheduledblocks.Fragment_detail_expanlv.onCreateView(Fragment_detail_expanlv.java:424)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Bind the fragment not the activity 绑定片段而不是活动

View v = inflater.inflate(R.layout.xxx, container, false);
ButterKnife.bind(this, v);

ButterKnife probably assumes you are binding the activity view to an activity, not a fragment. ButterKnife可能假设您将活动视图绑定到活动,而不是片段。 Please try using ButterKnife.bind(this, getActivity()) (notice the extra this). 请尝试使用ButterKnife.bind(this, getActivity()) (注意额外的这个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM