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
)
Related
I am using the following to fetch a string from my table. The cursor is always returning empty even when I have data in database. Is the query wrong?
public void find(String myNumber){
String[] thecolumns = new String[]{
ID,
FLAG};
cursor = sqlDb.query(MY_TABLE,
thecolumns, NUMBER + "='"
+ myNumber+ "'", null, null, null, null);
if (cursorToFetchAssets != null ) {
cursorToFetchAssets.moveToFirst();{
try{
//code to fetch
}catch{
//return when there are no rows found.
}
}
EDIT: NUMBER is of type string "...+ NUMBER + " TEXT,.. " and myNumber is also a string
FIXED: Issue was on the server side of my code. Not over here..
try this:
cursor = sqlDb.query(
MY_TABLE,
thecolumns,
NUMBER + "=?",
new String[]{String.valueOf(number)},
null, null, null);
I got a null value when data is present at the location in sqlite
Cursor c = db.query("SELECT * FROM table WHERE id " = '" + value + "'", null);
if(c !=null && c.moveToFirst())
{
temp = c.getString(c.getColumnIndex(b1));
Log.v(TAG, ""+temp);
}
The log file is
------------
Tag Text
-------------
class null
-------------
The value is present but i get null can it be sorted out.
if cursor is null it obviously should skip the if statement but it executes the statement.
For some other values i get the answer
Tag Text
-----------
class 100
----------
class 86
Thank you for the time and response given
You didn't write the right SQLquery
this is the right query
Cursor c = db.rawQuery("SELECT * FROM "+ table +" WHERE id = " + value , null);
you also can use db.query() method like that
Cursor cursor = db.query(TABLE_NAME, // a. table
COLUMNS, // b. column names as array of strings
KEY_ID + "= ?", // c. selections
new String[] { String.valueOf(id) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null)
cursor.moveToFirst();
temp = cursor.getString(c.getColumnIndex(b1));
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.
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
}
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.