SQLite select query to string - android

I'm not able to add read data from the following SQLite select query function. I have a table with 3 columns, namely driverID, driversName, driversNo.
It's supposed to return a simple string but alas.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
if (cursor != null){
cursor.moveToFirst();
Log.v("TEST", Integer.toString(cursor.getCount()));
Log.v("TEST", cursor.getColumnName(0));
Log.v("TEST", cursor.getColumnName(1));
Log.v("TEST", cursor.getString(0));
Log.v("TEST", cursor.getString(1));
}
String returnString = cursor.getString(0) + cursor.getString(1);
return returnString;
}
Below are the most recent results from LogCat. The last two logs don't show, for some strange reason.
08-04 20:27:35.271: V/TEST(25126): 1
08-04 20:27:35.271: V/TEST(25126): driversName
08-04 20:27:35.271: V/TEST(25126): driversNo
Any help will be greatly appreciated.
The rest of the code is based on this tut http://www.vogella.com/tutorials/AndroidSQLite/article.html

It would be easier if you provided your table structure, but in any case, some info that might help:
Cursor starts from position -1 when not null.
A good way to read the cursor would be
while (cursor.moveToNext()) {
...
}
Also,
String returnString = cursor.getString(1) + cursor.getString(2);
The above code will concatenate column index 1 and column index 2 (please note that indexes start from 0), from first row returned from your query.
Edit:
Then something as the following should work fine.
public String readDrivers() {
Cursor cursor = database.query(MySQLiteHelper.PROFILE_TABLE_NAME, necessaryColumns, null, null, null, null, null);
List<String> list = new ArrayList<String>;
while (cursor.moveToNext()) {
list.add(cursor.getString(1) + cursor.getString(2));
}
return list;
}

Related

How to get last record from table SQLite

I have problem with receiving last data from table in Android SQLite.
Adding values works great but I struggle with receiving last date from table, here is code:
int getKoniec() {
SQLiteDatabase db = this.getReadableDatabase();
String sortOrder = TABELA_koniec + " DESC LIMIT 1";
Cursor cursor = db.query(
TABELA,
new String[] { "koniec" },
null,
null,
null,
null,
sortOrder
);
if(cursor != null) {
cursor.moveToFirst();
}
int koniecINT = cursor.getInt(0);
Log.v("VALUE: ","" + koniecINT);
cursor.close();
return koniecINT;
}
While adding values 10,9,8,7.. output (return koniecINT) is always 10.
Can you help me to solve this problem? Thanks
Try this query
select * from table_name order by row_id desc limit 1
or
mCursor.moveToLast();

Skip deleted/empty rows sqlite

I am populating AChartEngine from sqlite database and I need all of the data to be displayed. The problem I'm having is when I delete a record the graph series stops populating at the deleted record. I need to find a way to skip over deleted/empty records and continue populating my graph. I need it to do it the same way listview skips over deleted records and keeps on displaying all rows. I am very new to a lot of this and am having a very difficult time with this. I have tried to write if statements in order to skip deleted/empty rows but nothing seems to work. Thank you for helping!
in my graphing activity:
for (int i = 1; !c.isAfterLast(); i++) {
String value1 = db.getValue1(i);
String value2 = db.getValue2(i);
c.moveToNext();
double x7 = Double.parseDouble(value1);
double y7 = Double.parseDouble(value2);
myseries.add(x7, y7);
}
I am getting error: CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
If I surround with try and catch it will populate rows up until the deleted record.
"EDIT"
in my sqlite database:
public String getValue1(long l) {
String[] columns = new String[]{ EMP_DEPT };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value1 = c.getString(0);
return value1;
}
return null;
}
public String getValue2(long l) {
String[] columns = new String[]{ EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String value2 = c.getString(0);
return value2;
}
return null;
}
Your issue is that your safety net for commands on rows that don't exist is to use if (c != null){ and then perform your commands inside that block, but a Cursor request from a query will never come up null, it will instead result in a cursor object with no rows.
A more appropriate solution to use this as your safety net instead if (c.moveToFirst()){ Because the method itself returns a boolean for if the method actually carried itself out in the first place - true if it moved and false if not (which occurs when there's no rows to move into). another check, if you wish, would be to see how many rows the cursor has with c.getCount().
Additionally, you should combine your methods so that you don't make redundant queries to the database:
public String[] getValues(long l) {
String[] results = new String[2];
String[] columns = new String[]{ EMP_DEPT, EMP_DATE1 };
Cursor c = db.query(EMP_TABLE, columns, EMP_ID + "=" + l, null, null, null, null);
if (c.moveToFirst()) {
results[0] = c.getString(0);
results[1] = c.getString(1);
} else {
Log.d("GET_VALUES", "No results formed from this query!");
}
return results;
}
You should use a single query to get all values at once:
SELECT Date1 FROM MyTable WHERE id BETWEEN 1 AND 12345
or:
db.query(EMP_TABLE, columns, EMP_ID + " BETWEEN 1 AND " + ..., ...);
Then missing values will just not show up when you iterate over the cursor.

Android: Sqlite - Moving Values From One Table To Another

I am trying to search for information in one table (DATABASE_FAV_EQUIP_TABLE) based on a value, pull that information, and then place it into another table (DATABASE_EQUIP_TABLE) - checking first if it is not already there. My code is below. Nothing is crashing, and I am not getting any errors, however no information gets placed into the second table (DATABASE_EQUIP_TABLE). I have gone over it several times and cannot figure out why this isn't working.
//takes all equip data from saved equip set, and puts into equip table
public String AddSavedEquipToEquipTable(String name) {
String[] columns = new String[]{KEY_EQUIP};
Cursor c = ourDatabase.query(DATABASE_FAV_EQUIP_TABLE, columns, KEY_FAVNAME + "='" + name + "'", null, null, null, null);
if (c == null){
return null;
}
else if(c != null && c.moveToFirst()) {
do {
int iEquip = c.getColumnIndex(KEY_EQUIP);
String equip = c.getString(iEquip);
CheckEquipTable(equip);
c.moveToNext();
} while (KEY_FAVNAME == name);
}
return null;
}
public void CheckEquipTable(String equip){
String[] columns = new String[]{KEY_EQUIP};
ContentValues cv = new ContentValues();
Cursor check = ourDatabase.query(DATABASE_EQUIP_TABLE, columns, KEY_EQUIP + "='" + equip + "'", null, null, null, null);
if(check == null){
cv.put(KEY_EQUIP, equip);
ourDatabase.insert(DATABASE_EQUIP_TABLE, null, cv);
}
}
Try this:
public void AddSavedEquipToEquipTable(String name) {
String[] columns = new String[]{KEY_EQUIP};
Cursor c = ourDatabase.query(DATABASE_FAV_EQUIP_TABLE, columns, KEY_FAVNAME + "='" + name + "'", null, null, null, null);
int iEquip = c.getColumnIndex(KEY_EQUIP);
while(c.moveToNext())
CheckEquipTable(c.getString(iEquip));
}
I'll explain a few changes:
The column index of KEY_EQUIP will not change so we only need to retrieve the index once
In Java you must compare Strings with if(name.equals(KEY_FAVNAME)) not ==, (KEY_FAVNAME == name) is probably false.
ourDatabase.query() will never return null, the smallest result will be an empty Cursor (as in cursor.getCount() == 0)
cursor.moveToNext() returns true / false, and when the index is at -1 moveToNext() is the same as moveToFirst(). Also if the Cursor is empty then moveToNext() returns false.
Don't hesitate with any other questions with my suggestion. Hope that helps!
Addition
I didn't notice CheckEquipTable() was checking if a Cursor is null the first time:
if(check == null){
Change it like so:
if(check.getCount() == 0){
Um, you should be able to do this solely in sqlite. I can help more if I had the table names / columns, but you would basically do a query like this.
INSERT INTO SomeTable(C, D)
SELECT A, B
FROM OtherTable
WHERE NOT EXISTS (
SELECT 1
FROM SomeTable
WHERE A = C AND B = D
)

Check if cursor has results

I am using a database to store date and want a single column returned based on which id is given in the where claus.
public String getPmax(String serial) {
String[] columns = new String[]{KEY_SERIAL, KEY_PMAX};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "serial = " + serial,
null, null, null, null);
String result = "nothing found";
if(c != null) {
int iPmax = c.getColumnIndex(KEY_PMAX);
c.moveToFirst();
result = c.getString(iPmax);
}
return result;
}
This code works if I use a serial that is in the database but it gives me a force close when i am using a serial that's not in the database!
it says:
04-11 16:31:19.423: E/AndroidRuntime(21226): java.lang.RuntimeException: Unable to start activity ComponentInfo{nl.janjanus.solardetect/nl.janjanus.solardetect.DatabaseView}: android.database.sqlite.SQLiteException: no such column: g: , while compiling: SELECT serial, pmax FROM SolareCel WHERE serial = g
So my question is: How do I check if there is result? or do I need to check if the serial given is a serial that is in the database?
if (!(mCursor.moveToFirst()) || mCursor.getCount() ==0){
//cursor is empty
}
If you look closely, the error is that the SQL is faulty.
It reads the g as a column. You have to encase it in apostrophes like so 'g'.
In your case, the line where you get the cursor should be:
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, "serial = '" + serial + "'",
null, null, null, null);
As to checking whether the cursor has no results, look at Samir Mangroliya's answer.
You can check if the Cursor has elements:
boolean isEmpty = cursor.getCount() < 1;
AFAIK, the Cursor never returns null when there is no row which the requested conditions, just return a empty Cursor.
int x = cursor.getCount(); //this will return number of records in current cursor
if ( x == 0 ) {
// there are no records
} else {
// do your stuff
}

Android- Getting a single value from a database table using cursor

I'm using cursors to retrieve data from a database. I know how to retrieve entire columns to use on listviews and such, but I'm struggling to find a way to retrieve a single value.
Let's say I have a table with two columns ("_id" and "Name") and I have ten records (rows) in that table. How would I get, for example, the Name in the third row? Considering I defined a cursor that reads that table:
public Cursor getMyNameInfo() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String sqlTables = "MyNames";
qb.setTables(sqlTables);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToFirst();
return c;
}
Instead of c.moveToFirst() use c.moveToPosition(2) (Cursor indexes are zero-based hence '2' is the third record).
Remember to check that the Cursor has valid data first though.
EDIT:
Once you've moved the cursor to the 3rd record as I explain above, use the following to just get the value of the "Name" column.
String theName = c.getString(getColumnIndex("Name"));
Cursor cursor = dbHelper.getdata();
System.out.println("colo" + cursor.getColumnCount() + ""
+ cursor.getCount());
cursor.moveToFirst();
if (cursor != null) {
while (cursor.isAfterLast() == false) {
String chktitle = title.trim().toString();
String str = cursor.getString(cursor.getColumnIndex("title"));
System.out.println("title :: "
+ cursor.getString(cursor.getColumnIndex("title")));
System.out.println("date :: "
+ cursor.getString(cursor.getColumnIndex("date")));
System.out.println("desc :: "
+ cursor.getString(cursor.getColumnIndex("desc")));
if (chktitle.equals(str) == true) {
tvAddfavorite.setText("Remove Favorite");
break;
}
cursor.moveToNext();
}
}
cursor.close();
Add a WHERE clause:
qb.appendWhere("_id = 2");
Thanks to the answers above I created the following method to give the value of an item from another column but in the same row.
public String getValueFromColumn(int position, String tableName, String columnToGetValueFrom) {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(tableName);
Cursor c = qb.query(db, null, null, null,
null, null, null);
c.moveToPosition(position);
String neededValue = c.getString(c.getColumnIndex(columnToGetValueFrom));
return neededValue;
}
Hope it helps anyone.

Categories

Resources