简体   繁体   中英

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>

在您的XML中,您使用android.id而不是android:id来实现可变。

You have a small problem in the XML, this:

android.id="@+id/svariable"

Should be:

android:id="@+id/svariable"

只需将XML android.id更改为android:id

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.

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.

Your issue is a typo.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM