Im new to android, and i use Sqlite to store an array of type double into a column called "KEY_VALUE"
public long createEntry(Double rates) {
ContentValues cv = new ContentValues();
cv.put(KEY_VALUE, rates);
return ourDatabase.insert(TABLE, null, cv);
}
I put the data into the columns here via another class
for(i=0;i<37;i++){
entry.createEntry((theRSSHandler.rates()[i]));
}
Now i would like to retrieve the column i saved and get each row as an array element, ive seen and tried other similar solutions but they have not worked.
Here is the method i use to try and get the column data But it has failed.
public Double[] getData() {
String[] col = {KEY_VALUE};
Cursor c = ourDatabase.query(TABLE, col, KEY_VALUE , null, null, null, null);
Double[] result = null;
if(c != null){
c.moveToFirst();
}
int iVal = c.getColumnIndex(KEY_VALUE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result[c.getPosition()] = c.getDouble(iVal);
}
return result;
}
you are trying to put values in an array that has not been initialized.
Double[] result = null;
needs to be followed up with something like...
result = new Double[100];
i think you probably want to initialize it with the number of records pointed to by the cursor
result = new Double[c.count()];
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());
}
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'm creating a simple multiple choice trivia game in Android where the user has three choices. The correct answer choice is pulled directly from the DB, and the two other wrong choices are randomly selected using a method. I put the correct and 2 wrong answers in an array and shuffle the array. The game works fine when in the random selection method I'm only grabbing one column from the row. Now I'd like to grab 3 columns from each random row. So then my problem is how to write the code that is "get two random rows with three columns and put the resulting array into an array that can be shuffled". Here's my working code:
DBAdapter:
// ---Grabs 2 RANDOM ---
public String[] getRandomHA() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_HA }, null, null, null, null, null);
if (cursor != null) {
int i = 0;
String colStrings[] = new String[cursor.getCount()];
while (cursor.moveToNext())
{
colStrings[i] = cursor.getString(0);
i++;
//cursor.close();
}
return colStrings;
}
return null;
}
// --- END Grabs 2 RANDOM ---
Main Activity:
// --- Random 2 answers ----
public void getRandom() {
dba.open();
String[] wrong2 = dba.getRandomHA();
dba.close();
}
shuffle an Array:
// --- shuffle array ----
String[] numbArray = { rightAnswer[2], wrong2[0], wrong2[1] };
List<String> aList = new ArrayList<String>();
for (String s : numbArray)
aList.add(s);
Collections.shuffle(aList);
TextView[] tVs = { optionA_TV, optionB_TV, optionC_TV };
for (int i = 0; i < tVs.length; i++) {
tVs[i].setText(aList.get(i));
}
// --- END shuffle array ----
So is this how I'd write the DB Adapter method?
// ---Grabs 2 RANDOM ---
public String[] getRandomHA() {
Cursor cursor = this.db.query(
"hdtable Order BY RANDOM() LIMIT 2",
new String[] { KEY_Y, KEY_MD, KEY_HA }, null, null, null, null, null);
if (cursor != null) {
int i = 0;
String colStrings[] = new String[cursor.getCount()];
while (cursor.moveToNext())
{
colStrings[i] = cursor.getString(0);
colStrings[i] = cursor.getString(1);
colStrings[i] = cursor.getString(2);
i++;
//cursor.close();
}
return colStrings;
}
return null;
}
// --- END Grabs 2 RANDOM ---
and if the above method is correct, then how would I write the main activity methods to reflect the nested arrays?
The first thing that comes to my mind is to use an instance of the java.util.Random class to call one of the nextXXX() methods to generate a random number. Use that number to select a row from the database to use as your random wrong answer.
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));