无法添加到圈子帆布动态 [英] unable to add circles to canvas dynamically

查看:126
本文介绍了无法添加到圈子帆布动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个球弹跳动态弹跳球。例如:在这里圈数是50。
但我得到的错误,而试图使圈动态的(模型)。如何让我的这工作,使dynamic.In这种情况下,50圈模型/圈?我真的AP preciate任何帮助。先谢谢了。

 包com.stuffthathappens.games;引入静态android.hardware.SensorManager.DATA_X;
引入静态android.hardware.SensorManager.DATA_Y;
引入静态android.hardware.SensorManager.SENSOR_ACCELEROMETER;
引入静态android.hardware.SensorManager.SENSOR_DELAY_GAME;进口java.util.concurrent.TimeUnit中;进口android.app.Activity;
进口android.graphics.Canvas;
进口android.graphics.Color;
进口android.graphics.Paint;
进口android.hardware.SensorListener;
进口android.hardware.SensorManager;
进口android.os.Bundle;
进口android.os.Vibrator;
进口android.view.SurfaceHolder;
进口android.view.SurfaceView;
进口android.view.SurfaceHolder.Callback;/ **
 *本活动表明,跳来跳去一球。这款手机的
 *加速度作为对球的重力。当球击中
 *边缘,它反弹回来,并触发手机振动器。
 * /
@燮pressWarnings(德precation)
公共类BouncingBallActivity扩展活动实现回调,SensorListener {
    私有静态最终诠释BALL_RADIUS = 20;
    私人SurfaceView表面;
    私人SurfaceHolder持有人;    私人GameLoop gameLoop;
    私人涂料backgroundPaint;
    私人涂料ballPaint;
    私人的SensorManager sensorMgr;
    私人长期lastSensorUpdate = -1;
    私人涂料ballPaintyellow;     私人BouncingBallModel []模型;    INT Totalcircles = 50;
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);        的setContentView(R.layout.bouncing_ball);        的for(int i = 0; I< Totalcircles;我++){
            模型由[i] =新BouncingBallModel(BALL_RADIUS);
        }        表面=(SurfaceView)findViewById(R.id.bouncing_ball_surface);
        支架= surface.getHolder();
        。surface.getHolder()的addCallback(本);        backgroundPaint =新的油漆();
        backgroundPaint.setColor(Color.WHITE);        ballPaint =新的油漆();
        ballPaint.setColor(Color.BLUE);
        ballPaint.setAntiAlias​​(真);        ballPaintyellow =新的油漆();
        ballPaintyellow.setColor(Color.YELLOW);
        ballPaintyellow.setAntiAlias​​(真);
    }    @覆盖
    保护无效的onPause(){
        super.onPause();        的for(int i = 0; I< Totalcircles;我++){            模型[I] .setVibrator(NULL);
        }        sensorMgr.unregisterListener(这一点,SENSOR_ACCELEROMETER);
        sensorMgr = NULL;        的for(int i = 0; I< Totalcircles;我++){            模型[I] .setAccel(0,0);
        }
    }    @覆盖
    保护无效onResume(){
        super.onResume();        sensorMgr =(的SensorManager)getSystemService(SENSOR_SERVICE);
        布尔accelSupported = sensorMgr.registerListener(这一点,
                SENSOR_ACCELEROMETER,
                SENSOR_DELAY_GAME);        如果(!accelSupported){
            //加速度计在此设备上
            sensorMgr.unregisterListener(这一点,SENSOR_ACCELEROMETER);
            // TODO显示错误
        }        //注1:你不能的onCreate之前得到系统服务()
        //注2:AndroidManifest.xml中必须包含这一行:
        //<使用许可权的android:NAME =android.permission.VIBRATE/>
        振动器振动=(振动器)getSystemService(Activity.VIBRATOR_SERVICE);        的for(int i = 0; I< Totalcircles;我++){            模型[I] .setVibrator(振动);
        }
    }    公共无效surfaceChanged(SurfaceHolder架,INT格式,宽度INT,
            INT高度){
        的for(int i = 0; I< Totalcircles;我++){
            模型[I] .setSize(宽,高);
        }
    }    公共无效surfaceCreated(SurfaceHolder持有人){
        gameLoop =新GameLoop();
        gameLoop.start();
    }    私人无效的draw(){
        //线程安全 - 的SurfaceView可以走,而我们正在绘制        帆布C = NULL;
        尝试{
            //注意:在LunarLander他们没有这里的任何同步,
            //所以我想这是确定。它会返回null,如果持有人是没有准备好
            C = holder.lockCanvas();            //这需要的东西同步
            如果(C!= NULL){
                doDraw(C);
            }
        } {最后
            如果(C!= NULL){
                holder.unlockCanvasAndPost(C);
            }
        }
    }    私人无效doDraw(帆布C){
        INT宽度= c.getWidth();
        INT高度= c.getHeight();
        c.drawRect(0,0,宽度,高度,backgroundPaint);        ///        浮ballX [] =新的浮动[50],BALLY [] =新的浮动[50];        的for(int i = 0; I< Totalcircles;我++){
            同步(模型[I] .LOCK){
                ballX [I] =模型[I] .ballPixelX;
                BALLY [I] =模型[I] .ballPixelY;            }
        }        //        的for(int i = 0; I< Totalcircles;我++){            c.drawCircle(ballX [I],BALLY [I],BALL_RADIUS,ballPaint);
        }
        }
    公共无效surfaceDestroyed(SurfaceHolder持有人){
        尝试{            的for(int i = 0; I< Totalcircles;我++){
                模型[I] .setSize(0,0);
            }
            gameLoop.safeStop();
        } {最后
            gameLoop = NULL;
        }
    }    私有类GameLoop继承Thread {
        私人挥发性布尔运行= TRUE;        公共无效的run(){
            而(运行){
                尝试{
                    //不喜欢这种硬编码
                    TimeUnit.MILLISECONDS.sleep(5);                    画();                    的for(int i = 0; I< Totalcircles;我++){
                        模型[I] .updatePhysics();
                    }                }赶上(InterruptedException的IE){
                    运行= FALSE;
                }
            }
        }        公共无效safeStop(){
            运行= FALSE;
            打断();
        }
    }    公共无效onAccuracyChanged(INT传感器,精度INT){
    }    公共无效onSensorChanged(INT传感器,浮动[]值){
        如果(传感器== SENSOR_ACCELEROMETER){
            长CURTIME = System.currentTimeMillis的();
            //只允许一个更新每隔50ms,否则更新
            //来太快
            如果(lastSensorUpdate == -1 ||(CURTIME - lastSensorUpdate)→50){
                lastSensorUpdate = CURTIME;                的for(int i = 0; I< Totalcircles;我++){
                    模型[I] .setAccel(值[数据_X]值[数据Y]);
                }
            }
        }
    }
}

model.java

 包com.stuffthathappens.games;进口java.util.concurrent.atomic.AtomicReference中;进口android.os.Vibrator;/ **
 *此数据模型沿轨道比赛场地的宽度和高度
 *用球的当前位置。
 * /
公共类BouncingBallModel {
    //球速度为米/秒。当我们绘制到屏幕,
    // 1像素再presents 1米。这结束了太慢了,所以乘
    //这个号码。更大的数字加速的事情了。
    私人最终浮动pixelsPerMeter = 10;    私人最终诠释ballRadius;    //这些都是公开的,所以一定要确保你在锁同步
    //读取时这些。我让他们公开,因为您需要
    //得到X和Y在对,并且这比更有效
    // getter方法​​。有两个干将,你仍旧需要
    //同步。
    公众持股量ballPixelX,ballPixelY;    私人诠释pixelWidth,pixelHeight;    //值以米/秒
    私人浮动velocityX,velocityY;    //典型值范围从-10 ... 10,但可能更高或更低,如果
    //用户快速移动的手机
    私人浮动accelX,accelY;    / **
     *当球击中的边缘,乘以反弹的速度。
     *值为1.0意味着100%的效率皮球反弹。降低
     *数字模拟不反弹非常多球。
     * /
    私有静态最终浮动反弹= 0.8f;    //如果球反弹和速度低于该恒定,
    //停止跳动。
    私有静态最终浮动STOP_BOUNCING_VELOCITY = 2F;    私人挥发性长lastTimeMs = -1;    公众最终对象锁=新的对象();    私人的AtomicReference<振动器> vibratorRef =
        新的AtomicReference<振动器>();    公共BouncingBallModel(INT ballRadius){
        this.ballRadius = ballRadius;
    }    公共无效setAccel(浮点斧,浮动AY){
        同步(LOCK){
            this.accelX = AX;
            this.accelY = AY;
        }
    }    公共无效的setSize(INT宽度,高度INT){
        同步(LOCK){
            this.pixelWidth =宽度;
            this.pixelHeight =高度;
        }
    }    公众诠释getBallRadius(){
        返回ballRadius;
    }    / **
     *调用此球移动到屏幕上的特定位置。这个
     *复位速度为零,但加速度不发生变化,以便
     *球应该开始下降很快。
     * /
    公共无效moveBall(INT ballX,诠释BALLY){
        同步(LOCK){
            this.ballPixelX = ballX;
            this.ballPixelY = BALLY;
            velocityX = 0;
            velocityY = 0;
        }
    }    公共无效updatePhysics(){
        //复制一切,本地变量(因此'L'preFIX)
        浮lWidth,lHeight,lBallX,lBallY,松懈,打好,LVX,常春藤;
        同步(LOCK){
            lWidth = pixelWidth;
            lHeight = pixelHeight;
            lBallX = ballPixelX;
            lBallY = ballPixelY;
            LVX = velocityX;
            常春藤= velocityY;
            LAX = accelX;
            莱= -accelY;
        }
        如果(lWidth&下; = 0 || lHeight&下; = 0){
            //无效的宽度和高度,无事可做,直到GUI来了
            返回;
        }
        长CURTIME = System.currentTimeMillis的();
        如果(lastTimeMs℃,){
            lastTimeMs = CURTIME;
            返回;
        }        长ela​​psedMs = CURTIME - lastTimeMs;
        lastTimeMs = CURTIME;        //更新速度
        //(除以1000,以毫秒转换为秒)
        //最后的结果是米/秒
        LVX + =((elapsedMs * LAX)/ 1000)* pixelsPerMeter;
        常春藤+ =((elapsedMs * LAY)/ 1000)* pixelsPerMeter;        //更新位置
        //(速度为米/秒,因此通过1000又分为)
        lBallX + =((LVX * elapsedMs)/ 1000)* pixelsPerMeter;
        lBallY + =((*常春藤elapsedMs)/ 1000)* pixelsPerMeter;        布尔bouncedX = FALSE;
        布尔bouncedY = FALSE;        如果(lBallY - ballRadius℃,){
            lBallY = ballRadius;
            常春藤= -lVy *反弹;
            bouncedY = TRUE;
        }否则如果(lBallY + ballRadius> lHeight){
            lBallY = lHeight - ballRadius;
            常春藤= -lVy *反弹;
            bouncedY = TRUE;
        }
        如果(bouncedY&安培;&安培; Math.abs(常春藤)LT; STOP_BOUNCING_VELOCITY){
            LVY = 0;
            bouncedY = FALSE;
        }        如果(lBallX - ballRadius℃,){
            lBallX = ballRadius;
            LVX = -lVx *反弹;
            bouncedX = TRUE;
        }否则如果(lBallX + ballRadius> lWidth){
            lBallX = lWidth - ballRadius;
            LVX = -lVx *反弹;
            bouncedX = TRUE;
        }
        如果(bouncedX&安培;&安培; Math.abs(LVX)LT; STOP_BOUNCING_VELOCITY){
            LVX = 0;
            bouncedX = FALSE;
        }
        //安全本地变量复制回对象字段
        同步(LOCK){
            ballPixelX = lBallX;
            ballPixelY = lBallY;            velocityX = LVX;
            velocityY =常春藤;
        }        如果(bouncedX || bouncedY){
            振动器V = vibratorRef.get();
            如果(V!= NULL){
                v.vibrate(20L);
            }
        }
    }    公共无效setVibrator(振动器V){
        vibratorRef.set(五);
    }
}

logcat的错误:

 致命异常:主要
 了java.lang.RuntimeException:无法启动活动ComponentInfo {} com.stuffthathappens.games/com.stuffthathappens.games.BouncingBallActivity:显示java.lang.NullPointerException
    在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2194)
    在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2229)
    在android.app.ActivityThread.access $ 600(ActivityThread.java:139)
    在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1261)
    在android.os.Handler.dispatchMessage(Handler.java:99)
    在android.os.Looper.loop(Looper.java:154)
    在android.app.ActivityThread.main(ActivityThread.java:4945)
    在java.lang.reflect.Method.invokeNative(本机方法)
    在java.lang.reflect.Method.invoke(Method.java:511)
    在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
    在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    在dalvik.system.NativeStart.main(本机方法)
 显示java.lang.NullPointerException:产生的原因
    在com.stuffthathappens.games.BouncingBallActivity.onCreate(BouncingBallActivity.java:52)
    在android.app.Activity.performCreate(Activity.java:4531)
    在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
    在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)


解决方案

您可以声明数组你这样的:

 私人BouncingBallModel [] =模型新BouncingBallModel [50];

像下面的

如何在Java中声明数组?

I tried to make a single ball bouncing to dynamic ball bouncing . Eg: here the number of circles is 50. But I am getting error while trying to make the circles dynamic (Model) .How do I make it work and make the model/circle dynamic.In this case 50 circles ? I really appreciate any help. Thanks in Advance.

package com.stuffthathappens.games;

import static android.hardware.SensorManager.DATA_X;
import static android.hardware.SensorManager.DATA_Y;
import static android.hardware.SensorManager.SENSOR_ACCELEROMETER;
import static android.hardware.SensorManager.SENSOR_DELAY_GAME;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;

/**
 * This activity shows a ball that bounces around. The phone's 
 * accelerometer acts as gravity on the ball. When the ball hits
 * the edge, it bounces back and triggers the phone vibrator.
 */
@SuppressWarnings("deprecation")
public class BouncingBallActivity extends Activity implements Callback, SensorListener {
    private static final int BALL_RADIUS =20;
    private SurfaceView surface;
    private SurfaceHolder holder;

    private GameLoop gameLoop;
    private Paint backgroundPaint;
    private Paint ballPaint;
    private SensorManager sensorMgr;
    private long lastSensorUpdate = -1;


    private Paint ballPaintyellow;

     private BouncingBallModel[] model;

    int Totalcircles=50;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.bouncing_ball);

        for (int i = 0; i < Totalcircles; i++) {
            model[i] = new BouncingBallModel(BALL_RADIUS); 
        }

        surface = (SurfaceView) findViewById(R.id.bouncing_ball_surface);
        holder = surface.getHolder();
        surface.getHolder().addCallback(this);

        backgroundPaint = new Paint();
        backgroundPaint.setColor(Color.WHITE);

        ballPaint = new Paint();
        ballPaint.setColor(Color.BLUE);
        ballPaint.setAntiAlias(true);

        ballPaintyellow = new Paint();
        ballPaintyellow.setColor(Color.YELLOW);
        ballPaintyellow.setAntiAlias(true);
    }

    @Override
    protected void onPause() {
        super.onPause();

        for (int i = 0; i < Totalcircles; i++) {

            model[i].setVibrator(null);
        }

        sensorMgr.unregisterListener(this, SENSOR_ACCELEROMETER);
        sensorMgr = null;

        for (int i = 0; i < Totalcircles; i++) {

            model[i].setAccel(0, 0);
        }


    }

    @Override
    protected void onResume() {
        super.onResume();

        sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
        boolean accelSupported = sensorMgr.registerListener(this, 
                SENSOR_ACCELEROMETER,
                SENSOR_DELAY_GAME);

        if (!accelSupported) {
            // on accelerometer on this device
            sensorMgr.unregisterListener(this, SENSOR_ACCELEROMETER);
            // TODO show an error
        }

        // NOTE 1: you cannot get system services before onCreate()
        // NOTE 2: AndroidManifest.xml must contain this line:
        // <uses-permission android:name="android.permission.VIBRATE"/>
        Vibrator vibrator = (Vibrator) getSystemService(Activity.VIBRATOR_SERVICE);

        for (int i = 0; i < Totalcircles; i++) {

            model[i].setVibrator(vibrator);
        }
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {


        for (int i = 0; i < Totalcircles; i++) {
            model[i].setSize(width, height);
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        gameLoop = new GameLoop();
        gameLoop.start();
    }

    private void draw() {
        // thread safety - the SurfaceView could go away while we are drawing

        Canvas c = null;
        try {
            // NOTE: in the LunarLander they don't have any synchronization here,
            // so I guess this is OK. It will return null if the holder is not ready
            c = holder.lockCanvas();

            // this needs to synchronize on something
            if (c != null) {
                doDraw(c);
            }
        } finally {
            if (c != null) {
                holder.unlockCanvasAndPost(c);
            }
        }
    }

    private void doDraw(Canvas c) {
        int width = c.getWidth();
        int height = c.getHeight();
        c.drawRect(0, 0, width, height, backgroundPaint);

        ///

        float ballX[]=new float[50], ballY[]=new float[50];

        for (int i = 0; i < Totalcircles; i++) {
            synchronized (model[i].LOCK) {
                ballX[i] = model[i].ballPixelX;
                ballY[i] = model[i].ballPixelY;

            }
        }

        //

        for (int i = 0; i < Totalcircles; i++) {

            c.drawCircle(ballX[i], ballY[i], BALL_RADIUS, ballPaint);
        }
        }


    public void surfaceDestroyed(SurfaceHolder holder) {
        try {

            for (int i = 0; i < Totalcircles; i++) {
                model[i].setSize(0,0);
            }
            gameLoop.safeStop();
        } finally {
            gameLoop = null;
        }
    }

    private class GameLoop extends Thread {
        private volatile boolean running = true;

        public void run() {
            while (running) {
                try {
                    //  don't like this hardcoding
                    TimeUnit.MILLISECONDS.sleep(5);

                    draw();

                    for (int i = 0; i < Totalcircles; i++) {
                        model[i].updatePhysics();
                    }

                } catch (InterruptedException ie) {
                    running = false;
                }
            }
        }

        public void safeStop() {
            running = false;
            interrupt();
        }
    }

    public void onAccuracyChanged(int sensor, int accuracy) {       
    }

    public void onSensorChanged(int sensor, float[] values) {
        if (sensor == SENSOR_ACCELEROMETER) {
            long curTime = System.currentTimeMillis();
            // only allow one update every 50ms, otherwise updates
            // come way too fast
            if (lastSensorUpdate == -1 || (curTime - lastSensorUpdate) > 50) {
                lastSensorUpdate = curTime;

                for (int i = 0; i < Totalcircles; i++) {
                    model[i].setAccel(values[DATA_X], values[DATA_Y]);
                }
            }
        }
    }
}

model.java

package com.stuffthathappens.games;

import java.util.concurrent.atomic.AtomicReference;

import android.os.Vibrator;

/**
 * This data model tracks the width and height of the playing field along 
 * with the current position of a ball. 
 */
public class BouncingBallModel {
    // the ball speed is meters / second. When we draw to the screen,
    // 1 pixel represents 1 meter. That ends up too slow, so multiply
    // by this number. Bigger numbers speeds things up.
    private final float pixelsPerMeter = 10;

    private final int ballRadius;

    // these are public, so make sure you synchronize on LOCK 
    // when reading these. I made them public since you need to
    // get both X and Y in pairs, and this is more efficient than
    // getter methods. With two getters, you'd still need to 
    // synchronize.
    public float ballPixelX, ballPixelY;

    private int pixelWidth, pixelHeight;

    // values are in meters/second
    private float velocityX, velocityY;

    // typical values range from -10...10, but could be higher or lower if
    // the user moves the phone rapidly
    private float accelX, accelY;

    /**
     * When the ball hits an edge, multiply the velocity by the rebound.
     * A value of 1.0 means the ball bounces with 100% efficiency. Lower
     * numbers simulate balls that don't bounce very much.
     */
    private static final float rebound = 0.8f;

    // if the ball bounces and the velocity is less than this constant,
    // stop bouncing.
    private static final float STOP_BOUNCING_VELOCITY = 2f;

    private volatile long lastTimeMs = -1;

    public final Object LOCK = new Object();

    private AtomicReference<Vibrator> vibratorRef =
        new AtomicReference<Vibrator>();

    public BouncingBallModel(int ballRadius) {
        this.ballRadius = ballRadius;
    }

    public void setAccel(float ax, float ay) {
        synchronized (LOCK) {
            this.accelX = ax;
            this.accelY = ay;
        }
    }

    public void setSize(int width, int height) {
        synchronized (LOCK) {
            this.pixelWidth = width;
            this.pixelHeight = height;
        }
    }

    public int getBallRadius() {
        return ballRadius;
    }

    /**
     * Call this to move the ball to a particular location on the screen. This
     * resets the velocity to zero, but the acceleration doesn't change so
     * the ball should start falling shortly.
     */
    public void moveBall(int ballX, int ballY) {
        synchronized (LOCK) {
            this.ballPixelX = ballX;
            this.ballPixelY = ballY;
            velocityX = 0;
            velocityY = 0;
        }
    }

    public void updatePhysics() {
        // copy everything to local vars (hence the 'l' prefix)
        float lWidth, lHeight, lBallX, lBallY, lAx, lAy, lVx, lVy;
        synchronized (LOCK) {
            lWidth = pixelWidth;
            lHeight = pixelHeight;
            lBallX = ballPixelX;
            lBallY = ballPixelY;
            lVx = velocityX;            
            lVy = velocityY;
            lAx = accelX;
            lAy = -accelY;
        }


        if (lWidth <= 0 || lHeight <= 0) {
            // invalid width and height, nothing to do until the GUI comes up
            return;
        }


        long curTime = System.currentTimeMillis();
        if (lastTimeMs < 0) {
            lastTimeMs = curTime;
            return;
        }

        long elapsedMs = curTime - lastTimeMs;
        lastTimeMs = curTime;

        // update the velocity
        // (divide by 1000 to convert ms to seconds)
        // end result is meters / second
        lVx += ((elapsedMs * lAx) / 1000) * pixelsPerMeter;
        lVy += ((elapsedMs * lAy) / 1000) * pixelsPerMeter;

        // update the position
        // (velocity is meters/sec, so divide by 1000 again)
        lBallX += ((lVx * elapsedMs) / 1000) * pixelsPerMeter;
        lBallY += ((lVy * elapsedMs) / 1000) * pixelsPerMeter;

        boolean bouncedX = false;
        boolean bouncedY = false;

        if (lBallY - ballRadius < 0) {
            lBallY = ballRadius;
            lVy = -lVy * rebound;
            bouncedY = true;
        } else if (lBallY + ballRadius > lHeight) {
            lBallY = lHeight - ballRadius;
            lVy = -lVy * rebound;
            bouncedY = true;
        }
        if (bouncedY && Math.abs(lVy) < STOP_BOUNCING_VELOCITY) {
            lVy = 0;  
            bouncedY = false;
        }

        if (lBallX - ballRadius < 0) {
            lBallX = ballRadius;
            lVx = -lVx * rebound;
            bouncedX = true;
        } else if (lBallX + ballRadius > lWidth) {
            lBallX = lWidth - ballRadius;
            lVx = -lVx * rebound;
            bouncedX = true;
        }
        if (bouncedX && Math.abs(lVx) < STOP_BOUNCING_VELOCITY) {
            lVx = 0;
            bouncedX = false;
        }


        // safely copy local vars back to object fields
        synchronized (LOCK) {
            ballPixelX = lBallX;
            ballPixelY = lBallY;

            velocityX = lVx;
            velocityY = lVy;
        }

        if (bouncedX || bouncedY) {
            Vibrator v = vibratorRef.get();
            if (v != null) {
                v.vibrate(20L);
            }
        }
    }

    public void setVibrator(Vibrator v) {
        vibratorRef.set(v);
    }
}

Logcat error:

 FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.stuffthathappens.games/com.stuffthathappens.games.BouncingBallActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2194)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2229)
    at android.app.ActivityThread.access$600(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1261)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:4945)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at com.stuffthathappens.games.BouncingBallActivity.onCreate(BouncingBallActivity.java:52)
    at android.app.Activity.performCreate(Activity.java:4531)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)

解决方案

You can declare you array like this:

private BouncingBallModel[] model = new BouncingBallModel[50]; 

like the following

How to declare an array in Java?

这篇关于无法添加到圈子帆布动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆