This is my first time using a database and I'm not really sure how this works. I made the database and made a query that returns a cursor and... now what? What is a cursor, really? Can I just use that to navigate through my data or do I have to put it in an ArrayList or ListActivity or what?
You need to iterate the cursor to get your results.
Use cursor.moveToFirst() and/or cursor.moveToNext() (with a while loop). Then you can use the getX() method, like cursor.getInt() or cursor.getString().
For example, ir your are expecting one result from your query:
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex('NAME'));
int age = cursor.getInt(cursor.getColumnIndex('AGE'));
} else {
// oops nothing found!
}
First call cursor.moveToFirst(). Each time you call cursor.moveToNext() it will move to the next row. Make sure when you are done with your cursor you call cursor.deactivate() or you will get errors in your log cat.
Iterate over the returned Cursor instance
public List<Object[]> cursorToTableRows(Cursor cursor) {
List<Object[]> result = new ArrayList<Object[]>(cursor.getCount());
cursor.move(0);
cursor.moveToNext();
while (cursor.isAfterLast() == false) {
Object[] tableRow = new Object[cursor.getColumnCount()];
for(int i=0; i<cursor.getColumnNames().length; i++) {
int columnIndex = cursor.getColumnIndex(cursor.getColumnName(i));
String columnValue = cursor.getString(columnIndex);
tableRow[i] = columnValue;
}
result.add(tableRow);
cursor.moveToNext();
}
cursor.close();
return result;
}
Then create the desired objects.
public List<Vehicle> getVehicles() {
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Cursor cursor = null;
List<Object[]> objects = cursorToTableRows(cursor);
for(Object[] row : objects) {
int i=0;
Vehicle vehicle = new Vehicle(row[i++].toString(), row[i++].toString()));
vehicles.add(vehicle)
}
return vehicles;
}
from Developer.android: This interface provides random read-write access to the result set returned by a database query.
In other words: query returns you a set of data represented by a cursor. First you need to make sure you got a valid cursor (not null) and then try to move it to desired position in the data set (use moveToXXX methods). In order to obtain data pointed by cursor use getXXX methods. When done using it make sure to call close to release resources.
According to this link it looks like you can iterate through the query return using something like:
cursor.next();
And grab the data at the location you are looking for using:
cursor.getString(0)
After you successfully have your Cursor setup, you would typically want to display that to a view in some form.
Have a look at the following answer for a detailed, but simple example of using a Cursor Adapter to pair up your newly-minted Cursor with your desired XML View:
https://stackoverflow.com/a/20532937/293280
Related
Buckle up folks, this is a weird one. I'm currently working on an android app that involves storing and retrieving data in an sqlite database. I was going through the app and testing some of the basic features to make sure everything worked, and lo and behold I found a bug in retrieving data from my database. When a user inputs their very first entry to the app, everything works as expected, the values get processed and stored. However, when I go back and attempt to access that data using SELECT * FROM history; I get a cursor that returns true when I call data.moveToNext(), yet when I loop through it using while(data.moveToNext()) { //get values and add to a List<> } the while loop never gets executed.
I've looked at the contents of the database after moving the file to my computer and opening the database using this db browser and I can see my entry.
Here's the method that I call to get all the points from my database:
List<PointValue> getAllPoints() {
List<PointValue> points;
Cursor data = rawQuery("SELECT * FROM history");
if (data.moveToNext()) {
points = new ArrayList<>();
while (data.moveToNext()) {
System.out.println("Looped");
long timestamp = data.getLong(data.getColumnIndexOrThrow("timestamp"));
int level = data.getInt(data.getColumnIndexOrThrow("level"));
points.add(new PointValue(timestamp, level));
}
} else {
return null;
}
data.close();
if (points.size() == 0) {
return null;
}
return points;
}
The rawQuery method looks like this:
private Cursor rawQuery(String sql) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(sql, null);
}
When I tried debugging this on my own, the size of points is 0 even though I know that there's at least one point in the database. Thoughts? The class containing all of my sql related stuff extends SQLiteOpenHelper
EDIT:
Here's the solution suggested by #Isaac Payne (still doesn't work):
public List<PointValue> getAllPoints() {
List<PointValue> points = new ArrayList<>();
Cursor data = rawQuery("SELECT * FROM history");
while (data.moveToNext()) {
long timestamp = data.getLong(data.getColumnIndexOrThrow("timestamp"));
int level = data.getInt(data.getColumnIndexOrThrow("level"));
points.add(new PointValue(timestamp, level));
}
data.close();
if (points.size() == 0) {
return null;
}
return points;
}
The issue is that when you call data.moveToNext() in the if statement you are moving to the first entry, then you call moveToNext() again in your while loop moving to the second non-existent entry. Try removing the if statement
Add data.moveToFirst() before if loop.
Cursor data = rawQuery("SELECT * FROM history");
//add this line
data.moveToFirst();
if (data.moveToNext()) {
I have an app that inserts data into a database with 2 tables (project and alvara)
The insertion method for the second table depends on what type the first table gets. (1 or 2) for resumed idea.
This is a method that I made for looking into the second table with cursor. If it finds, it sets in setters from alvara_db class. And later on, I use getters to show info on textviews in another activity. The issue is that it's not setting info at all. Is anything wrong in my Cursor?
Thanks in advance!
public ArrayList<alvara_db> getAlvaras(){
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<alvara_db> projects = new ArrayList<>();
String[] project = new String[]{String.valueOf(tipoprojetoid)};
Cursor cur = db.rawQuery("SELECT placa, proj_exec, resp_tec, rtnum, parecer FROM alvara WHERE projetoid = ?", project);
cur.moveToFirst();
alvara_db alvaras = new alvara_db();
alvaras.setPlaca(cur.getInt(cur.getColumnIndex("placa")));
alvaras.setProj_exec(cur.getInt(cur.getColumnIndex("proj_exec")));
alvaras.setResp_tec(cur.getString(cur.getColumnIndex("resp_tec")));
alvaras.setRtnum(cur.getInt(cur.getColumnIndex("rtnum")));
alvaras.setParecer(cur.getString(cur.getColumnIndex("parecer")));
projects.add(alvaras);
return projects;
}
Fragment where I call getAlvaras method:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalhes_projeto_alvara);
db.getAlvaras();
placa = alvaras.getPlaca();
resp_tec = alvaras.getResp_tec();
proj_exec = alvaras.getProj_exec();
rtnum = alvaras.getRtnum();
}
You are not using the returned value from db.getAlvaras().
Instead the alvaras variable in your second snippet is something that is likely not initialized - the code you posted does not show that exactly.
(In addition, you might want to check the return value of moveToFirst() in case the query matches no rows, and add a do-while loop to retrieve more than one row.)
Hello I am pretty new with SQLite and I am trying to deal with some database manipulation in my project.
I have a table with almost 4000 rows and this is the format of every row:
problem_id (string)
problem_no (string)
problem_title (string)
dacu (int)
I need to query a bunch of problem_no based on the problem_id. The quantity of query is almost 1000 at a time. So I wrote a query code like this:
Set<Integer> getProblemsTitle(HashSet<String> problemsIDs) {
SQLiteDatabase db = this.getReadableDatabase();
HashSet<Integer> problemNo = new HashSet<Integer>();
Cursor cursor = null;
for (Iterator<String> iterator = problemsIDs.iterator(); iterator.hasNext();) {
cursor = db.query(CommonUtils.PROBLEM_TABLE, new String[] {
CommonUtils.KEY_PROBLEM_NO },
CommonUtils.KEY_PROBLEM_ID + "=?",
new String[] { iterator.next() }, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
problemNo.add(cursor.getInt(0));
}
cursor.close();
}
db.close();
Set<Integer> set = new TreeSet<Integer>(problemNo);
return set;
}
I know this is not a optimized snippet. And I need to optimize it a lot to reduce the execution time of the query. I did it inside AsyncTask but it is taking too much time.
How can I do this efficiently with faster performance?
You might want to consider taking this out of the database. If you just grabbed all the problems, you could add them all in code. Running one SELECT with 4000 results is still going to be much faster than a thousand SELECT statements.
The approach would be to grab them all, but sorted(ORDER BY problem_id). You could then just check each item in problemIDs against it, and add when you get a match.
You could also use the IN operator as Mathew suggests, but I don't know how efficient that will be with 1000 items in the set.
Don't iterate over a collection of IDs, but use the IN operator in a WHERE condition.
SELECT * FROM Table WHERE problem_id IN (1,2,3,4,5)
This will return all the records in the set. Whereas you are querying them one at a time.
You could try compiling a query, and maybe you can try to load the database into memory before reading.
Create an index on the problem_id column.
I m working on an e-learning type of an application where i retrieve the data from the database on list.
It works fine on the emulator,but when i use the APK file of that app on real device,it does not show any data on list, my database is stored in the windows-file explorer-package-data-database-table_name.
I am referring to this site
http://anujarosha.wordpress.com/2011/12/19/how-to-retrieve-data-from-a-sqlite-database-in-android/
Here's a snippet of my code using database
list_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, namelist1());
list1.setAdapter(list_adapter);
}
public List<String> namelist1()
{
// We have to return a List which contains only String values. Lets create a List first
List<String> namelist= new ArrayList<String>();
// First we need to make contact with the database we have created using the DbHelper class
Database_helper_class open_database_helper= new Database_helper_class(this);
// Then we need to get a readable database
SQLiteDatabase sqlitedatabase = open_database_helper.getReadableDatabase();
// We need a a guy to read the database query. Cursor interface will do it for us
//(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor cursor =sqlitedatabase.query(open_database_helper.TABLE_E_LEARNING,null,null,null,null,null,null);
//above query is read all the database column
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
while(cursor.moveToNext()){
String str_name = cursor.getString(cursor.getColumnIndex(Database_helper_class.QUES_COLUMN));
String str_id = cursor.getString(cursor.getColumnIndex(Database_helper_class.ANS_COLUMN));
//double str_gpa = cursor.getDouble(cursor.getColumnIndex(Database_helper_class.GPA_COLUMN));
// Finish reading one raw, now we have to pass them to the POJO
nameclass nameclassobj1=new nameclass();
nameclassobj1.setname(str_name);
nameclassobj1.setid(str_id);
//nameclassobj1.setgpa(str_gpa);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojo_namelist.add(nameclassobj1);
// But we need a List of String to display in the ListView also.
//That is why we create "nameList"
namelist.add(str_name);
}
sqlitedatabase.close();
sqlitedatabase.query() returns a cursor which is positioned before the first record. make sure to call moveToFirst() before trying to access any data from it.
verify your database path in DBHelper.class. And after that Write below line before you call while loop.
cursor.moveToFirst();
This will point to your first record and then your while loop will work.
Try it like this:
// Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String str_name = cursor.getString(cursor.getColumnIndex(Database_helper_class.QUES_COLUMN));
String str_id = cursor.getString(cursor.getColumnIndex(Database_helper_class.ANS_COLUMN));
//double str_gpa = cursor.getDouble(cursor.getColumnIndex(Database_helper_class.GPA_COLUMN));
// Finish reading one raw, now we have to pass them to the POJO
nameclass nameclassobj1=new nameclass();
nameclassobj1.setname(str_name);
nameclassobj1.setid(str_id);
//nameclassobj1.setgpa(str_gpa);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
pojo_namelist.add(nameclassobj1);
// But we need a List of String to display in the ListView also.
//That is why we create "nameList"
namelist.add(str_name);
}
Use the isAfterLast()-method to check, if your reached the end of your cursor.
Sorry for late reply, got busy in other application
Actually the data was not saved in the database, that is why i was not getting it on device.
It works now.
I'm using Sqlite in Android and to get a value from the database I use something like this:
Cursor cursor = sqliteDatabase.rawQuery("select title,category from table", null);
int columnIndexTitle = cursor.getColumnIndex("title");
iny columnIndexCategory = cursor.getColumnIndex("category");
cursor.moveToFirst();
while (cursor.moveToNext()) {
String title = cursor.getString(columnIndexTitle);
String category = cursor.getString(columnIndexCategory);
}
cursor.close();
I want to create my own Cursor so that I can do getColumnIndex() and getString() with one method. Something like this:
String title = cursor.getString("title");
I want to create my own class that extends the cursor that I get from sqliteDatabase.rawQuery, but I'm not sure how to accomplish this. Should I extend SQLiteCursor or how should I do this? Is it even a possible and is it a good idea?
I came across this question looking for the best way to create a custom Cursor to use together with a SQLiteDatabase. In my case I needed an extra attribute to the Cursor to carry an additional piece of information, so my use case is not exactly as in the body of the question. Posting my findings in hope it will be helpful.
The tricky part for me was that the SQLiteDatabase query methods returns a Cursor, and I needed to pass on a custom subclass to Cursor.
I found the solution in the Android API: Use the CursorWrapper class. It seems to be designed exactly for this.
The class:
public class MyCustomCursor extends CursorWrapper {
public MyCustomCursor(Cursor cursor) {
super(cursor);
}
private int myAddedAttribute;
public int getMyAddedAttribute() {
return myAddedAttribute;
}
public void setMyAddedAttribute(int myAddedAttribute) {
this.myAddedAttribute = myAddedAttribute;
}
}
Usage:
public MyCustomCursor getCursor(...) {
SQLiteDatabase DB = ...;
Cursor rawCursor = DB.query(...);
MyCustomCursor myCursor = new MyCustomCursor(rawCursor);
myCursor.setMyAddedAttribute(...);
return myCursor;
}
Creating your own getString will cause a map lookup for each call instead of only for getColumnIndex.
Here's the code for SQLiteCursor.getColumnIndex and AbstractCursor.getColumnIndex. If you have many rows, reducing calls to this function will prevent unnecessary string processing and map lookups.
I wouldn't extend it, I'd make a helper:
class MartinCursor {
private Cursor cursor;
MartinCursor(Cursor cursor) {
this.cursor = cursor;
}
String getString(String column) {
....
}
}
or
class MartinCursorHelper {
static String getString(Cursor cursor, String column) {
....
}
}
Personally, I'd do the latter, unless you hate providing this extra argument all the time.
EDIT: I forgot to mention pydave's important point: If you call this in a loop, you're setting yourself up for a noticeable performance impact. The preferred way is to lookup the index once, cache it, and use that instead.
You should make use of the DatabaseUtils.stringForQuery() static method that is already in Android SDK to easily retrieve a value, this example is for String bot there is also method for Long
stringForQuery(SQLiteDatabase db, String query, String[] selectionArgs)
Utility method to run the query on the db and return the value in the first column of the first row.
Something like
String myString=DatabaseUtils.stringForQuery(getDB(),query,selectionArgs);
Came across this looking for a different solution, but just want to add this since I believe the answers are unsatisfactory.
You can easily create your own cursor class. In order to allow functions requiring Cursor to accept it, it must extend AbstractCursor. To overcome the issue of system not using your class, you simply make your class a wrapper.
There is a really good example here.
https://android.googlesource.com/platform/packages/apps/Contacts/+/8df53636fe956713cc3c13d9051aeb1982074286/src/com/android/contacts/calllog/ExtendedCursor.java
public class ExtendedCursor extends AbstractCursor {
/** The cursor to wrap. */
private final Cursor mCursor;
/** The name of the additional column. */
private final String mColumnName;
/** The value to be assigned to the additional column. */
private final Object mValue;
/**
* Creates a new cursor which extends the given cursor by adding a column with a constant value.
*
* #param cursor the cursor to extend
* #param columnName the name of the additional column
* #param value the value to be assigned to the additional column
*/
public ExtendedCursor(Cursor cursor, String columnName, Object value) {
mCursor = cursor;
mColumnName = columnName;
mValue = value;
}
#Override
public int getCount() {
return mCursor.getCount();
}
#Override
public String[] getColumnNames() {
String[] columnNames = mCursor.getColumnNames();
int length = columnNames.length;
String[] extendedColumnNames = new String[length + 1];
System.arraycopy(columnNames, 0, extendedColumnNames, 0, length);
extendedColumnNames[length] = mColumnName;
return extendedColumnNames;
}
That's the general idea of how it will work.
Now to the meat of the problem. To prevent the performance hit, create a hash to hold the column indices. This will serve as a cache. When getString is called, check the hash for the column index. If it does not exist, then fetch it with getColumnIndex and cache it.
I'm sorry I can't add any code currently, but I'm on mobile so I'll try to add some later.