1

Im new to androiod coding. Ive only ever published one app which was a simple piano. Im trying to make a flash card app for studying but it keep crashing. When I debug I get a nullPointerException which Im not exactly sure what it means. Here is my code(I dont understand how to post code):

package com.example.hostoryflashcards;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends ListActivity{
String classes[] = {
        "Usa", "Canada", "New Mexico", "Other3", "Other4", "Other5"
};
String answer[] = {
        "Washington DC", "Ottowa", "Santa fae"
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_expandable_list_item_1, classes));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    super.onListItemClick(l, v, position, id);

    Button b1;
    b1 = (Button)findViewById(position);
    b1.setText("test");

}

}

Whats my problem?

Thanks, Jason

4

3 回答 3

2

你没有说你在哪里NullPointerException,但我想问题在于:

b1 = (Button)findViewById(position);
b1.setText("test");

b1 == Null,所以当你这样做时,你b1.setText("test")会得到一个NullPointerException.

编辑:

正如@Martin Cazares 指出的那样:

“您错过了 onCreate 上的“setContentView”调用以膨胀视图,然后在尝试获取按钮(或任何其他视图)的引用后,您得到 null,然后崩溃......”

于 2013-11-02T00:16:32.753 回答
1

假设您的布局文件名为 activity_main.xml

只需将此代码添加到您的 super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

在那里你得到它的工作。

于 2013-11-02T03:43:19.863 回答
0

尝试这个...

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
   super.onListItemClick(l, v, position, id);
   TextView textView = (TextView)v;
   textView.setText("test");
}
于 2013-11-02T04:45:26.103 回答