I'm trying to read from a SQLite database using the following code:
public List<DBEntry> getAllDBEntrys() {
List<DBEntry> DBEntrys = new ArrayList<DBEntry>();
Cursor cursor = database.query(DatabaseClass.TABLE_APPTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
DBEntry DBEntry = cursorToDBEntry(cursor);
DBEntrys.add(DBEntry);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return DBEntrys;
}
private DBEntry cursorToDBEntry(Cursor cursor) {
DBEntry DBEntry = new DBEntry();
DBEntry.setId(cursor.getLong(0));
DBEntry.setName(cursor.getString(1));
DBEntry.setStartDate(new Date(cursor.getLong(2)));
DBEntry.setDueDate(new Date(cursor.getLong(3)));
DBEntry.SetPriority(cursor.getInt(4));
DBEntry.setDesc(cursor.getString(5));
DBEntry.SetCompletion(cursor.getInt(6)==1?true:false);
return DBEntry;
}
I get this error:
01-23 16:35:23.509: E/CursorWindow(14609): Failed to read row 0, column 6 from a CursorWindow which has 1 rows, 6 columns.
The database already has one entry, as the sqlite3 utility shows:
sqlite> select * from ThingsToDo;
0|asdf|1358847122203|1359192722202|7|abcd|0
sqlite> .schema
CREATE TABLE ThingsToDo( _id integer primary key autoincrement,name text not null,start_date integer,due_date integer,priority integer,description text, completed integer);
CREATE TABLE android_metadata (locale TEXT);
I think the issue is that the _id column is not counted as a column, because the cursor.getColumnCount() function returns 6, not 7 as the sqlite3 utility showed when I moved to file to my PC.
How can I make this work?
public List<DBEntry> getAllDBEntrys()
{
List<DBEntry> DBEntrys = new ArrayList<DBEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_APPTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
DBEntry DBEntry = new DBEntry();
DBEntry .setID(Integer.parseInt(cursor.getString(0)));
DBEntry .setName(cursor.getString(1));
DBEntry .setPhoneNumber(cursor.getString(2));
// Adding to list
DBEntrys .add(DBEntry );
} while (cursor.moveToNext());
}
// return list
return DBEntrys ;
}
Related
I have an Android app with a SQL database that has 4 columns. I would like to search all 4 columns in the database however I can only get 1 to be searched.
I'm not quite sure on how to get it to search all 4 columns.
All 4 Columns are displayed but I can only search one. I can not seem to get it to search all 4 columns.
the code I'm using to get it to search one column is
#SuppressLint("Range")
public List<Data> getDataByVARIETY (String VARIETY) {
variety = VARIETY;
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"VARIETY", "COMMODITY", "PLU", "BOTANICAL"};
String tableName = "data";
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
List<Data> result = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
Data data = new Data();
data.setCOMMODITY(cursor.getString(cursor.getColumnIndex("COMMODITY")));
data.setVARIETY(cursor.getString(cursor.getColumnIndex("VARIETY")));
data.setPLU(cursor.getString(cursor.getColumnIndex("PLU")));
data.setBOTANICAL(cursor.getString(cursor.getColumnIndex("BOTANICAL")));
result.add(data);
} while (cursor.moveToNext());
}
return result;
}
so all i had to do was
change this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
Cursor cursor = qb.query(db, sqlSelect, "VARIETY LIKE ?", new String[]{"%" + VARIETY + "%"}, null, null, null);
to this
qb.setTables(tableName);
//This will query : Select * from Data where Variety %PATTERN%"
String conditions = "COMMODITY LIKE ? OR PLU LIKE ? OR VARIETY LIKE ?";
String par;
par = "%"+COMMODITY+"%";
Cursor cursor = db.query(tableName, sqlSelect, conditions, new String[]{par, par, par}, null, null, null);
I am working on a project and created a database with SQLite. In my database I have just two columns, column names are r_id and m_id. I want to take the first element of the r_id and assign it in to a string. The elements of the r_id column is like 1, 2, 3.. in this situation my String has to be 1.
My code; creating a db query:
There is no problem I can add data correcly.
my_table = "CREATE TABLE "my_table"("r_id" Text, "m_id" Text);";
db.execSQL(my_table );
Code to take the first element of the column;
public String getSetting() {
String result = "";
String[] columns = {"r_id"};
String[] selectionArgs = {"1"};
String LIMIT = String.valueOf(1); // <-- number of results we want/expect
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(true, "r_id", columns, "row", selectionArgs, null, null, null, LIMIT);
if (c.moveToFirst()) {
result = result + c.getString(0);
} else {
result = result + "result not found";
}
c.close();
databaseHelper.close();
return result;
}
The error I am getting:
android.database.sqlite.SQLiteException: no such column: row (code 1 SQLITE_ERROR): , while compiling: SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
The 4th argument of query() is the WHERE clause of the query (without the keyword WHERE) and for it you pass "row".
Also, the 2nd argument is the table's name for which you pass "r_id", but the error message does not contain ...FROM r_id... (although it should), so I guess that the code you posted is not your actual code.
So your query (translated in SQL) is:
SELECT DISTINCT r_id FROM my_table WHERE row LIMIT 1
which is invalid.
But you don't need a WHERE clause if you want just the min value of the column r_id.
You can do it with a query like:
SELECT MIN(r_id) AS r_id FROM my_table
without DISTINCT and a WHERE clause.
Or:
SELECT r_id FROM my_table ORDER BY r_id LIMIT 1;
So your java code should be:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT MIN(r_id) AS r_id FROM my_table", null);
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
I used rawQuery() here instead of query().
Or:
public String getSetting() {
SQLiteDatabase db = databaseHelper.getReadableDatabase();
Cursor c = db.query(false, "my_table", new String[] {"r_id"}, null, null, null, null, "r_id", "1");
String result = c.moveToFirst() ? c.getString(0) : "result not found";
c.close();
databaseHelper.close();
return result;
}
Log Cat
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col 5 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:465)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.example.workhours.DataBaseHelper.ViewAllNotes(DataBaseHelper.java:90)
at com.example.workhours.MainActivity.ViewAllNotes(MainActivity.java:55)
at com.example.workhours.MainActivity.onCreate(MainActivity.java:37)
public ArrayList<newNote> ViewAllNotes() {
ArrayList<newNote> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT NOTEMEMOS FROM " + TABLE_NAME, null);
while(cursor.moveToNext()){
String notes = cursor.getString(5);
newNote newNote = new newNote(notes);
arrayList.add(newNote);
}
return arrayList;
}
Query
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, DATE TEXT, TIMESHIFTSTART INTEGER, TIMESHIFTENDS TEXT, NOTES TEXT, NOTEMEMOS TEXT)");
}
Your cursor has one column SELECT NOTEMEMOS but you're trying to read the sixth one with getString(5). Replace that with getString(0) to read the only column value.
Try moving cursor to first before getting any data and you are selecting only on column from database but you are asking for 5th .
public ArrayList<newNote> ViewAllNotes() {
ArrayList<newNote> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT NOTEMEMOS FROM " + TABLE_NAME, null);
cursor.moveToFirst();
newNote newnote = new newNote(cursor.getString(0));
arrayList.add(newnote);
while(cursor.moveToNext()){
String notes = cursor.getString(0);
newNote newnote = new newNote(notes);
arrayList.add(newnote);
}
return arrayList;
}
I have an SQLite Database in my android application with the following structure:
public void onCreate(SQLiteDatabase db) {
String CREATE_LISTS_TABLE = "CREATE TABLE " + TABLE_LISTS +
"("+
_ID + " INTEGER PRIMARY KEY , " +
NOTE + " TEXT" +
")";
db.execSQL(CREATE_LISTS_TABLE);
}
And this works, in that I can insert data into it without a problem. However I need to store the notes inside an array. I currently have the following query:
public List<String> getAllNotes() {
List<String> notes = new ArrayList<>();
String GET_ALL_NOTES = "SELECT * FROM " + TABLE_LISTS;
SQLiteDatabase db = getReadableDatabase();
if(db!=null)
{
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex("notes"))));
cursor.moveToNext();
}
cursor.close();
}
db.close();
return notes;
}
However, this gives the following error:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I was wondering how to fix this, I have read the android developer stuff but I can't seem to get anything to work.
Thanks in advance
Check the value of "NOTE", and use it in:
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex(NOTE))));
I think a best way to make the call should be something like this:
// Check the cursor
if(cursor != null) {
if (cursor.moveToFirst()) {
// Variables to be used
String note;
// Col position
int colNote = cursor.getColumnIndex(NOTE);
do {
// Get the information
note = cursor.getString(colNote);
// Add the note
notes.add(note);
} while (cursor.moveToNext());
}
// Close the cursor
cursor.close();
}
Because you are fetching only integer and string from database, instead of using ArrayList , you can try using HashMap. So you can get the value by just giving the key. Below simple code will work for ArrayList too with minor changes..
Try this
HashMap<Integer,String> notes = new HashMap<Integer,String>() ;
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
while (cursor.moveToNext())
{
int i = cursor.getInt(0);
String s = cursor.getString(1);
notes.put (i,s) ;
}
cursor.close();
Using Android SQL, I'm trying to get a list of the columns from an SQL table which is empty.
Here is what I have tried so far:
SQLiteDatabase db = getReadableDatabase();
ArrayList<String> output = new ArrayList<String>();
Cursor ti = db.rawQuery("PRAGMA table_info("+myTable+")", null);
if ( ti.moveToFirst() ) {
do {
output.add(ti.getString(1));
} while (ti.moveToNext());
}
ti.close();
db.close();
return output;
The resulting list Appears just the word INTEGER, while the database has many columns. How can I make this work?
this is i use to retrieve column name in string:
SQLiteDatabase mDataBase;
(some code here...)
mDataBase = getReadableDatabase();
Cursor dbCursor = mDataBase.query(TABLE_NAME, null, null, null, null, null, null);
String[] columnNames = dbCursor.getColumnNames();
or this :
Cursor c = db.rawQuery("SELECT * FROM table WHERE 0", null);
try {
String[] columnNames = c.columnNames();
} finally {
c.close();
}
The column name is returned in the column named name:
...
int nameColIdx = ti.getColumnIndexOrThrow("name");
...
output.add(ti.getString(nameColIdx));
...