0

I got Cannot resolve symbol button1 error from my code R.id.button1. I imported android.widget.Button and declared a variable button1 properly but I couldn't fix this error.

Here's my code:

    import android.content.Intent;
    import android.graphics.Color;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {
    Button button1;
    Button button2;
    Button button3;
    Button button4;

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

        button1 = (Button) findViewById(R.id.button1);
        button1.setBackgroundColor(Color.GRAY);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                Toast.makeText(getApplicationContext(),"Open the website",Toast.LENGTH_SHORT).show();
                Intent mIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.google.com"));startActivity(mIntent);
            }
                                   });
ishant kaushik
  • 891
  • 6
  • 18
Yun
  • 1
  • Please double check that you have a button in your activity_main layout file with the attribute android:id="@+id/button1" – TofferJ Nov 18 '21 at 01:51
  • Re duplink. Look specifically look at section 4.6 of the accepted answer ... issues with `R` on Android. – Stephen C Nov 18 '21 at 02:13

1 Answers1

0

Check the XML file where you places the button. There is a discrepancy of the id in XML and that in your Java file.

ensure this is how the Button attribute looks

<Button
android:id="@+id/button1

.../>
Meggrain
  • 178
  • 10