简体   繁体   中英

App crashing when using SharedPreferences to carry over final score

My android app is crashing when using SharedPreferences to try and carry the final score over from when the game ends. The app crashes inside the onTouchEvent at the line.

SharedPreferences.Editor editor = mySharedPreferences.edit();

The idea is when the game ends it final score that is within the SVGameView to carry over into the SVGameOver class and display there. If anyone could give some advice that would be great!

SVGameView:

    public class SVGameView extends SurfaceView implements Runnable {
    private SurfaceHolder holder;
    Thread thread = null;
    volatile boolean running = false;
    static final long FPS = 30;
    private Sprite sprite;
    private long lastClick;

    private Bitmap ball, gameOver;
    //private int x = 200, y = 200;
    private int scorePosX = 100;
    private int scorePosY = 100;
    private int countScore = 0;
    private int life = 1;

    SharedPreferences mySharedPreferences;

    public SVGameView(Context context) {
        super(context);
        thread = new Thread(this);
        holder = getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                boolean retry = true;
                running = false;
                while (retry) {
                    try {
                        thread.join();
                        retry = false;
                    } catch (InterruptedException e) {
                    }
                }
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                running = true;
                thread.start();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format,
                                       int width, int height) {
            }
        });

        ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball2);
        gameOver = BitmapFactory.decodeResource(getResources(),R.drawable.endscreen);
        sprite = new Sprite(this, ball);

        context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
    }

    @Override
    public void run() {
        long ticksPS = 1000 / FPS;
        long startTime;
        long sleepTime;

        while (running) {
            Canvas c = null;
            startTime = System.currentTimeMillis();
            try {
                c = getHolder().lockCanvas();
                synchronized (getHolder()) {
                    update();
                    onDraw(c);
                }
            } finally {
                if (c != null) {
                    getHolder().unlockCanvasAndPost(c);
                }
            }
            sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
            try {
                if (sleepTime > 0)
                    thread.sleep(sleepTime);
                else
                    thread.sleep(10);
            } catch (Exception e) {}

        }
    }

    private void update(){
        sprite.update();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
        Paint paint = new Paint();
        canvas.drawPaint(paint);
        paint.setColor(Color.WHITE);
        paint.setTextSize(48);
        canvas.drawText("Score: " + countScore, scorePosX, scorePosY, paint);
        canvas.drawText("Lives: " + life, 500, 100, paint);
        sprite.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if(System.currentTimeMillis()-lastClick > 300){
            lastClick = System.currentTimeMillis();
        }

        synchronized (getHolder()){
            if(sprite.isHit(event.getX(), event.getY())){
                countScore += 1;
                sprite.increase();
            }else{
                life --;
            }
        }

        if(life == 0) {
            getContext().startActivity(new Intent(getContext(), SVGameOver.class));
            //Intent intent;
            //intent = new Intent(getContext(), SVGameView.class);
            //intent.putExtra("scoreOutput", countScore);

            //Crashes Here
            SharedPreferences.Editor editor = mySharedPreferences.edit();
            editor.putString("cScore", String.valueOf(countScore));
        }
        return super.onTouchEvent(event);
    }
}

SVGameOver Class:

 public class SVGameOver extends Activity implements View.OnClickListener{

    Button btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        btnBack = (Button)findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);

        SharedPreferences mySharedPreferences = getSharedPreferences("myPrefsFile", 0);

        String theScore = mySharedPreferences.getString("cScore","");
        TextView textView = (TextView)findViewById(R.id.scoreOutput);
        textView.setText(theScore);

        //intent = getIntent();
        //String uir = intent.getStringExtra("scoreOutput");
    }

    @Override
    public void onClick(View v) {

    }
}

XML Layout:

https://gyazo.com/8e49d02c66dde7ff0e7f09a4fa9eacd2

You're missing:

mySharedPreferences = context.getSharedPreferences("myPrefsFile", Context.MODE_PRIVATE);

in your SVGameView, so mySharedPreferences always null.

You missed assigning SharedPreferences object to your reference mySharedPreferences in SVGameView(Context context) -

context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);

Change it to

mySharedPreferences = context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);

You are not initializing the SharedPreference object right. Use this library , which simplifies the use of SharedPreferences and will make life simpler for you.

Android-SharedPreferences-Helper simplifies usage of the default Android SharedPreferences Class. The developer can do in a few lines of code which otherwise would have required several. Simple to understand as compared to the default class and easy to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM