public List<User> getAllUsers() {
List<User> userList = new ArrayList<User>();
String selectQuery = "SELECT * FROM " + TABLE_USERS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
User user = new User(cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),cursor.getString(6));
userList.add(user);
} while (cursor.moveToNext());
}
return userList;
}
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, user._id); // User id
values.put(KEY_BLUETOOTH_NAME, user._bluetooth_name);
values.put(KEY_COLOR, user._color);
values.put(KEY_LAST_LAT, user._last_lat);
values.put(KEY_LAST_LNG, user._last_lng);
values.put(KEY_MODEL, user._model);
values.put(KEY_LAST_SEEN, user._last_seen);
db.insert(TABLE_USERS, null, values);
db.close();
}
用户类属性
public class User {
String _id;
String _bluetooth_name;
String _color;
String _last_seen;
String _model;
String _last_lng;
String _last_lat;
public User(String id, String bluetooth_name, String color, String last_seen, String model, String last_lng, String last_lat){
this._id = id;
this._bluetooth_name = bluetooth_name;
this._color = color;
this._last_seen = last_seen;
this._model = model;
this._last_lat = last_lat;
this._last_lng = last_lng;
}
}
DatabaseHandler dh = new DatabaseHandler(getApplicationContext());
dh.clearTable(); //clear the table
User user = new User("1","2","3","5","6","7","8"); //add dummy user
dh.addUser(user);
List<User> userlist = dh.getAllUsers(); //all users properties are null, except "id" (which is the first prop, value: "1")
可能是一个简单的问题,因为这是我第一次尝试在 android 中使用 SQLite:
我正在尝试获取已添加到用户 SQLite 表中的所有用户。但是我的所有用户只设置了第一个属性“id”。谁能解释一下为什么?
更新:
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "(" +
KEY_ID + " INTEGER PRIMARY KEY," +
KEY_BLUETOOTH_NAME + " TEXT," +
KEY_COLOR + " TEXT," +
KEY_LAST_LAT + " TEXT," +
KEY_LAST_LNG + " TEXT," +
KEY_LAST_SEEN + " TEXT," +
KEY_MODEL + " TEXT" + ")";
db.execSQL(CREATE_USERS_TABLE);
}