Nibirue
Nibirue

Reputation: 411

Android app and java activities, issues with onCreate() method and XML

I am trying use the onClick() function in an activity for an android app. So far I have:

public class Activity2 extends Activity implements OnClickListener {

    private ImageButton closeButton;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);

        Button myButton = (Button) findViewById(R.id.wowButton);
        myButton.setOnClickListener(this);


        this.closeButton = (ImageButton)this.findViewById(R.id.close);
        this.closeButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v){
                finish();
            }
        });   
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        TextView lowerText = (TextView) findViewById(R.id.textView2);
        EditText boxText = (EditText) findViewById(R.id.editText1);
        lowerText.setText(boxText.getText());       
    }

}

This is just a stripped down version of my project. When I enter my app as usual in the emualtor, everything works fine. When I click the button to open up this particular activity, everything crashes. I assume the issue lies within the onClick() method. This code was sent to me by my project partner without the XML files so I think thats where the problem lies.

here is my basic XML file that I thought should work:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="vertical">

    <Button android:id="@+id/wowButton" android:layout_width="fill_parent"
        android:layout_height="200dp" android:text="WoW" android:typeface="sans"
        android:background="@drawable/btn_default_normal_red" />

    <EditText 
        android:id="@+id/editText1"
        />

    <TextView 
        android:id="@+id/textView2"
        />

</LinearLayout>

While very basic, I though it should work. Thanks for your help.

Upvotes: 0

Views: 93

Answers (1)

Huang
Huang

Reputation: 4842

you instantiate an ImageButton through this.closeButton = (ImageButton)this.findViewById(R.id.close); But you don't declare it in the xml file. That's why it's null and throws a NullPointer Exception.

Upvotes: 3

Related Questions