我在Android市场上有一个应用程序用户报告偶尔出现的错误ArrayIndexOutofBounds(强制关闭)。我自己从来没有经历过这个错误,所以很难找出问题所在。我希望有一个更有天赋的程序员可以看一看。有些人查看此文件对话框时会发生这种情况。
public void fileDialog() {
// TODO Auto-generated method stub
d = new Dialog(this);
d.setTitle("Choose the song file");
if (canWriteToFlash()) {
ScrollView sview = new ScrollView(this);
LinearLayout holder = new LinearLayout(this);
holder.setOrientation(1);
String path = Environment.getExternalStorageDirectory().getPath()
+ File.separator + "Music" + File.separator;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
int count = 0;
// count files in directory
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
count++;
}
}
if (count == 0) {
TextView empty1 = new TextView(this);
empty1.setText("The folder sdcard/Music, is empty. You must add song files in order to attach music to lyrics.");
empty1.setTextSize(18);
empty1.setPadding(8, 0, 8, 8);
holder.addView(empty1);
}
// turn files into string array
String[] sfiles = new String[count];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
sfiles[i] = listOfFiles[i].getName();
}
}
// Sort Array case insenstive
Arrays.sort(sfiles, String.CASE_INSENSITIVE_ORDER);
// create text
TextView[] t1 = new TextView[(count)];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
t1[i] = new TextView(this);
t1[i].setText(sfiles[i]);
t1[i].setPadding(7, 8, 7, 8);
t1[i].setTextSize(18);
holder.addView(t1[i]);
}
}
// Create Click
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
final TextView thetext = t1[i];
thetext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
songname = (String) thetext.getText();
songfile.setText(songname);
d.cancel();
}
});
}
}
sview.addView(holder);
d.setContentView(sview);
} else {
TextView usbt = new TextView(this);
usbt.setText("Cannot communicate with sdcard! Make sure that USB connected is not enabled. Or try unplugging your USB cord.");
usbt.setPadding(7, 8, 7, 8);
usbt.setTextSize(18);
d.setContentView(usbt);
}
d.show();
}
答案 0 :(得分:0)
我不喜欢这个:
if (listOfFiles[i].isFile()) {
t1[i] = new TextView(this);
t1[i].setText(sfiles[i]);
t1[i].setPadding(7, 8, 7, 8);
t1[i].setTextSize(18);
holder.addView(t1[i]);
}
您假设sFiles [i]与listOfFiles [i]具有相同的位置,但您之前订购过,所以它可能不是同一个文件?
无论如何,除此之外,你一遍又一遍地问同样的问题。 (if(listOfFiles [i] .isFile()){)如果你有完整的堆栈跟踪,请发布它。
答案 1 :(得分:0)
您已将“TextView”声明为最终版。在最终字段中存储对象的引用将使您的引用不可变。它没有造成任何问题吗?