2011-10-25 3 views
0

내가 만드는 앱에는 사용자가 스크롤 할 수있는 사진이 많이 있습니다. 앱에는 개체 배열이 있고 각 개체에는 그림과 통계량. 나는 응용 프로그램이 종료 구축하고 오류 "죄송합니다, 응용 프로그램이 예기치 않게 중지"를 불러와 로그 캣 그래도내 배열이 특정 길이 인 경우 Android 앱이 실행되지 않음

10-25 18:46:24.578: ERROR/AndroidRuntime(491): FATAL EXCEPTION: main 
10-25 18:46:24.578: ERROR/AndroidRuntime(491): java.lang.RuntimeException: Unable to 
instantiate activity ComponentInfo{com.example.notes/com.example.notes.NotesListActivity}: 
java.lang.ArrayIndexOutOfBoundsException 

를 보여주고 여기에있을 때 내 응용 프로그램은 이제하지만, 내 배열은 58 개체를 포함 할 것입니다 완벽하게 실행되었다 내 현재 코드

public class NotesListActivity extends Activity implements OnClickListener 
{ 

public boolean nextClicked = false; 
public boolean prevClicked = false; 
public int counter = 1; 
public int nextImg; 
public FunnyPic[] picArray = new FunnyPic[55]; 
{ 
    picArray[0] = new FunnyPic(R.raw.img1, 0); 
    picArray[1] = new FunnyPic(R.raw.img2, 0); 
    ..... 
    ..... 
    ..... 
    picArray[180] = new FunnyPic(R.raw.img181, 0); 
    picArray[181] = new FunnyPic(R.raw.img182, 0); 

} 

public void onCreate(Bundle savedInstanceState) 
{ 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Button changePicButton = (Button) this.findViewById(R.id.button1); 
    changePicButton.setOnClickListener(this); 


} 

public void onClick(View view) 
{ 
    Log.i("onClick", "BEGIN"); 
    ImageView image = (ImageView) findViewById(R.id.imageView1); 
    if(counter == picArray.length-1) 
     counter=0; 
    image.setImageResource(picArray[counter].getImg()); 
    counter++; 
    Log.i("onClick", "END"); 
} 

public void prevPicHandler(View traget) 
{ 
    if(counter==0) 
    { 
     counter = picArray.length-1; 
    } 
    counter--; 
    Log.i("onClick", "BEGIN"); 
    ImageView image = (ImageView) findViewById(R.id.imageView1); 
    image.setImageResource(picArray[counter].getImg()); 

    Log.i("onClick", "END"); 
} 




} 

제안 사항이 있으면 알려주십시오. 또한 누구든지 배열에 개체를 넣을 더 효율적인 방법을 추천 할 수 있다면 새로운 그림을 추가 할 때마다 수동으로 넣지 않아도됩니다.

감사

답변

2

당신은 55 개 요소로 구성된 배열을 만들 :

:

public FunnyPic[] picArray = new FunnyPic[55]; 

최대 유효 인덱스는 여기에 54

당신은 다음 요소를 181에 액세스하려는입니다

picArray[181] = new FunnyPic(R.raw.img182, 0); 

어떻게 작동하길 기대 했습니까? 대신 List<FunnyPic>을 사용해 보셨습니까?

배열 변수 선언문이 있고 그 다음에 이니셜 라이저 블록이 별도로 있습니다. 에 배열 초기화 프로그램이 없습니다. 즉 당신이 알았는데 무엇을, 당신이 사용해야 :

public FunnyPic[] picArray = 
{ 
    new FunnyPic(R.raw.img1, 0), 
    new FunnyPic(R.raw.img2, 0), 
    ... 
    new FunnyPic(R.raw.img182, 0) 
}; 
+0

와우 나는 어리석은 하하를 느낍니다. 어떻게 보지 못했습니까? –

0

귀하의 최대 지수는 54입니다, 아직 샘플 코드, 당신은보다 큰 인덱스를 액세스하는. 흠 .. 문제가 무엇인지 궁금하네요.?


고양이

enter image description here

0

왜 ArrayList에 또는 벡터의 FunnyPic 객체를 저장?

public ArrayList<FunnyPic> getFunnyPicArray() 
{ 
    ArrayList<FunnyPic> picList = new ArrayList<FunnyPic>(); 
    picList.add(new FunnyPic(R.raw.img1, 0)); 
    //.. 
    return picList; 
} 
관련 문제