Search code examples
javaandroidcrashtextviewfindviewbyid

Build your first app DisplayMessageActivity textview error, app crashes at startup


I started Build Your First App on Android Developer's Website. I get the following error in the DisplayMessageActivity.java file.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.amir.myapplication/com.example.amir.myapplication.DisplayMessageActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import static com.example.amir.myapplication.R.id.textView;

public class DisplayMessageActivity extends AppCompatActivity {

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

    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

    // Capture the layout's TextView and set the string as its text
    TextView textView = findViewById(R.id.textView);
    textView.setText(message);
   }
}

Additionally I am wondering why, when I type manualy:

textView.setText(message);

setText is turning red into an error, however when I copy paste it from the android tutorial setText is grey.

Please note that I am a complete beginner. I followed one basic Java course and started this android tutorial as my first home "project".

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="TextView"
    android:textColor="@android:color/holo_purple"
    android:typeface="sans"
    app:fontFamily="sans-serif"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

I fixed it by changing it into textView2 TextView textView = findViewById(R.id.textView2);


Solution

  • I fixed it by changing it into textView2 which was the id in my xml file (android:id="@+id/textView2")

    TextView textView = findViewById(R.id.textView2);