0

When i try to run the app on my phone,it force closes when i try to do activity 3. Logcat says:

01-13 17:53:25.368: E/AndroidRuntime(3235): Caused by: java.lang.NullPointerException 01-13 17:53:25.368: E/AndroidRuntime(3235): at android.app.activity3.onCreate(activity3.java:18)

where line 18 is

Button wg = (Button) findViewById(R.id.Back); 

heres my full code for activity3.java:

package android.app;
import android.app.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class activity3 extends Activity{

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main3);

        Button wg = (Button) findViewById(R.id.Back);
        wg.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    }
}

Thanks in advance

user1148715
  • 93
  • 1
  • 1
  • 6

4 Answers4

1

I don't see a button in the xml. And once you have that, it needs to have:

android:id="@+id/Back"
Jere
  • 3,377
  • 1
  • 21
  • 28
1

This is happening because you don't have a button declared in your view. Only a Textview. You must create the button in the view. You're referencing nothing hence the null.

You can find a nice example of how to make a button here.

Aidanc
  • 6,921
  • 1
  • 26
  • 30
1

You don't have button with id "Back" in xml posted, that is why you are getting null there. Add button entry in your xml.

kosa
  • 65,990
  • 13
  • 130
  • 167
1

You need to modify your xml:

<?xml version="1.0" encoding="utf-8"?>

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

    <!-- your textview -->
    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/text1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        />

    <!-- your back button -->
    <Button
        android:id="@+id/back"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Back"
        />

</RelativeLayout>

What I did:

  • Removed text and orientation from your root RelativeLayout, these do nothing.
  • Modified your height and width, feel free to change these as you please.
  • Added a Button with id of R.id.back and text of @string/Back.

You will now be able to reference your button using findViewById(R.id.back) and set your click listener.

sgarman
  • 6,152
  • 5
  • 40
  • 44