我是Android新手。
我在代码中使用了2个数组列表al
和oh
。
我假设循环条件为k+2 < al.size()
,但我仍然遇到异常&#34;索引0大小为0&#34;。我该如何解决这个问题?
公共类延迟扩展了活动{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.delay);
//final EditText text;
Button btnReadSDFile;
//String line="" ;
//String file_name;
btnReadSDFile = (Button) findViewById(R.id.button12);
//text = (EditText) findViewById(R.id.text);
//text.setHint("Enter some lines of data here...");
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File dir = Environment.getExternalStorageDirectory();
File file = new File(dir, "/Notes/delay.csv");
FileInputStream fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
FileWriter outFile = new FileWriter("/sdcard/Notes/duration.csv");
BufferedWriter outStream = new BufferedWriter(outFile);
String aDataRow = "";
StringTokenizer st = null;
String start=null;
String end=null;
String sm_time,sn_time,em_time,en_time;
long dm_time1,sn_time1,em_time1,en_time1;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> oh = new ArrayList<String>();
while ((aDataRow = myReader.readLine()) != null) {
st = new StringTokenizer(aDataRow, ",");
while (st.hasMoreTokens()) {
al.add(st.nextToken());
}//while
}
int i=0;
do{
start=al.get(i);
end=al.get(i+3);
if(start.equals(end))
{
sm_time=al.get(i+1);
em_time=al.get(i+4);
dm_time1=Long.parseLong(em_time)-Long.parseLong(sm_time);
oh.add(start);
oh.add(String.valueOf(dm_time1));
sn_time=al.get(i+2);
en_time=al.get(i+5);
sn_time1=Long.parseLong(en_time)-Long.parseLong(sn_time);
oh.add(String.valueOf(sn_time1));
i+=2;
}
else{
dm_time1=1;
oh.add(start);
oh.add(String.valueOf(dm_time1));
sn_time1=1;
oh.add(String.valueOf(sn_time1));
i++;
}
}while((i+5)<al.size());
outStream.write("AppName");
outStream.write(",");
outStream.write("duration(ms)");
outStream.write(",");
outStream.write("duration(ns)");
outStream.write("\n");
for (int k = 0; (k+2)< oh.size(); k++)
{
outStream.write(oh.get(k));
outStream.write(",");
outStream.write(oh.get(k+1));
outStream.write(",");
outStream.write(oh.get(k+2));
outStream.write("\n");
}
outStream.close();
// System.out.println("Data saved.");
}//try
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 0 :(得分:1)
if(al.size()>0){
//loop here
}else{
//do something
}