iguarna iguarna - 2 months ago 22
Android Question

NullPointerException when calling findViewById in onCreate

Whenever I use findViewById in my Activity's onCreate I get a NullPointerException. For example:

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView mTextView = (TextView) findViewById(R.id.textview);
}


I have read that the problem might by that the views may not be fully loaded when I try to find them and that is why I get a null pointer. If I call for findViewById in onCreateView of my Activity's fragment, everything works fine:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView mTextView = (TextView) rootView.findViewById(R.id.textview);
}


However, I need to use mTextView outside this fragment class. I have seen many examples in Android's official documentation where findViewById is used in the Activity's onCreate. What am I doing wrong?

Answer

From the layout xmls, place your textview in the layout xml- activity_main so the activity's setContentView can find it there.

Currently the textview is in the layout xml fragment_main

fyi: fragment_main and activity_main are two different layouts. If your app structure doesn't demand the fragment then you don't need it at all.

Comments