這是我的第一個問題,但我會盡力問好。無論如何,我試圖從Android中的文本文件讀取數據,但由於某些原因,它不會返回任何內容 - 即IndexOutOfBounds異常。所有相關代碼:從Android中的文本文件讀取數據不會返回任何內容?
public Question getNextQuestion(int num) {
Log.d(TAG, array.toString());
return array.get(num+1);
}
public ArrayList<Question> getData(String str) throws NumberFormatException, IOException {
Log.d(TAG, "STARTING getData");
Log.d(TAG, str);
ArrayList<Question> a = new ArrayList<Question>();
String[] strline = str.split("//");
for (int j = 0; j < strline.length; j++) {
if (strline[j] == null) {
strline[j] = "TESTING";
Log.d(TAG, strline[j]);
}
}
int num = 0;
int x = 0;
String y = strline[x];
while (x == 0 || y != null) {
num++;
String[] data = y.split("//");
Log.d(TAG, y);
if (data.length >= 7) {
a.add(new Question(Integer.parseInt(data[0]), data[1], data[2], data[3], data[4], data[5], Integer.parseInt(data[6])));
Log.d(TAG, a.get(a.size()).getText());
}
else if (data.length >= 3) {
a.add(new Question(Integer.parseInt(data[0]), data[1], data[2]));
Log.d(TAG, a.get(a.size()).getText());
}
x++;
if (x < strline.length)
y = strline[x];
else
break;
}
for (int i=0; i<a.size(); i++){
Log.d(TAG, a.get(i).getText());
}
Log.d(TAG, "ENDING getdata");
return a;
}
public ArrayList<Question> openFile() throws IOException {
Log.d(TAG, "STARTING openFile()");
//FileReader fr = new FileReader("data/data/scibowl.prog/questionsb.txt");
FileInputStream fis;
String storedString = "";
try {
fis = openFileInput("questionsb.txt");
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
while ((strLine = dataIO.readLine()) != null) {
storedString = storedString + strLine;
}
dataIO.close();
fis.close();
}
catch (Exception e) {
}
array = getData(storedString);
Log.d(TAG, "DID open file, ending openFile()");
return array;
}
這將打印在logcat中:
onCreate done
STARTING openFile()
STARTING getData
ENDING getdata
DID open file, ending openFile()
right before Toast.makeText
[]
Caused by: java.lang.IndexOutOfBoundsException: Invalid location 1, size is 0
at java.util.ArrayList.get(ArrayList.java:341)
at scibowl.prog.Round.getNextQuestion(Round.java:55)
at scibowl.prog.RoundView.<init>(RoundView.java:26)
at scibowl.prog.Round.onCreate(Round.java:35)
我已經試過幾乎一切從StringBuffers到FileInputStreams到BufferedReaders,並閱讀相關的Android文檔,但隨時告訴我我不夠難讀。有人知道爲什麼我一直在使用沒有元素的數組嗎?
文本文件以供參考,儘管略微編輯與BLOCKQUOTE規則符合:
1 //在標準電磁頻譜,其頻率爲γ射線和紫外線//無線電波之間//微波// X射線//紅外線// 1
2 //電磁頻譜上的哪個波大致包含10^9 Hz到10^12 Hz的頻率?//可見光//伽馬射線//紫外線//微波// 3
3 //大約佔美國po的百分比// 30%// 40%// 50%// 60%// 0
4 //如果一個100公斤的人從靜止開始行走並且加速到4.0米/秒超過2米在不斷加速的情況下,他做了多少工作?// 600 J // 800 J // 1200 J // 2000 J // 1
是的,對不起,我忘了提及來自logcat的空ArrayList來自getdata()。不過,我仍然不知道發生了什麼問題。 – biblioman 2012-02-25 22:08:41
謝謝,對不起,我最終搞清楚了 - 儘管忘記了。 – biblioman 2012-11-06 18:18:40