[英]how to resolve ArrayIndexOutOfBoundsException
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. 我正在尝试访问数据库“ listOfFolder”表“文件夹”中的所有数据,并希望将数据存储在字符串数组文件夹中[],但是我正在获取如何解决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);
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. 您必须调用new
来分配足够大的数组。
I'd prefer a collection like a List if it's available to you. 如果您可以使用清单,我更喜欢一个列表 。 Check this one out, too. 也检查一下这个 。
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());
}
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. 如果您要搜索JavaDocs和Java教程中的列表,则有很多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.