从ArrayList中选择一个随机ImageButton会引发NullPointerException

时间:2014-08-04 19:23:49

标签: java android arraylist nullpointerexception imagebutton

我正在尝试更改从ArrayList中随机拾取的ImageButton的图像,但会引发NullPointerException。

单击ImageButton时,我试图通过ImageButton1.setImageResource(R.drawable.someImage);更改ImageButton的图像。

然后我希望程序更改从包含我想要使用的ImageButtons的ArrayList中随机选取的其他一些ImageButton的ImageResource。然后我想通过

将随机选择的ImageButton的imageResource设置为someOtherPicture
ImageButton currentImage;
Random randomNumber = new Random();
int randomNum = randomNumber.nextInt(someArrayList.size());
currentImage = someArrayList.get(randomNum);
currentImage.setImageResource(R.drawable.someOtherImage);

我在Android Studio中编辑并在Motorola Moto G设备上运行,当我点击该按钮时,应用程序突然停止。 Log Cat声称它是randomlyPlaceImage()方法的NullPointerException。

以下是整个代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends Activity {

ImageButton ImageButton1;
ArrayList<ImageButton> someArrayList = new ArrayList<ImageButton>();
Random randomNumber = new Random();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

addItemsToList();
ImageButton1 = (ImageButton) findViewById(R.id.imageButton1);
        ImageButton1.setOnClickListener(ImageButton1Listener);

}

  addItemsToList (){
    someArrayList.add(ImageButton1);
    someArrayList.add(ImageButton2);
    someArrayList.add(ImageButton3);
    someArrayList.add(ImageButton4);
    someArrayList.add(ImageButton5);
    someArrayList.add(ImageButton6);
    someArrayList.add(ImageButton7);
    someArrayList.add(ImageButton8);
    someArrayList.add(ImageButton9);
}

public void changeImageResource() {
 ImageButton currentImage;
    int randomNum = randomNumber.nextInt(someArrayList.size());
    currentImage = someArrayList.get(randomNum);
    currentImage.setImageResource(R.drawable.someOtherImage);
}

    View.OnClickListener ImageButton1Listener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        ImageButton1.setImageResource(R.drawable.someImage);
        someArrayList.remove(ImageButton1);

        changeImageResource();
    }
};    

}

注意:OnCLick方法当然是针对所有ImageButtons重复的

1 个答案:

答案 0 :(得分:1)

在初始化之前,您似乎要将项目添加到列表中:

addItemsToList();
ImageButton1 = (ImageButton) findViewById(R.id.imageButton1);
        ImageButton1.setOnClickListener(ImageButton1Listener);

这意味着someArrayList将包含一堆空引用。

这就是为什么currentImage = someArrayList.get(randomNum);返回null和 currentImage.setImageResource(R.drawable.someOtherImage);导致NullPointerException。

您应该将初始化顺序更改为:

ImageButton1 = (ImageButton) findViewById(R.id.imageButton1);
        ImageButton1.setOnClickListener(ImageButton1Listener);
ImageButton2 = (ImageButton) findViewById(R.id.imageButton2);
        ImageButton2.setOnClickListener(ImageButton2Listener);
....
addItemsToList();