Skip deleted/empty rows sqlite - android

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.

Related

Displaying data on Android after retrieving data form Android Sq lite

I am retrieving data according to dates but when running my app its shows nothing.
Here's my code :
SQL QUERY :
private Cursor getAllCurrentData()
{
String[] selectArg = new String[]{};
return db.query(Db_Contract.Db_Fieds.TABLE_NAME,
null ,
Db_Contract.Db_Fieds.DATE+ "= 2018-11-10",
selectArg,
null,
null,
Db_Contract.Db_Fieds.TIMESTAMP);
}
Displaying Data :
private void totalMoney()
{
Cursor cursor = getAllCurrentData();
double sum = 0.000d;
double getMoney;
while (cursor.moveToNext()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
}
total.setText("Total money spent: " +sum);
}
I am new to Android Programming. Where I am doing wrong ?. Please correct me
First make sure you are connected to database and cursor returned by db.query() is not empty/null. Then Iterate over cursor like
private void totalMoney()
{
openDatabase();
Cursor cursor = getAllCurrentData();
cursor.moveToFirst();
double getMoney = 0;
while (!cursor.isAfterLast()) {
getMoney = cursor.getDouble(cursor.getColumnIndex(Db_Contract.Db_Fieds.MONEY));
sum += getMoney;
cursor.moveToNext();
}
total.setText("Total money spent: " + sum );
closeDatabase();
}

Cursor not working in Android sqlite

My android app has 2 tables Projects and Tasks.
Each Project can have multiple Tasks.
Like below
Now I want to sum up all proportion values of the single task table
I did it.. but the issue is its adding proportion values from all task tables !
The cursor I coded is as follows
public int sumproportion(long projectId){
int value = 0;
int p = 0;
Cursor cu = mDatabase.rawQuery("SELECT * FROM " + DBHelper.TABLE_TASKS, null);
ArrayList temp = new ArrayList();
if (cur != null) {
if (cur.moveToFirst()) {
do {
temp.add(cur.getString(cur.getColumnIndex("proportion"))); // "Title" is the field name(column) of the Table
} while (cur.moveToNext());
}
}
Object ia[] = temp.toArray();
for(int i=0; i<ia.length; i++)
{
p = Integer.parseInt((String) ia[i]);
value = value + p;
}
System.out.println("Value is: " + value);
return value;
}
When I added cursor as below
Cursor cur = mDatabase.query(DBHelper.TABLE_TASKS, mAllColumns,
DBHelper.COLUMN_TASK_PROJECT_ID + " ="+String.valueOf(projectId),
null, null, null, null);
It doesn't add anything. Can any one help fix it please?
First of all, you can just use query like this SELECT SUM(proportion) from TABLE_TASK. proportion should have numeric type.
Secondly, verify that your Cursor return any rows. Probably you pass wrong projectId if there no rows.

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
)

Select multiple rows at a table and insert to an array

I have a table called food. I am selecting the "category" of the food item and I want to show it in a List View. This is the code I tried.
Cursor c = db.query(DATABASE_TABLE,
new String[] { "category" }, null, null, null, null, null);
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
if(c.moveToFirst())
{
do
{ ArrayList<String> recipe = new ArrayList<String>();
recipe.add(c.getString(1));
recipe.add(c.getString(2));
recipe.add(c.getString(3));
recipe.add(c.getString(4));
results.add(recipe);
}while(c.moveToNext());
if(c != null && !c.isClosed())
c.close();
}
Try Now,
Cursor c = db.query(DATABASE_TABLE,
new String[] { "category" }, null, null, null, null, null);
ArrayList<String> results = new ArrayList<String>();
if(c.moveToFirst())
{
do
{
results.add(c.getString(0)); // instead of 0 Index of Category column in your case
}while(c.moveToNext());
if(c != null && !c.isClosed())
c.close();
}
From your database query You are selecting only category column so you have only one column result in cursor and its start with 0 index. So c.getString(1) to c.getString(4) is meaning less. If your select all data from table then only you get all columns..
I see your problem, you are only returning one column (category), yet you are trying to access several different ones.
You should be returning at least five (since you are trying to access up to 4 and the cursor columns start at 0).
If you are trying to pull a list of items with a certain category you need to change your query. Somethign like this :
String query = "SELECT * FROM " + DATABASE_TABLE + " WHERE category = " + category;
return mDb.rawQuery(query, null);
That will select all items that have a category matching whatever is contained in the variable category, and return all the coilumns in the row.

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
}

Categories

Resources