大家好我已经尝试过这段代码,但它没有用。我无法插入并从数据库sqlite android中选择。
问题: 我错了吗?
代码:
public class Test extends SQLiteOpenHelper {
private static final String DATABASE_CREATE = "CREATE TABLE PLS (" +
"id text, " +
"nama text);";
public Test(Context context) {
super(context, "ABC.db", null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
db.execSQL("INSERT INTO PLS VALUES('1', 'dede');");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS PLS");
onCreate(db);
}
public ArrayList<HashMap<String, String>> getUser() {
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT id, nama FROM PLS";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", cursor.getString(0));
map.put("nama", cursor.getString(1));
} while (cursor.moveToNext());
}
return wordList;
}
public void addUser(String id, String nama) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", id);
values.put("nama", nama);
database.insert("PLS", null, values);
database.close();
}
}
以下是插入和选择sqlite的代码:
controller = new Test(this);
user = new ArrayList<HashMap<String,String>>();
controller.addUser("1", "daniel");
user = controller.getUser();
for(int i=0; i<user.size(); i++){
tempMenu = new HashMap<String, String>();
tempMenu = user.get(i);
i1.setText(tempMenu.get("id"));
i2.setText(tempMenu.get("nama"));
}
答案 0 :(得分:2)
我认为你的代码是正确的,除了你忘了填充wordList变量! 在getUser()函数返回之前...
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", cursor.getString(0));
map.put("nama", cursor.getString(1));
//Here you forgot wordList.add(map);
} while (cursor.moveToNext());
}