Error "Cannot resolve Symbol editText" in Android Studio MyFirstApp tutorial

Viewed 8035

I'm new to Android Studio and Android development. So I was following the tutorial given by developer.android.com and I'm having an error in this line : EditText editText = (EditText) findViewById(R.id.editText); The error is saying that : cannot find symbol variable editText .

This is part of my code :

import android.os.Bundle;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {
   
    public void sendMessage(View view){
        EditText editText = (EditText) findViewById(R.id.editText);
        String message = editText.getText().toString();

    }
}
6 Answers

I had the same issue as you OP. I went back to the activity_main.xml and noticed the ID was different somehow in the top right corner under attributes for the Text box. Changed the ID back and reran the app and no issues/

The reason is that you need to write editTextTextPersonName2 instead of editText to match the definition in activity_main.xml:

android:id="@+id/editTextTextPersonName2"

The code shall thus be as follows:

public void sendMessage(View view) 
{
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editTextTextPersonName2);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

R.id.editTextTextPersonName2 cause problem. You can try R.id.editText and follow the recommendation mentioned by others by adding android:id="@+id/editText" in activity_main.xml

Related