1user1160804
1user1160804

Reputation: 53

NullPointerException when trying to change text of textview on click

I am trying to change the text of a textView after a user clicks on an image (could have easily been a button). I keep getting a force close and nullpointerexception. I'm trying to write it for Android 2.3.3

The code is based off many examples found on google.

public class TestImagesActivity extends Activity { 
    private android.view.View.OnClickListener mCorkyListener = new android.view.View.OnClickListener() { 
    public void onClick(View v) {
            final TextView txt = (TextView) findViewById(R.id.svariable);
            txt.setText("new text"); // this line throws an exception
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ImageView image = (ImageView) findViewById(R.id.test_image);
    image.setOnClickListener(mCorkyListener);
}

my main.XML looks like this:

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

    <TextView
        android.id="@+id/svariable"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ImageView 
   android:id="@+id/test_image"
   android:src="@drawable/test"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   />
</LinearLayout>

Upvotes: 0

Views: 429

Answers (6)

Kingamajick
Kingamajick

Reputation: 2291

Your issue is a typo.

android.id="@+id/svariable" should be android:id="@+id/svariable"

Upvotes: 0

FoamyGuy
FoamyGuy

Reputation: 46856

I think it is also worth noting that findViewById() is a fairly expensive method call in terms of device resources.

You should get your TextView reference from this call inside your onCreate method next the same call that you use to get your imageView reference. That way it doesn't get called each time the button is pressed.

Upvotes: 0

Egor
Egor

Reputation: 40218

The variable mCorkyListener is created when the activity class is loaded, before the onCreate method is called. And as you may know, you can't inflate any views before you call setContentView(layout), where layout is the parent view of your views. So your TextView inside the listener creation code will always be null. You should create the listener after the setContentView call. Hope this helps.

Upvotes: 0

Oscar Gomez
Oscar Gomez

Reputation: 18488

Just change in your XML android.id to android:id

Upvotes: 0

xpapad
xpapad

Reputation: 4456

In your XML you're using android.id instead of android:id for svariable.

Upvotes: 2

MByD
MByD

Reputation: 137382

You have a small problem in the XML, this:

android.id="@+id/svariable"

Should be:

android:id="@+id/svariable"

Upvotes: 1

Related Questions