I have an almost completely Vanilla App. All I\'m trying to do is change the text of a textView, but it gives me a NullPointerException. I have no XML configuration, no added me
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.
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;
}
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);