tags:

views:

94

answers:

2

I have recently started on android.

i have written this piece of code

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

public class ArrangeMe extends Activity {
    private Button button1;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        this.button1 = (Button)findViewById(R.id.buttonOne);
        this.button1.setOnClickListener(new OnClickListener() {
            //@Override
            public void onClick(View v) {
             finish();
            }
        });
        setContentView(R.layout.main);
    }
}

and my main.xml looks as below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:text="ArrangeMe"/>
<Button android:text="Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonOne"></Button>
</LinearLayout>

but when i pass through this line

this.button1 = (Button)findViewById(R.id.buttonOne);

i observe button1 = null. but when i type R.id. eclipse does suggest an auto complete buttonOne (that suggests layout xml is correct !)

where am I going wrong ?

edit:

interstingly, i tried the following code,

still the button does not appear. it has stopped crashing, but the button does not appear !

   button1 = new Button(getContext());
    button1.setText("1");
    addView(button1, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    button1.setOnClickListener(new OnClickListener() {
        //@Override
        public void onClick(View v) {
         finish();
        }
    });

this was giving error

i changed them to

   button1 = new Button(getBaseContext());
    button1.setText("1");
    addContentView(button1, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    button1.setOnClickListener(new OnClickListener() {
        //@Override
        public void onClick(View v) {
         finish();
        }
    });
+1  A: 

I think you should call setContentView(R.layout.main); After that you activity class should be aware there to find views.

Nikolay Ivanov
A: 

Thanks ivanov, both the codes worked after i moved the setContentView to top

so silly of mine

regards

jaggay
Don't post this, just accept his answer as the correct one. This is not a forum.
Whaledawg