我是第一次使用Android Studio和SQLite进行“实验”。我的应用程序屏幕变成白色,并在打开新活动时冻结,该活动应该显示我的SQL查询值。
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper (Context context) {
super(context,"book.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table books (ID INTEGER NOT NULL PRIMARY KEY, " +
"BOOK_TITLE TEXT NOT NULL, BOOK_CATEGORY TEXT NOT NULL, " +
"BOOK_DESCRIPTION TEXT NOT NULL)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists books");
onCreate(db);
}
public boolean insertData(String book_title_, String book_category_, String book_description_)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cValues = new ContentValues();
cValues.put("BOOK_TITLE", book_title_);
cValues.put("BOOK_CATEGORY", book_category_);
cValues.put("BOOK_DESCRIPTION", book_description_);
long result = db.insert("book", null, cValues);
if (result == -1)
return false;
return true;
}
public Cursor getAllData()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM book", null);
return res;
}
}
我发现问题出在从另一个类调用getAllData()函数。按照我的逻辑,一切都应该正常工作?我虽然问题出在我的QUERY中,但是根据Google的说法,我所做的一切都很好。 有什么建议吗?
答案 0 :(得分:0)
尝试此方法。这是一种非常有效的方法:
public List<Movie> getAllData()
{
List<Movie> movies_list = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM movie_collection", null);
while(res.moveToNext())
{
movies_list.add(new Movie(res.getString(1)+"\n", res.getString(2)+"\n", res.getString(3)+"\n", R.drawable.gladiator));
}
res.close();
return movies_list;
}
以及在viewAll()方法中:
public void viewAll()
{
movies_list = movie_database.getAllData();
// do whatever you want
}