I want to display the database in a list in Android. I am using cursors for that. I am getting the columncount and using for loop I am moving the cursor. But the database is not displayed. Please help. Here is my code:
List<String> s;
Cursor c = db.query(Geo_Create_Table, new String[] { lat + "", lon + "", result1 }, null, null, null, null, null);
c.moveToFirst();
int count = c.getColumnCount();
for (int i = 0; i < count; i++)
{
c.moveToNext();
}
Please let me know if there is any other simpler approach.
You seem to have lost some of your code there. You should edit your post, I don't have the privilages. The column count will give you the number of columns (fields) in each row and shouldn't be used to loop through the cursor's records if that is what you're trying to do, you should probably use the getCount() method instead.
List<String> s;
Cursor c=db.query(Geo_Create_Table, new String[]{lat+"",lon+"",result1}, null,null, null, null, null);
c.moveToFirst();
int count=c.getCount();
for(int i=0; i < count; i++)
{
....
c.moveToNext();
}
Alternatively, in my code below you query moveToFirst(), if this returns true it means there are records to be traversed. The I use a do/while loop to move through each record (note: c.moveToNext()).
List s;
Cursor c=db.query(Geo_Create_Table, new String[]{lat+"",lon+"",result1}, null,null, null, null, null);
if (c.moveToFirst()) {
do
{
...
c.moveToNext();
}
while (!c.isAfterLast());
}
Related
I tried to read the SQLite database column and store each values in an String array. I did the following but it returned exception cursoroutofbounds. Help me figure out what I'm doing wrong?
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
String[] places = new String[c.getColumnCount()];
c.moveToNext();
for(int i=0; i<c.getColumnCount(); i++)
places[i] = c.getString(i);
return places;
}
Here :
String[] places = new String[c.getColumnCount()];
c.getColumnCount() will return count of column in row instead of number of rows in column. use c.getCount() to initialize places Array:
String[] places = new String[c.getCount()];
Or use ArrayList .
I worked out for sometime and found out the solution:
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
c.moveToFirst();
ArrayList<String> places = new ArrayList<String>();
while(!c.isAfterLast()) {
places.add(c.getString(c.getColumnIndex("place1")));
c.moveToNext();
}
c.close();
return places.toArray(new String[places.size()]);
}
You need to change your query and further processing at multiple places. Rectify your third parameter of query method to a proper where clause or keep it null. Loop through the cursor properly and add it to your String.
public String[] getPlaces(){
SQLiteDatabase db = this.getReadableDatabase();
String [] columns = {"place1"};
c = db.query("rates_table", columns, null, null, null, null, null);
if (c.getCount() > 0) {
String[] places = new String[c.getCount()];
int i=0;
c.moveToFirst();
do {
places[i] = c.getString(c.getColumnIndex(0)));
} while (c.moveToNext());
return places;
}
c.close();
db.close();
}
First you have an issue with c = db.query("rates_table", columns, "place1", null, null, null, null);
The third parameter will result in no rows being selected.
You could use c = db.query("rates_table", columns, null, null, null, null, null); , which would return all rows.
Or you could use c = db.query("rates_table", columns, "place1 = 'myplace'", null, null, null, null);, in which case only rows that have the value myplace in the column place1 would be shown.
The best practice way is to use the 3rd and 4th parameter in conjunction where you use ? placeholders in the 3rd parm (e.g "place1=?") and corresponding args in the 4th parameter (e.g. new String[]{"myplace"}), so to replicate the previous query you could have c = db.query("rates_table", columns, "place1=?", new String[]{"myplace}, null, null, null);
Using c.moveToNext, will try to move to the next (initially the first) row of the cursor. However, if it cannot move (i.e. there are no rows, as would be the case as described above) it will not fail, rather it returns false (true if the cursor could be moved).
So You need to check this otherwise, in the case of no rows, an attempt to access a row will fail with Cursor out of bounds Index 0 requested, with a size of 0 (i.e. you requested the first (index 0) when the size of the cursors (number of rows) is 0.
There are various ways to check.
However I suspect you will then wonder why your loop only displays 1 column. That would be because you have said in the query to just get 1 column.
If you changed the query's 2nd parameter to null, it would get all columns.
At a guess you want to return an array of all places.
Assuming this then :-
// get Cursor with all rows(3rd parm null) for the place1 column (2nd parm)
c = db.query("rates_table", columns, null, null, null, null, null);
// Create String array according to the number of rows returned.
String[] places = new String[c.getCount()];
// loop through all rows setting the respective places element with the
// value obtained from the Cursor
while (c.moveToNext) {
places[c.getPosition()] = csr.getString(csr.getColumnIndex("place1"));
}
csr.close(); // Should always close a Cursor
return places;
I want to get date difference between today and expiring day. This is the code I implemented. But this is not returning the right output.
public String[] getDaysList(){
Cursor cursor = db.query("COUPON", null, null, null, null, null, null );
if(cursor.getCount()<1){
cursor.close();
return null;
}
String[] array = new String[cursor.getCount()];
int i=0;
while(cursor.moveToNext()){
String days = "(julianday('now') - julianday(EXPIRED_DATE))";
array[i] = days;
i++;
}
return array;
}
This returns (julianday('now') - julianday(EXPIRED_DATE)). Please help me to get date difference as string to a array here.
The now modifier returns not only the date but also the time.
To change the timestamp to the start of the date, use the date() function:
SELECT julianday(date('now')) - julianday(EXPIRED_DATE) FROM ...
(If the expired column also contains time values, you have to use date() for it, too.)
And to actually execute this, you have to give it to the database:
public String[] getDaysList() {
String days = "julianday(date('now')) - julianday("+EXPIRED_DATE+")";
Cursor cursor = db.query("COUPON",
new String[]{ days }, // query returns one column
null, null, null, null, null);
try {
String[] array = new String[cursor.getCount()];
int i = 0;
while (cursor.moveToNext()) {
array[i++] = cursor.getString(0); // read this column
}
return array.length > 0 ? array : null;
} finally {
cursor.close();
}
}
(And the number of days is not a string; consider using int[] instead.)
Hi please try these one
Cursor cursor = db.rawQuery("SELECT julianday('now') - julianday(DateCreated) FROM COUPON", null);
if (cursor.moveToFirst()) {
do {
array[i]=cursor.getString(0)
} while (cursor.moveToNext());
}
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.
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 want to store the values of a particular column in the array, As I am a fresher I don't know how to do this. I am getting values from sqlite as
1
2
123
432
3
5
I want to store these values in string array. Please tell me I am not finding any appropriate example by googling about this.. thanx in advance.
public void fun(String query){
Cursor cursor = db.rawQuery(query, null);
try{
String[] arr = new String[cursor.getCount()];
if(cursor != null){
while(cursor.moveToNext()){
for(int i = 0; i < cursor.getCount(); i++){
arr[i] = cursor.getString(0).trim();
}
cursor.moveToNext();
}
cursor.close();
}
}finally{
cursor.close();
}
}
Here query is
SELECT <COLUMN_NAME> FROM <TABLE_NAME> WHERE <CONDITION>;
I think I am doing it wrong please correct my errors...
I consider using rawQuery is a bad habit, try to avoid this(except in extreme cases)
Try as follows to solve your problem, hope this will help you:
public ArrayList<String> getAllStringValues() {
ArrayList<String> yourStringValues = new ArrayList<String>();
Cursor result = db.query(true, YOUR_TABLE,
new String[] { YOUR_COLUMN_NAME }, null, null, null, null,
null, null);
if (result.moveToFirst()) {
do {
yourStringValues.add(result.getString(result
.getColumnIndex(YOUR_COLUMN_NAME)));
} while (result.moveToNext());
} else {
return null;
}
return yourStringValues;
}
Use this method in YourCustomDBManager class. consider NotePad example of android developers sites example programmers guide for getting better concept. It will help you to learn how to deal with SQLite. I am also new in Android, but I learned everything about SQLite from NotePad example.
Vector<String> vecInt = new Vector<String>; // you can use any datatype <int><float>
cursor.moveToFirst();
for(i=0;i<cursor.getCount();i++)
{
vecInt.add(cursor.getString(COLUMN_NUM));// if you are using datatype other then string then need to convert here
}
int [] val = new int[cursor.getCount()]; // integer array
for(int i= 0; i<cursor.getCount(); i++)
val[i] = cursor.getInt(cursor.getColumnIndex(COLUMN_NAME));