无法从sqlite数据库中检索数据

时间:2012-06-30 18:11:06

标签: android sqlite

在这个应用程序中,我希望当我点击按钮时,我的数据库中的数据显示在列表视图上,并使用OnItemClick()它应该显示另一个活动但不幸的是我的应用程序正在停止,因为我点击按钮Plzz告诉我我错了哪里这是我的活动类`

public class DictionaryActivity extends Activity {
protected EditText searchText;
protected DatabaseHelper d;
protected Cursor cursor;
protected ListAdapter adapter;
   protected ListView wordList;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    d = new DatabaseHelper(this);

    d.addWord(new Contact("Apple", "Fruit"));
    d.addWord(new Contact("Ape", "Animal"));
    d.addWord(new Contact("Boy", "Male"));
    d.addWord(new Contact("Bat", "Playing Object"));

    searchText = (EditText) findViewById(R.id.word);
    wordList = (ListView) findViewById(R.id.list);

    final Button button = (Button) findViewById(R.id.search);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            searchword(v);
        }
    });

}

public void searchword(View view) {

    // || is the concatenation operation in SQLite
    cursor = d.getData(searchText);
    adapter = new SimpleCursorAdapter(this, R.layout.word_list, cursor,
            new String[] { "word" }, new int[] { R.id.word });
    wordList.setAdapter(adapter);

    wordList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getApplicationContext(),
                    WordDetails.class);
            Cursor cursor = (Cursor) adapter.getItem(position);
            intent.putExtra("Word_ID",
                    cursor.getInt(cursor.getColumnIndex("id")));
            startActivity(intent);
        }

    });
}}`

这是DataBaseHelper Class

public class DatabaseHelper extends SQLiteOpenHelper {
protected SQLiteDatabase db;
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "Word_Meanings";

// Contacts table name
private static final String TABLE_NAME = "Meanings";

// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_WORD = "word";
private static final String KEY_MEAN = "mean";

private Contact contact;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_WORD + " TEXT,"
            + KEY_MEAN + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    // Create tables again
    onCreate(db);
}

// Adding new contact
void addWord(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_WORD, contact.getword()); // Contact Name
    values.put(KEY_MEAN, contact.getmean()); // Contact Phone

    // Inserting Row
    db.insert(TABLE_NAME, null, values);
    db.close(); // Closing database connection
}

// Updating single contact
public int updateWord(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_WORD, contact.getword());
    values.put(KEY_MEAN, contact.getmean());

    // updating row
    return db.update(TABLE_NAME, values, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
}

// Deleting single contact
public void deleteWord(Contact contact) {
    this.contact = contact;
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_NAME, KEY_ID + " = ?",
            new String[] { String.valueOf(contact.getID()) });
    db.close();
}

// Getting contacts Count
public int getCount() {
    String countQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

public Cursor getData(EditText s) {
    // TODO Auto-generated method stub


    String sql = "SELECT id, word FROM Meanings WHERE word LIKE ?";


    String sqlArgs[] = new String[] { s.getText().toString() + "%" };


    Cursor c = db.rawQuery(sql, sqlArgs);


    return c;

}}

这里是logcat:

E/AndroidRuntime(543): FATAL EXCEPTION: main E/AndroidRuntime(543): java.lang.NullPointerException 
E/AndroidRuntime(543): at com.Dictionary.DatabaseHelper.getData(DatabaseHelper.java:107) 
E/AndroidRuntime(543): at com.Dictionary.DictionaryActivity.searchword(DictionaryActivity.java:56) 
E/AndroidRuntime(543): at com.Dictionary.DictionaryActivity$1.onClick(DictionaryActivity.java:47) 
E/AndroidRuntime(543): at android.view.View.performClick(View.java:3511) 
E/AndroidRuntime(543): at android.view.View$PerformClick.run(View.java:14105) 
E/AndroidRuntime(543): at android.os.Handler.handleCallback(Handler.java:605) 
E/AndroidRuntime(543): at android.os.Handler.dispatchMessage(Handler.java:92) 
E/AndroidRuntime(543): at android.os.Looper.loop(Looper.java:137) 
E/AndroidRuntime(543): at android.app.ActivityThread.main(ActivityThread.java:4424) 
E/AndroidRuntime(543): at java.lang.reflect.Method.invokeNative(Native Method) 
E/AndroidRuntime(543): at java.lang.reflect.Method.invoke(Method.java:511) 
E/AndroidRuntime(543): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
E/AndroidRuntime(543): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) E/AndroidRuntime(543): at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

使用Cursor填充Adapter时,Cursor必须包含名为_id的列(请注意前面的_字符)。

将数据库CREATE更改为使用_id而不是id,或将SELECT更改为别名id更改为_id。例如......

String sql = "SELECT id as _id, word FROM Meanings WHERE word LIKE ?";

注意:如果您需要执行SELECT * ...之类的操作,您很可能无法对id列进行别名。在这种情况下,通常最好使用_id列创建数据库表。

编辑:顺便说一句,在您尝试使用getCount()之前,cursor.close()方法会在调用return cursor.getCount()时失败。当您关闭Cursor时,其资源将被释放,Cursor无效,这意味着cursor.getCount()无法正常工作。

编辑:另外,如上所述,在SQLiteDatabase db = getReadableDatabase()方法中调用db.rawQuery(...)之前使用getData(...)