Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 356
VSchreyer Avatar asked Sep 06 '16 19:09

VSchreyer


2 Answers

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.activity);

    TextView t= (TextView)findViewById(R.id.startofweek);
    t.setText("05.09.2016");    
}
like image 126
FriendlyMikhail Avatar answered Nov 10 '22 06:11

FriendlyMikhail


In your xml file, you used "example" as the id of your TextView. But, inside the code, you are looking for "R.id.startofweek" when you are initializing your TextView.

PS: You also called "setContentView( R.layout.activities);" after the variable initialization. It has to be done before you initialize the TextView.

You can use the following code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView( R.layout.activities);

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

} 
like image 43
Hungry Coder Avatar answered Nov 10 '22 06:11

Hungry Coder