Am I using Cursor properly with SQLite?

Revaljilji :

I'm "experimenting" with Android Studio and SQLite for the first time. My app screen turns white and freezes upon opening new activity which should show up my SQL query values.

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;
}
}

I found out that the problem is in calling getAllData() fuction from another class. By my logic everything should work fine? I though that the problem is in my QUERY but according to google I've done everything good. Any suggestions?

Manzurul Hoque Rumi :

Try this method. It's very efficient method:

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;
}

and in viewAll() method:

public void viewAll()
{
    movies_list = movie_database.getAllData();
    // do whatever you want
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=109280&siteId=1