我的代码如下。当用户在EditText上键入时,我想过滤列表视图的数据。我的数据源是一个数据库。它给出了空指针异常!
请有人帮助我。
我的代码如下。当用户在EditText上键入时,我想过滤列表视图的数据。我的数据源是一个数据库。它给出了空指针异常!
请有人帮助我。
package com.learn24bd.dictionary;
import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
private SQLiteDatabase database;
private static final String DB_NAME = "myDictionary";
private static final String TABLE_NAME = "sortForm";
private static final String SORT_FORM = "field2";
private static final String FULL_FORM = "field3";
EditText etSearch;
public ArrayList<String> friends;
ArrayAdapter<String> adapter1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etSearch = (EditText) findViewById(R.id.etSearch);
ListView lvFirst = (ListView) findViewById(R.id.lvFirst);
// at this on create method for open the database
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this,
DB_NAME);
database = dbOpenHelper.openDataBase();
lvFirst.setTextFilterEnabled(true);
adapter1 = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, friends);
lvFirst.setAdapter(adapter1);
etSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
MainActivity.this.adapter1.getFilter().filter(arg0);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
}
});
friends = new ArrayList<String>();
Cursor friendCursor = database.query(TABLE_NAME, new String[] {
SORT_FORM, FULL_FORM }, null, null, null, null, FULL_FORM);
friendCursor.moveToFirst();
if (!friendCursor.isAfterLast()) {
do {
String sForm = friendCursor.getString(0);
String fForm = friendCursor.getString(1);
friends.add(sForm);
friends.add(fForm);
} while (friendCursor.moveToNext());
}
friendCursor.close();
}
}
我的XML文件是
<?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" >
<EditText
android:id="@+id/etSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<ListView
android:id="@+id/lvFirst"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
请帮助
答案 0 :(得分:0)
您需要更改您的pojo类toString方法或类似于给定链接中的处理