Question

I am creating an activity that displays 9 images in a GridView. I want those images be selected randomly from an Integer[] array that contains 26 images. So my best approach is setting the 26 images fixed and then created a new array and fill using this simple method:

    public Integer [] allLetters = {
             R.drawable.a, R.drawable.b,
             R.drawable.c, R.drawable.d,
             R.drawable.e, R.drawable.f,
             R.drawable.g, R.drawable.h,
             R.drawable.i, R.drawable.j,
             R.drawable.k, R.drawable.l,
             R.drawable.m, R.drawable.m,
             R.drawable.o, R.drawable.p,
             R.drawable.q, R.drawable.r,
             R.drawable.s, R.drawable.t,
             R.drawable.u, R.drawable.v,
             R.drawable.w, R.drawable.x,
             R.drawable.y, R.drawable.z
    };
    private Integer[] randomLetters=null;
    public int index=0;
    public Random r= new Random();
    public void creaArray() {
        for (int i = 0; i < 9; i++){
            index=r.nextInt(26);
            randomLetters[i]=allLetters[index];
        }
    }

I thought this would fill randomLetters with 9 random values from allLetters but the app is "forced closing" me :( Any ideas?

Was it helpful?

Solution

It crashes because you have not initialized the integer array. You must do something like this:

private Integer[] randomLetters = new Integer[9];

Bear in mind that your current algorithm could repeat some of the letters, which sometimes is an undesirable behavior.

Also, ready about how to use adb logcat in order to detect problems like this. You will save you and us a lot time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top