2016-06-09 2 views
0

방금 ​​java.lang.IndexOutOfBoundsException을 받았지만 발생 원인을 이해할 수 없습니다. 기본적으로, 나는 sqlite 테이블의 레코드를 listview에 통합하고있다. 다음은 테이블에서 레코드를 가져 오는 SQL 쿼리입니다.해결 방법 IndexOutOfBoundsException : 잘못된 인덱스 1, 크기가 1입니까?

public ArrayList<Integer> getRecordsCount(int no) { 

    ArrayList<Integer> count = new ArrayList<>(); 

    Cursor c = database.rawQuery(
      "select count(*) as TotalCount, tDate, " + 
        "strftime('%d', tDate) as DayPart, " + 
        "strftime('%m', tDate) as MonthPart, " + 
        "strftime('%Y', tDate) as YearPart " + 
        "from library " + 
        "where type = '" + no + "' " + 
        "group by MonthPart, YearPart", null); 

    while (c.moveToNext()) { 
     count.add(c.getInt(0)); 
    } 

    return count; 
} 

이 내 방법은 데이터를 검색하는 것입니다 : -

public void setDataInList(int no) { 

    if (no == 0) { 

     ArrayList<Integer> count = helper.getRecordsCount(1); 

     mainGetLibraryModels.clear(); 
     MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no); 
     for (int i = 0; i < modelWS.getRecords().size(); i++) { 

      WSLibraryModel model = new WSLibraryModel(); 
      model.setAmount(modelWS.getRecords().get(i).getAmount()); 
      model.setTotalCount("" + count.get(i)); 
      model.setYearPart(modelWS.getRecords().get(i).getYearPart()); 
      model.setMonthPart(modelWS.getRecords().get(i).getMonthPart()); 

      mainGetLibraryModels.add(model); 

     } 
     adapter.notifyDataSetChanged(); 

    } else if (no == 1) { 

     ArrayList<Integer> count = helper.getRecordsCount(2); 

     mainGetLibraryModels.clear(); 
     MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no); 
     for (int i = 0; i < modelWS.getRecords().size(); i++) { 

      WSLibraryModel model = new WSLibraryModel(); 
      model.setAmount(modelWS.getRecords().get(i).getAmount()); 
      model.setTotalCount("" + count.get(i)); 
      model.setYearPart(modelWS.getRecords().get(i).getYearPart()); 
      model.setMonthPart(modelWS.getRecords().get(i).getMonthPart()); 

      mainGetLibraryModels.add(model); 
     } 
     adapter.notifyDataSetChanged(); 

    } else { 

     mainGetLibraryModels.clear(); 
     MainLibraryModelWS modelWS = helper.getAllRecordsMonthWise2(no); 
     for (int i = 0; i < modelWS.getRecords().size(); i++) { 

      WSLibraryModel model = new WSLibraryModel(); 
      model.setAmount(modelWS.getRecords().get(i).getAmount()); 
      model.setTotalCount(" - "); 
      model.setYearPart(modelWS.getRecords().get(i).getYearPart()); 
      model.setMonthPart(modelWS.getRecords().get(i).getMonthPart()); 

      mainGetLibraryModels.add(model); 

     } 
     adapter.notifyDataSetChanged(); 

    } 
} 

그러나, 나는이 코드를 실행하면, 그것은 내게 오류를 준다? 대신이의

FATAL EXCEPTION: main Process: com.teezom, PID: 14168 
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 
    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) 
    at java.util.ArrayList.get(ArrayList.java:308) 
+2

때문에 – ThiepLV

답변

1

먼저 if-else 브랜칭 대신 switch을 사용하십시오. 쿼리 결과가 수정 된 결과를 배열로 제공하므로 (스위치가 더 효율적이며 가독성을 향상 시킴).

public void setDataInList(int no) { //just a suggestion not a answer 

    switch (no){ 
    case 0 : 
      //Your Code as you specified in your code context. 
      break; 
    case 1 : 
      //Your Code as you specified in your code context. 

      break; 
    case 2 : 
      //Your Code as you specified in your code context. 

     break; 
    default : 
     break; 
    } 

지금 당신은 당신의 Exception 스택 트레이스를 볼 경우 문제가 오는하고 쉽게 솔루션을 얻을 것이다 일단 응용 프로그램을 디버깅.

이 당신의 스택 트레이스가

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 

당신이 배열에 존재하지 않는 어떤 배열 인덱스에 액세스하려고하는 동안 IndexOutOfBoundsException 만 온이 인기 예외를 알고 희망 말했죠 것입니다.

이제 Array 크기가 one이라는 오류 메시지가 분명하게 표시됩니다. 배열이 zero (0) 인 경우에만 액세스 할 수 있음을 의미합니다.

그래서, 당신의 코드를 디버깅 및 In-사실 카운트 배열 크기가 1 그래서 당신은 0 인덱스로 접근 할 필요가있다

2

:

ArrayList<Integer> count = helper.getRecordsCount(1); 

이 시도 :

ArrayList<Integer> count = helper.getRecordsCount(0); 
+0

아니, 난 할 수없는 예외를 생성하는 코드의 어떤 라인을 찾아 보시기 바랍니다. – Mahesh

+0

@MaheshBpsk 첫 번째 위치에서 요소에 액세스하려면 0부터 요소에 액세스해야합니다. 인덱스는 0부터 시작합니다. 레코드를 액세스하기 위해 if (no == 0)를 확인하고 1을 보냅니다. 두 번째로 2 대신에 1을 넣으십시오. –

0

첫째, 당신은() 너무 여러 번 GetRecords라는 호출하지 않도록해야합니다. 성능에 비용이 소요되고 동일한 결과 (오류의 가능한 원인)가 반환되지 않을 수 있습니다. 대신이 함수의 캐시 출력으로 로컬 매개 변수를 도입하고 함께 사용하십시오.

+1

이것은 주석이어야합니다. 또한 OP에서 물어 본 질문에 실제로 대답하지 않았습니다. – YoungHobbit

+2

내 평판 <50. 내가 할 수 있으면 좋겠다 ... – Robo

관련 문제