android代码从数据库中获取数据

时间:2010-08-23 05:48:01

标签: android nullpointerexception android-cursor

    ParsedNotificationDataSet result = new ParsedNotificationDataSet();
    Cursor c = db.rawQuery("select * from notificationtable", null);
    if (c.getCount() > 0) {
        c.moveToFirst();
        do {
            result.setclassurl(c.getString(c.getColumnIndex("Id")));
            result.settype(c.getString(c.getColumnIndex("type")));
            result.setschool(c.getString(c.getColumnIndex("school")));
            result.setdescription(c.getString(c.getColumnIndex("description")));
            result.settitle(c.getString(c.getColumnIndex("title")));
            result.setdatePosted(c.getString(c.getColumnIndex("datePosted")));
            results.add(result);
        } while (c.moveToNext());
    }

这是我从数据库中获取数据的代码。在我看来,它应该正常工作,但在第一次生成java.lang.NullPointerException异常时。之后它运行没有问题。我需要做些什么修改才能解决这个问题?

2 个答案:

答案 0 :(得分:3)

您可以尝试以下代码。我认为它会起作用,不会给出NullPointerException错误。

Cursor c = db.rawQuery("select * from notificationtable", null);

if (c.getCount() > 0) {
  while (cursor.moveToNext()) {
    result.setclassurl(c.getString(c.getColumnIndex("Id")));
    result.settype(c.getString(c.getColumnIndex("type")));
    result.setschool(c.getString(c.getColumnIndex("school")));
    result.setdescription(c.getString(c.getColumnIndex("description")));
    result.settitle(c.getString(c.getColumnIndex("title")));
    result.setdatePosted(c.getString(c.getColumnIndex("datePosted")));
    results.add(result);
  }

}

答案 1 :(得分:2)

我用这种方式使用数据库。你可以试试这种方式。   您首先创建ContactDbAdapter类文件,如下所示..

public class ContactDbAdapter {

  public static final String KEY_NAME = "name";
  public static final String KEY_SCORE = "score";
  public static final String KEY_ROWID = "_id";

   private static final String DATABASE_CREATE = "create table contactdetails (_id integer primary key autoincrement,"
        + "name text not null, score integer not null);";

  private static final String DATABASE_NAME = "contacts";
  private static final String DATABASE_TABLE = "contactdetails";
  private static final int DATABASE_VERSION = 3;

  public static final String TAG = "ContactDbAdapter";

private final Context mCtx;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS contactdetails");
        onCreate(db);
    }

}

public ContactDbAdapter open() throws SQLiteException {
    mDbHelper = new DatabaseHelper(mCtx);       
    try {
        mDb = mDbHelper.getWritableDatabase();
        } catch (SQLiteException ex) {
          mDb = mDbHelper.getReadableDatabase();
        }
    return this;
}

public ContactDbAdapter(Context ctx) {
    this.mCtx = ctx;
}

public void close() {
    mDbHelper.close();
}

public long createContact(String name, int score) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_SCORE, score);       

    return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public int updateEntry(long _rowIndex, String name, int score) {

      String where = KEY_ROWID + "=" + _rowIndex;

      ContentValues initialValues = new ContentValues();
      initialValues.put(KEY_NAME, name);
      initialValues.put(KEY_SCORE, score);       

      // TODO fill in the ContentValue based on the new object
      return mDb.update(DATABASE_TABLE, initialValues, where, null);
    }

public boolean deleteContact(long rowId) {
    Toast.makeText(this.mCtx, "RowID:" + rowId, Toast.LENGTH_LONG).show();
    return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

public Cursor fetchAllContacts() {
    String order = KEY_SCORE + " DESC ";
    return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
            KEY_SCORE}, null, null, null, null, order);
   }

}

而且你可以在你的活动java类中直接调用这个方法。

 private ContactDbAdapter mDbHelper;
 public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       mDbHelper = new ContactDbAdapter(this);
       mDbHelper.open();

   Cursor cursor = mDbHelper.fetchAllContacts();
   startManagingCursor(cursor);
}

所以这将从表中获取所有记录。然后光标将以您使用的相同方式使用。