开发者

Android SQLit Search: NullPointerException?

I need to perform a search operation into my SQLite DB.

In my Activity, I have EditText for entering the keyword and a search Button. Once the user clicks the button, the EditText text will be stored in the keyword and sent to a search(String keyword) method in the DBHelper class.

I have this code in my SearchActivityfor onCreate() and onClick():

//SearchActivity class extends ListActivity and implements OnClickListener 
Button search;
DataBaseHelper myDbHelper;
SimpleCursorAdapter ca;
ListView lv;
EditText txt;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.search_layout);

    txt 开发者_JAVA技巧= (EditText) findViewById(R.id.search_term);
    search = (Button) findViewById(R.id.search_button);

    search.setOnClickListener(this);
}

public void onClick(View v) {
    try {
        myDbHelper.openDataBase();
    } catch (SQLException sqle) {}

    try {
    String keyword= txt.getText().toString();
    Cursor cursor = myDbHelper.search(keyword); //A method in my DB
    cursor.moveToFirst();
    String[] columns = {cursor.getColumnName(1)}; 
    int[] columnsLayouts = {R.id.item_title};
    ca = new SimpleCursorAdapter(this.getBaseContext(), R.layout.items_layout, cursor,columns , columnsLayouts);
    lv = getListView();
    lv.setAdapter(ca);

    } catch(Exception e){}
}

However, I got NullPointerException in the LogCat!! I couldn't find where the error is.

Anyone can help ?


The description to the NullPointerException could be a little more informative. But it is very likely that the NullPointerException occurs here:

1: Cursor cursor = myDbHelper.search(keyword); //A method in my DB
2: cursor.moveToFirst();
3: String[] columns = {cursor.getColumnName(1)}; 

or here:

1: try {
2:    myDbHelper.openDataBase();
3: } catch (SQLException sqle) {}

Either in the first part in line 1: or 2: or in the second part in line 2:

You should always check if objects which rely on the existence of data are not null. So you should check if cursor is null. Another thing could be that you never initialize myDbHelper.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜