VSchreyer VSchreyer - 2 months ago 10
Android Question

Attempt to invoke virtual method '...TextView.setText(java.lang.CharSequence)' on a null object reference

I'm an German and new in android, so sorry for bad english or silly mistakes...
I want to edit the text of my TextView.
Eventhough I've read the problems with my error message, I didn't find a solution...
I'm receiving the error message in the title due to the following code.
Why?

Java Code (just the OnCreate Method where it shows up the error)

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TextView t= (TextView)findViewById(R.id.startofweek);
t.setText("05.09.2016");

setContentView( R.layout.activities);
}


FXML (just the Part of the TextView, originally it is placed in a FrameView)

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/example"
android:layout_gravity="left|top"
android:layout_marginTop="20dp"
android:layout_marginLeft="70dp"
android:background="#00ffffff"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="20dp" />


Would be happy if someone has a solution for me :)

Answer

Simple problem and even simpler fix. You are accessing a view prior to inflating layout. Your code needs to instead by rearranged this way

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView( R.layout.activities);

    TextView t= (TextView)findViewById(R.id.startofweek);
    t.setText("05.09.2016");

}
Comments