I am creating a database and I need to read all records from the database, but my program keeps crashing at this statement:
newWord= db.getAllRecords();
I assume there is an issue with getAllRecords(), as Eclipse indicates no errors.
public Cursor getAllRecords() {
db = dBHelper.getWritableDatabase();//obtains the writable database
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID,KEY_WORD}, null, null, null, null, null);//the query used to obtain all records form the table
}
Any ideas?
First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.
We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.
Here is what I do to get all contents from a table..
public ArrayList<MyObject> getAllElements() {
ArrayList<MyObject> list = new ArrayList<MyObject>();
// Select All Query
String selectQuery = "SELECT * FROM " + MY_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
try {
Cursor cursor = db.rawQuery(selectQuery, null);
try {
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
MyObject obj = new MyObject();
//only one column
obj.setId(cursor.getString(0));
//you could add additional columns here..
list.add(obj);
} while (cursor.moveToNext());
}
} finally {
try { cursor.close(); } catch (Exception ignore) {}
}
} finally {
try { db.close(); } catch (Exception ignore) {}
}
return list;
}
public void printTableData(String table_name){
SQLiteDatabase db = getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM " + table_name, null);
if(cur.getCount() != 0){
cur.moveToFirst();
do{
String row_values = "";
for(int i = 0 ; i < cur.getColumnCount(); i++){
row_values = row_values + " || " + cur.getString(i);
}
Log.d("LOG_TAG_HERE", row_values);
}while (cur.moveToNext());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With