마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

왜 이런 오류가 발생하는 건가요?

0 추천

파이어베이스에 있는 내용을 출력했습니다.  info0의 값 중에서 필요없는 부분을 제거하고 "&"로 문자를 나눴습니다. 문제는 3번째 "&" 뒤에 문자가 없으면 앱이 꺼집니다. 왜 그런건가요?  

"\n"뒤에는 항상 어떠한 문자가 존재 해야하나요??

 

 

 

DocumentReference docRef0= dbList.collection("order").document("info0");
            docRef0.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()) {
                        DocumentSnapshot document = task.getResult();
                        if (document.exists()) {
                            str=document.getData().toString();
                            str = str.substring(10,str0.length()-1);
                            strSplit = str.split("&");
                            str0=strSplit[0];
                            str1=strSplit[1];
                            str2=strSplit[2];
                            str3=strSplit[3];
                            str=str0+"\n"+str1+"\n"+str2+"\n"+str3;
                            arrayList.add(str);
                            Collections.sort(arrayList,Collections.reverseOrder());
                            listview.setAdapter(adapter);
                        } else {
                        }
                    } else {
                    }
                }
            });

 

 

 

개미1 (1,260 포인트) 님이 2021년 11월 13일 질문
개미1님이 2021년 11월 13일 수정

1개의 답변

0 추천

이유는 배열의 크기가 3인데 4번째 아이템에 접근했기 때문입니다. 아래를 보시면 이해가 가실 거예요.

str = "11/13(09-20)&&" // &로 끝나지 않는 문자열.
strSplit = str.split("&"); // ["11/13(09-20)", "'", ""]
str0=strSplit[0];  //11/13(09-20)
str1=strSplit[1];  // ""
str2=strSplit[2];  // ""
str3=strSplit[3]; // 존재하지 않음

 

위와 같은 경우 IndexOutOfBoundException이 발생합니다. 해결방법은  Exception를 캐치하거거나 Exception이 나지 않도록 방지하는 겁니다.

// Exception 캐치
try {
     strSplit = str.split("&"); // ["11/13(09-20)", "'", ""]
     str0=strSplit[0];  //11/13(09-20)
     str1=strSplit[1];  // ""
     str2=strSplit[2];  // ""
     str3=strSplit[3]; // 존재하지 않음
} catch (IndexOutOfBoundException e) {
     // 적절한 처리
}

// 에러방지
str = str + "&&&";  // 이렇게 &를 세개 더하면 어떤 경우에도 에러가 나지않겠죠.
strSplit = str.split("&");
str0=strSplit[0]; 
str1=strSplit[1]; 
str2=strSplit[2]; 
str3=strSplit[3];

 

spark (227,930 포인트) 님이 2021년 11월 13일 답변
...