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.
Related
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 have been struggling for hours trying to use an array inside a while loop. The problem is that im very new to android development so i have no idea how to do this. I have seen similar questions but most/all of them does not suite for my scenario. The code below does work but im calling a new instance of articlesData for each row in the while statement, this causes it to just return the value of the last row.. Is there any way to use an array like ArticlesData[] and get all my data in it? Please help :) Here is my code:
public ArticlesData[] getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
articlesData = new ArticlesData[] {
new ArticlesData(title, Integer.toString(id), url)
};
}
return articlesData;
}
You most probably want to use a Collection such as List:
public List<ArticlesData> getArticleData(int no) {
Log.e("DB STAT", "getArticleData Called");
SQLiteDatabase db = helper.getWritableDatabase();
String[] columns = { ArticlesHelper.ID, ArticlesHelper.TITLE, ArticlesHelper.IMAGEURL };
Cursor cursor = db.query(ArticlesHelper.TABLE_NAME,
columns,
ArticlesHelper.DATENUMBER+" < '"+Integer.toString(no)+"'", null, null, null, ArticlesHelper.DATENUMBER+" DESC", "20");
List<ArticlesData> list = new ArrayList<ArticlesData>();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
Log.e("DB STAT", "Article Id = "+Integer.toString(id));
String title = cursor.getString(1);
Log.e("DB STAT", "Article Title = "+title);
String url = cursor.getString(2);
list.add(new ArticlesData(title, Integer.toString(id), url));
}
return list;
}
You should not try to use a raw array here because it has a fixed size. You could use it if you limited the number of rows in the query so you'd know exactly how much elements you need, but even then it would still be much easier to just use a Collection elsewhere in the code.
As you seem new to Android development and Java I suggest you first get acquainted with the basic data structures such as Maps, Lists, and Sets, and then later you might want to use an ORM to save you the pain of writing boilerplate code for interacting with a database.
I'm developing an application which reads browser history.I tried using managedQuery but I just got to know that it is deprecated.I found the following answer on a similiar question
Cursor cursor = this.context.getContentResolver().query(Browser.SEARCHES_URI, null, null, null, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
final int indexDate = cursor.getColumnIndex(Browser.SearchColumns.DATE);
final int indexTerm = cursor.getColumnIndex(Browser.SearchColumns.SEARCH);
String date = cursor.getString(indexDate);
String term = cursor.getString(indexTerm);
cursor.moveToNext();
}
}
cursor.close();
My doubt is,what is the role of the context variable over here? How do I get the Browser's context in that variable?
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
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));