I am new to Android.
I have read through the threads and tried various solutions but none worked for me. Here is what I have which works.
public class Tab1 extends Fragment {
TextView mTextView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
mTextView = (TextView)rootView.findViewById(R.id.myTextView1);
mTextView.setText("This works"); //This works fine
return rootView;
}
}
This will update the TextView just fine with the words "This works".
But when I try this to make it more flexible so I can update it while the app is running, it fails on me with this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.schoolproject.tabs.Tab1.changeText(Tab1.java:29)
public class Tab1 extends Fragment {
TextView mTextView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
mTextView = (TextView)rootView.findViewById(R.id.myTextView1);
return rootView;
}
public void changeText(String mText) {
mTextView.setText(mText);
}
}
It DOESN'T even let me compile. If I comment out the line mTextView.setText(mText) then it will compile. Why is .setText() triggering this error? My goal was to update the TextView from my MainActivity like so:
Tab1 tab1 = new Tab1();
tab1.changeText("Please Update This Text");
Thanks!