0

Here is my MainActivity.java code :

package com.dg.buttontest3;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.d("dg","button was clicked");
}
}

And here is the activity_main.xml code :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="18dp"
    android:layout_marginTop="18dp"
    android:text="Button" />
    </LinearLayout>

I am getting the following error while running this code on Eclipse ADT : button1 cannot be resolved or is not a field. I don't understand what is wrong with my code. Please help.

KhiladiBhaiyya
  • 633
  • 1
  • 14
  • 43

1 Answers1

1

You haven't posted your XML code, but as this code seems to be working properly:

button = (Button)findViewById(R.id.button1);

I'd guess that in your activity_main.xml you never create something called button1, or that you don't use the @+id/ prefix.

It should look something like:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button1"/>

Just realised something else, you need to change your LinearLayout opening tag so it has a >.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

That might cause the button to never properly be recognised.

fear7
  • 81
  • 6
  • I have posted my xml code, can you look at it now ? – KhiladiBhaiyya Aug 05 '15 at 12:54
  • If you're still working on the main activity (i.e. just beginning) you could consider starting a new project from scratch to see if that fixes the issue. EDIT: might have found it – fear7 Aug 05 '15 at 13:12