-4

I have this code in Activity.java:

 public void scan(View view){
    EditText text = (EditText) findViewById(R.id.editText3);
    text.setText("asdas");
}

and this in Activity xml:

<Button
    android:id="@+id/button"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:onClick="scan"
    android:text="Scane"
    android:textColor="#fff"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    tools:layout_editor_absoluteY="271dp"
    tools:layout_editor_absoluteX="8dp" />

<EditText
    android:id="@+id/editText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName"
    android:text="Name"
    tools:layout_editor_absoluteX="89dp"
    tools:layout_editor_absoluteY="165dp" />

When click on button the app crash with:

Attempt to invoke virtual method 'void 
android.widget.EditText.setText(java.lang.CharSequence)' on a null object reference

Why, im use Android Studio latest version??

Phantômaxx
  • 36,442
  • 21
  • 78
  • 108

4 Answers4

0

seems that findViewById returns null: i.e. it does not find your edit-text for some reason.

maybe you only need to rebuild the project: Build - Rebuild Project

otherwise you have messed up something else and must post more info

TmTron
  • 10,318
  • 3
  • 52
  • 97
0

Put this Edittext intialization code in onCreate method .

EditText text;
protected void onCreate(Bundle savedInstanceState) {
 text = (EditText) findViewById(R.id.editText3);
}

public void scan(View view){
    text.setText("asdas");
}
Rose
  • 176
  • 1
  • 1
  • 9
0

Your findViewById is returning null since it doesn't have the context. I think you are passing view object for context but not using it. Try changing

EditText text = (EditText) findViewById(R.id.editText3);

to

EditText text = (EditText) view.findViewById(R.id.editText3);
Ranjan
  • 1,006
  • 10
  • 20
0

In the below code, you get the related EditText object

EditText text = (EditText) findViewById(R.id.editText3);

Then, you called the setText() method of that object but take null object reference

text.setText("asdas");

It means that you cannot get the EditText object properly. Thus the origin of the error causes from the below line:

EditText text = (EditText) findViewById(R.id.editText3);

Please be sure to invoke scan() method inside the right context. Try to invoke it inside onCreate() method. If you invoke findViewById() method from a different place, be sure to invoke it from the right context.

oiyio
  • 3,108
  • 3
  • 34
  • 41