How can I get the distinct values from SQLite - android

I have a problem while getting the distinct values from my table. I created one method which returns the String Array like this:
public String[] getUniversityNames() {
String[] university = new String[0];
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(true, TABLE_QUESTIONS,
new String[] { KEY_UNIVERSITY }, null, null, null, null, null,
null);
int i = 0;
if (cursor.moveToFirst()) {
do {
university[i] = cursor.getString(0); //Error occurs here # Line 119
i++;
} while (cursor.moveToNext());
} else {
Log.w("AQUEST", "No Data Found.");
}
cursor.close();
return university;
}
And gives me the following error in logcat:
E/AndroidRuntime(11100): FATAL EXCEPTION: main
E/AndroidRuntime(11100): java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
E/AndroidRuntime(11100): at com.anisTronic.quest.database.DatabaseHandler.getUniversityNames(DatabaseHandler.java:119)
I have 19 rows in my table.
Please help me out from this. I appreciate your help.

Your bug probably is:
String[] university = new String[0];
...
university is an array with 0 elements.
then:
university[i] = cursor.getString(0); //Error occurs here # Line 119
you try and add an element. You cannot, since university cannot hold an element, hence the exception. You could return some kind of Collection or collect them in a Collection before changing it to an array.

The String Array university is empty as per your initialisation String[] university = new String[0];
Try using ArrayList<String>
http://developer.android.com/reference/java/util/ArrayList.html

Related

Getting date difference in sqlite

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());
}

How to retrieve single sqlite column and store rows into array

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()];

how to resolve ArrayIndexOutOfBoundsException [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I am trying to access all the data from database "listOfFolder" table "folder" and want to store the data in a string array folders[] but i am getting how to resolve ArrayIndexOutOfBoundsException.
try{
mydb = openOrCreateDatabase("listOfFolder", MODE_WORLD_WRITEABLE, null);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
int count = 0;
String folders[] = null;
Cursor folderCursor = mydb.query("folder", null, null, null, null, null, null);
while(folderCursor.moveToNext()) {
folders[count] = folderCursor.getString(folderCursor.getColumnIndex("name"));
count++;
}
ListView list = (ListView)findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(DropboxActivity.this, android.R.layout.simple_list_item_1,folders);
list.setAdapter(adapter);
setContentView(R.layout.listoffolder);
Change
String folders[] = null;
Cursor folderCursor = mydb.query("folder", null, null, null, null, null, null);
while(folderCursor.moveToNext()){
folders[count] = folderCursor.getString(folderCursor.getColumnIndex("name"));
count++;
}
to
Cursor folderCursor = mydb.query("folder", null, null, null, null, null, null);
if (folderCursor.moveToFirst()) {
String folders[] = new String[folderCursor.getCount()];
do {
folders[count] = folderCursor.getString(folderCursor.getColumnIndex("name"));
count++;
} while(folderCursor.moveToNext());
}
Here's your problem:
String folders[] = null;
What did you expect to happen?
This code is a bad idea, because you have no idea how large a set the query will bring back. You have to call new to allocate a large enough array.
I'd prefer a collection like a List if it's available to you. Check this one out, too.
Like this:
ArrayList<datatypehere> namehere=new ArrayList<datatypehere>();
Then you can add elements to the list by:
String example1 = "this is a string";
namehere.add(example1);
Theres quite abit on lists in the JavaDocs and Java Tutorials if you search for them.

Fetch and store a column values from sqlite in android(java) array

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));

Android SQLite rawquery returns only first record

My SQLite query returning only one record, However, the table has multiple rows
cursor=mydb.rawQuery("Select category from items;", null);
I have even tried GROUP BY but still wont work.
I am new to SQLite, would appreciate any help. Thanks.
First of all your string query must not be terminated so instead of passing it as:
"Select category from items;"
you should try passing it as:
"Select category from items"
as mentioned on this page.
Also, are you looping over the cursor? Here is an example of how to get data out of a cursor with a while loop:
ArrayList<String> results = new ArrayList<String>()
while (cursor.moveNext()) {
results.add(cursor.getString(0)); // 0 is the first column
}
First, search:
Cursor cs = myDataBase.rawQuery("Your query", null);
if (cs.moveToFirst()) {
String a = cs.getString(cs.getColumnIndex("your_column_name"));
cs.close();
return a;
}
cs.close();
return "";
Get the information from cursor:
if (cs.moveToFirst()) {
ArrayList<String> results = new ArrayList<String>()
do {
results.add(cs.getString(cs.getColumnIndex("your_column_name")));
} while (cs.moveNext());
}
Without if, I took error in my project. But this worked for me. By the way, your query doesn't look good. If you give some information about your database, we can help much more.
Use this to select all items from the table:
Cursor cursor = db.rawQuery("SELECT * FROM Tablename ,
null);
this can help you
public ArrayList<mydata> getallContents() {
ArrayList<mydata> lst = new ArrayList<mydata>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("select * from " + GAMETABLE, null);
if (c.moveToFirst()) {
do {
lst.add(new mydata(c.getString(1),
c.getString(3),c.getString(4),c.getString(5),c.getString(6)));
} while (c.moveToNext());
}
db.close();
return lst;
}
you don't need raw query method. i think that the android way is better in this case:
db.query(items, category, null, null, null, null, null);
than use the cursor how already is written in the other comment.

Categories

Resources