Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eclipse error with android: id cannot be resolved or is not a field

I just started playing around with android development, and already with just an attempt at making a button, I have encountered a problem. The error I'm given in the following code is right on "R.id.button1". It says id cannot be resolved or is not a field. Do I need to manually reference every single object I make in the layout xml file? I found that this did work, but it does seem to be a bit much for every button I want to make...

package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */

 private Button button1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener()
        {
         public void onClick(View v)
         {
          finish();          
         }        
        });
    }
}
like image 591
Jaynathan Leung Avatar asked Dec 07 '22 00:12

Jaynathan Leung


2 Answers

I've been wasting a lot of time (two weeks) because of the same problem until I discovered the problem wasn't mine but Eclipse's. I guess there's a lot of people with the same problem.

Just try this: Save your project, close Eclipse and then open it again. So simple.

like image 141
Carmelo Avatar answered Dec 21 '22 23:12

Carmelo


Do I need to manually reference every single object I make in the layout xml file

Yes, otherwise you won't be able to do anything with those views. It's not that bad actually. So, each time you create a view in your XML, and you want to reference it, put an ID:

<View
    android:id="@+id/the_id"/>

And then, from your code you can reference it using the R class. You can type, in the example, R.id.the_id and then Ctrl+Shift+O to make Eclipse auto import the needed files.

You can speed up your productivity by using frameworks like Roboguice; I think it's for lazy people, though.

like image 22
Cristian Avatar answered Dec 22 '22 01:12

Cristian