无法从ArrayList获取数据

时间:2015-04-16 19:15:39

标签: java android

我制作了一个代码来从文本文件中获取信息,但它始终无法从数组中获取数据。如果我手动输入一个数字它可以工作,否则它会崩溃。

这里是代码:

 public void reload () {
        File file = new File(((Context)this).getExternalFilesDir(null), "Worktime.txt");


        StringBuilder text = new StringBuilder();



        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
            br.close();
        }
        catch (IOException e) {
            Log.e("tk.spyfly.Worktime", "Unable to read the Worktime.txt file.");
        }


        Scanner s = new Scanner(text.toString());

        list.clear();

        while (s.hasNext()){
            list.add(s.next());
        }
        s.close();
String current;
int worktimetoday=0;

        int i = list.size();
        int count = 0;
        while (count != i){
        count= count +1;
        current = list.get(count);
        current.replace(getString(R.string.workstart) + " ","");
        current.replace(getString(R.string.workstop) + " ","");
        Calendar cs = Calendar.getInstance();
            cs.getTime();
           int year = cs.YEAR;
           int month = cs.MONTH;
            int day = cs.DAY_OF_MONTH;
Date date;
            SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd kk:mm:ss zzz yyyy");

            try {

                date = formatter.parse(current);
                cs.setTime(date);


            } catch (ParseException e) {
                e.printStackTrace();

            }


        int workstart = cs.DAY_OF_MONTH;
            int workyear = cs.YEAR;
            int workmonth = cs.MONTH;
            int workstartmin = cs.MINUTE;
            int workstarth = cs.HOUR_OF_DAY;

        if ((count+1) != i){
            count=count+1;
            if (workyear == year & workmonth == month & day == workstart){
            current = list.get(count);
                current.replace(getString(R.string.workstart) + " ","");
                current.replace(getString(R.string.workstop) + " ","");

                try {

                    date = formatter.parse(current);
                    cs.setTime(date);


                } catch (ParseException e) {
                    e.printStackTrace();

                }

            int workend = cs.DAY_OF_YEAR;
            int workendmin = cs.MINUTE;
            int workendh = cs.HOUR_OF_DAY;

if (workend==workstart){
    int workendtime = workendh * 60 + workendmin;
    int workstarttime = workstarth * 60 + workstartmin;

worktimetoday = worktimetoday + (workendtime - workstarttime);
}else {
    int workstarttime = workstarth * 60 + workstartmin;

    worktimetoday = worktimetoday + (1440 - workstarttime);

}}}}

        TextView tw = (TextView) findViewById(R.id.textView);
        tw.setText(getString(R.string.worked)+ " "+ worktimetoday + " min.");
        }

这是控制台错误:

04-16 20:51:02.420  19544-19544/tk.spyfly.worktime E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: tk.spyfly.worktime, PID: 19544
    java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.spyfly.worktime/tk.spyfly.worktime.Overview}: java.lang.IndexOutOfBoundsException: Invalid index 42, size is 42
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2237)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:212)
            at android.app.ActivityThread.main(ActivityThread.java:5135)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
            at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.IndexOutOfBoundsException: Invalid index 42, size is 42
            at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
            at java.util.ArrayList.get(ArrayList.java:308)
            at tk.spyfly.worktime.Overview.reload(Overview.java:79)
            at tk.spyfly.worktime.Overview.onCreate(Overview.java:164)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:212)
            at android.app.ActivityThread.main(ActivityThread.java:5135)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
            at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
            at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:1)

while (count != i){

应该是:

while (count != i-1){

现在count等于列表大小,接下来你加1来计算。计数将大于列表大小。所以你得到一个outofbounds异常

答案 1 :(得分:0)

输出中的相关行是:

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 42, size is 42
       at tk.spyfly.worktime.Overview.reload(Overview.java:79)

这意味着在Overview类的第79行中,您尝试访问包含42个项目的集合的元素43。

问题在于此片段:

int i = list.size();
int count = 0;
while (count != i) {
  count = count + 1;
  current = list.get(count);
  // ...
}

想象一下count如何从循环增加到循环。您永远不会访问第一个元素(索引0),并且您将尝试访问不存在的元素(索引i + 1)。您应该在count循环结束处移动while的增量以使其正常工作。

答案 2 :(得分:0)

    int i = list.size();
    int count = 0;
    while (count != i){
    count= count +1;

列表索引从0开始并以" size-1"结束,在此循环中,您跳过第一个项目(索引0)并尝试读取索引42(没有&#t; t存在):

Caused by: java.lang.IndexOutOfBoundsException: Invalid index 42, size is 42

你可以将增量移动到循环的末尾(将读取索引0,并且42将不会

答案 3 :(得分:0)

你做错了什么

您正在将list.size()保存到变量i(值42)。 然后你有一个从0和while( count != i )开始的计数器,这意味着你试图循环43次而不是42次,因此IndexOutOfBoundsException。

解决方案

你使它变得比你更复杂。 您应该使用Java foreach循环,而不是保存list.size()并在while循环中使用计数器。

请参阅this example

for (int val : collection) { // for each int value in collection...
   // ...do something
}

提示

但是,如果您需要最佳性能(尽可能快),请阅读:

Performance comparison of different for loops in java