在模拟器中工作但在android中没有在手机中工作?

时间:2011-11-08 13:26:20

标签: android

我是android新手,我正处于创建一个应用程序的完成阶段。 但不幸的是,在Android手机中运行时会出现一些错误,但在android模拟器中完美运行...

这是我的java代码:

包com.VRG;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Animalsgame extends Activity implements OnClickListener {
    // int answer=0;
    Button voice;
    MediaPlayer mp;
    TextView time;// count down timer
    ImageView img_view1;
    ImageView img_view2;
    ImageView img_view3;
    ImageView img_view4;
    private ImageView selectedImageView;
    static int index = 0;
    static int index1 = 0;
    static int noOfLapse;
    static int count;
    static int score = 1;
    static boolean isSoundPlay;
    CountDownTimer CountDownTimer;
    int idx;
    Integer next;

    private Random random;
    private ArrayList<MediaPlayer> sounds;
    private ArrayList<MediaPlayer> tempSounds;
    // Track the sound which is playing
    private int soundSelectedIndex;

    private Vector matchImages = null;
    List<Integer> generated;

    // Total number of image boxes

    private static final int NO_IMAGE_BOXES = 4;

    final int[] imageViews = { R.id.img_view1, R.id.img_view2, R.id.img_view3,
            R.id.img_view4 };// Array of image views

    int[] Animals_images = { R.drawable.cow, R.drawable.lion, R.drawable.dog,
            R.drawable.sheep, R.drawable.elephant, R.drawable.camel,
            R.drawable.rhinos, R.drawable.horse, R.drawable.donkey,
            R.drawable.wolf }; // Array of Animal images

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);

        time = (TextView) this.findViewById(R.id.time);

        img_view1 = (ImageView) this.findViewById(R.id.img_view1);
        img_view2 = (ImageView) this.findViewById(R.id.img_view2);
        img_view3 = (ImageView) this.findViewById(R.id.img_view3);
        img_view4 = (ImageView) this.findViewById(R.id.img_view4);

        img_view1.setOnClickListener(this);
        img_view2.setOnClickListener(this);
        img_view3.setOnClickListener(this);
        img_view4.setOnClickListener(this);

        // Count down timer
        voice = (Button) this.findViewById(R.id.voice);// Animals sounds

        voice.setOnClickListener(this);

        // Initialise Lapse counter
        noOfLapse = 0;
        isSoundPlay = true;

        random = new Random();

        sounds = new ArrayList<MediaPlayer>();
        sounds.add(MediaPlayer.create(this, R.raw.cow));
        sounds.add(MediaPlayer.create(this, R.raw.lion));
        sounds.add(MediaPlayer.create(this, R.raw.dog));
        sounds.add(MediaPlayer.create(this, R.raw.sheep));
        sounds.add(MediaPlayer.create(this, R.raw.elephant));
        sounds.add(MediaPlayer.create(this, R.raw.camel));
        sounds.add(MediaPlayer.create(this, R.raw.rhino));
        sounds.add(MediaPlayer.create(this, R.raw.horse));
        sounds.add(MediaPlayer.create(this, R.raw.donkey));
        sounds.add(MediaPlayer.create(this, R.raw.wolf));

        tempSounds = (ArrayList<MediaPlayer>) sounds.clone();

        enableDisableImageView(false);

    }// End of Oncreate method

    public void setDuration(int duration) {

    }

    @Override
    public void onClick(View v) {
        Log.i("voice", "voice button clicking");
        enableDisableImageView(true);

        if (v instanceof ImageView) {

            count++;
            // Toast.makeText(getApplicationContext(), "Wrong",
            // Toast.LENGTH_SHORT).show();
            enableDisableImageView(false);

        }

        if (v == selectedImageView) {
            Toast.makeText(getApplicationContext(), "Correct!",
                    Toast.LENGTH_SHORT).show();
            score++;
            Log.i("11111", "count value:" + score);
            Log.i("22222", "count value:" + count);
            enableDisableImageView(false);

        }

        if (v == img_view1) {

            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }

            time.setText("");
            if (CountDownTimer != null) {
                CountDownTimer.cancel();
            }
            enableDisableButton(true);
        }
        if (v == voice) {

            // answer++;
            freezeButtonAndPlaySoundThenUnfreezeButton();
            loadImages();
            countDown();
            // enableDisableButton(true);
        }

        if (v == img_view2) {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }

            enableDisableButton(true); // Re-enable buttons
        }
        // else if (v == voice) {
        // loadImages();
        // countDown();
        // enableDisableButton(false);
        // }

        if (v == img_view3) {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }

            enableDisableButton(true); // Re-enable buttons
        }
        // else if (v == voice) {
        // loadImages();
        // countDown();
        // enableDisableButton(false);
        // }

        if (v == img_view4) {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }

            enableDisableButton(true); // Re-enable buttons
        }
        // else if (v == voice) {
        // loadImages();
        // countDown();
        // enableDisableButton(false);
        // }

        if (count > 8) {
            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
            setDuration(0);
            mp = MediaPlayer.create(this, R.raw.claps);
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.stop();
                }
            }
            mp.start();
            Toast.makeText(getApplicationContext(), "Your Score : " + score,
                    Toast.LENGTH_SHORT).show();
            // set the message to display
            alertbox.setMessage("Game Over..!" + " " + "Your score is:" + " "
                    + score + " " + " Do you want to play again?");
            // set a positive/yes button and create a listener
            alertbox.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {

                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {
                            if (mp != null) {
                                if (mp.isPlaying()) {
                                    mp.stop();
                                }
                            }
                            index = 0;
                            index1 = 0;
                            count = 0;
                            score = 1;
                            Intent i = new Intent(Animalsgame.this,
                                    Animalsgame.class);
                            startActivity(i);
                            finish();
                        }
                    });

            // set a negative/no button and create a listener
            alertbox.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {

                        // do something when the button is clicked
                        public void onClick(DialogInterface arg0, int arg1) {
                            if (mp != null) {
                                if (mp.isPlaying()) {
                                    mp.stop();
                                }
                            }
                            count = 0;
                            score = 0;
                            finish();
                            // Intent i = new Intent(VRGActivity2.this,
                            // VRGActivity1.class);
                            // startActivity(i);

                        }
                    });

            // display box
            alertbox.show();
            enableDisableButton(false);
        }
    }// End of voice on click

    private void countDown() {

        CountDownTimer = new CountDownTimer(6000, 10000) {

            public void onTick(long millisUntilFinished) {
                if (isSoundPlay) {
                    // freezeButtonAndPlaySoundThenUnfreezeButton();
                    isSoundPlay = false;
                }
                time.setText("" + "" + millisUntilFinished / 10000);

            }

            public void onFinish() {

                // time.setText("UP");
                setDuration(0);
                // Toast.makeText(getApplicationContext(), "Time Up",
                // Toast.LENGTH_SHORT).show();

                isSoundPlay = true;

            }// End of on finish
        }.start(); // End of countDown Constructor
    }// End of countDown method

    public void enableDisableButton(Boolean state) {

        voice.setEnabled(state);

    }// End of enableDisableButton(Boolean state)

    public void enableDisableImageView(Boolean state) {

        img_view1.setEnabled(state);
        img_view2.setEnabled(state);
        img_view3.setEnabled(state);
        img_view4.setEnabled(state);

    }// End of enableDisableImageView(Boolean state)

    private void loadImages() {

        Random rng = new Random(); // Random function

        if (generated == null) {
            generated = new ArrayList<Integer>();
        } else {
            generated.clear();
        }

        Log.i(this.toString(), "soundSelectedIndex " + soundSelectedIndex);
        generated.add(soundSelectedIndex);
        Log.i(this.toString(), "Initial Array Count " + generated.size());
        Boolean flag;

        for (int i = 0; i < NO_IMAGE_BOXES - 1; i++) {
            Log.i(this.toString(), "For i " + i);
            flag = true;
            while (flag) {
                next = rng.nextInt(9);
                index = next;
                if (!generated.contains(next)) {

                    Log.i(this.toString(), "Generated Array Contents " + next);
                    generated.add(next);
                    // ImageView iv = (ImageView) findViewById(imageViews[i]);
                    // iv.setImageResource(Animals_images[next]);
                    flag = !flag;

                }// End of if

                // break;

            }// While loop

        }// End of for loop

        // Set the last image

        // Choose the random position

        int pos = rng.nextInt(3);
        int temp = generated.get(0);
        generated.set(0, generated.get(pos));
        generated.set(pos, temp);
        selectedImageView = (ImageView) findViewById(imageViews[pos]);
        for (int i = 0; i < generated.size(); i++) {
            Log.i("Array Element in the list", "   " + generated.get(i));
            ImageView iv = (ImageView) findViewById(imageViews[i]);

            iv.setImageResource(Animals_images[generated.get(i)]);

        }

    }// End of loadImages()

    public void freezeButtonAndPlaySoundThenUnfreezeButton() {
        enableDisableButton(false); // disable buttons
        int randomInt = random.nextInt(tempSounds.size());

        // Set the selected sounds

        Log.i(this.toString(), "Random Generated Sounds " + randomInt);

        // soundSelectedIndex = randomInt;
        mp = tempSounds.get(randomInt);

        // if (sounds.contains(tempSounds.get(randomInt))){

        // Get the actual index from the sounds list

        soundSelectedIndex = sounds.indexOf(tempSounds.get(randomInt));

        Log.i(this.toString(), "freezeButtonAndPlaySoundThenUnfreezeButton "
                + soundSelectedIndex);

        // }

        tempSounds.remove(randomInt);

        mp.seekTo(0);
        mp.start();
        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mpalmost) {

            }// End of on completion method

        });// End of set on click listener method

    }// End of freezeButtonAndPlaySoundThenUnfreezeButton method

    @Override
    // while back pressed the task is refreshed
    public void onBackPressed() {

        if (mp != null) {
            if (mp.isPlaying()) {
                mp.stop();
            }// End of if (mp.isPlaying())

        }// End of if (mp != null)

    }// End of back pressed

    @Override
    protected void onPause() {

        super.onPause();

    }// End of on pause method

    @Override
    protected void onStart() {

        super.onStart();

    }// End of on start method

    @Override
    protected void onResume() {

        super.onResume();

    }// End of on resume method

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        onBackPressed();
        finish();

        return true;

    }// End of onKeyDown method

    // // Define method for choosing matching image
    //
    // void chooseImages() {
    //
    // }// End of choosing images
    //
    // // Define method for getting random values
    //
    // int getRandom(int value) {
    //
    // if (random == null) {
    //
    // random = new Random();
    //
    // }
    //
    // return random.nextInt(value);
    //
    // }// End of getRandom(int value) method

}// End of Animalsgame activity



I am using one sound button, and four image views. When i click the sound button, the sound get raised and simultaneously, imageviews are filled with images. But in phone when i run it. it shows error in some instance, when i click the sound button. 

My part of java coding, in which i am working is mentioned above..  

The error which i am getting is **Null pointer expection** and the error pointed out is in freezeButtonAndPlaySoundThenUnfreezeButton. Plz do me a needful..!

1 个答案:

答案 0 :(得分:0)

我猜你错过了声音(第394行的mp变量为null)。你不应该在0和int randomInt = random.nextInt(tempSounds.size())之间随机;因为没有元素和位置tempSounds.size()。它应该是(tempSounds.size() - 1)。