textView setText() NullPointerException

老子叫甜甜 提交于 2019-12-02 03:10:17

Can you post xml? It's likely that the id your java is assuming "R.id.textView1" is wrong. Maybe R.id.textview1?

Well if your text view lives inside the fragment just do this:

@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            TextView tv = (TextView) rootView.findViewById(R.id.textView1);
        tv.setText("Teststring");
            return rootView;
        }
enissay

You are giving setContentView() the wrong layout if your XML is actually declared as fragment_main. That is why the controls are currently null.

// The layout file is not correct.
setContentView(R.layout.activity_second);

The TextView textView1 you are trying to refer is in the Fragment's inflated layout. The content view you have set in the Activity is activity_main.xml, which probably doesn't have the textView1 component.

The solution is to override the Fragment's onViewCreated() method and set the text there

@Override
public void onViewCreated (View view, Bundle savedInstanceState)
{
    TextView tv = (TextView) view.findViewById(R.id.textView1);
    tv.setText("My text");
    /* Other code here */
}

Remember to call view.findViewById(R.id.textView1) and not just findViewById(R.id.textView1) because in the latter, you are trying to access the enclosing class non-static method in a static inner class. By calling view.findViewById(R.id.textView1) you are calling a method of a local variable in the static inner class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!