views:

45

answers:

0

I am writing an Android app, which is basically a quiz. A it contains pictures of animals and the user must click on the correct picture. The pictures are all png files used as background pictures for button views.

The problem I have/had is with the onCLick method. THis is the code.

public void onClick(View view) {

    if(view == r1){
        if (correct == 0){
            tally++;}
        total++;
        score.setText("Score: " + tally + " out of " + total );
        rg.clearFocus();
        rg.clearCheck();
        new Thread(new Runnable() {
            public void run() {
                quest.post(new Runnable() {
                    public void run() {
                        correct = nextQ();
                    }
                });

            }

        }).start();


    }

    if (view == r2){
        if (correct == 1){
            tally++;}
        total++;
        score.setText("Score: " + tally + " out of " + total );
        rg.clearFocus();
        rg.clearCheck();
        new Thread(new Runnable() {
            public void run() {
                quest.post(new Runnable() {
                    public void run() {
                        correct = nextQ();
                    }
                });

            }

        }).start();

    }

    if (view == r3){
        if (correct == 2){
            tally++;}
        total++;
        score.setText("Score: " + tally + " out of " + total );
        rg.clearFocus();
        rg.clearCheck();

        new Thread(new Runnable() {
            public void run() {
                quest.post(new Runnable() {
                    public void run() {
                        correct = nextQ();
                    }
                });

            }

        }).start();
    }
}

r1,r2.r3 are all buttons, and quest is the question TextView. My first attempt at doing this worked fine, except one problem - it crashed a lot. I didn't use the thread you se in the code above. I also had a fourth button r4. After investigating on the internet I found that making Android search and select pictures can cause problems and it is best to put this in another thread. So I did that, and it is shown in the code above. It still crashed, so I took out the fourth button. It now works fine, but I'm not sure why.

My question is, can anyone tell me how to do this correctly? I mean when a button is clicked, new pictures are randomly generated from a section. All the pictures are stored in the drawable folder, it doesn't grab them online.