简体   繁体   中英

AlertDialog.Builder Error

I have following problem:

I copied this Code into my existing file.

if (mSensorX >= 5){


        AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
        builder1.setMessage("Write your message here.");
        builder1.setCancelable(true);
        builder1.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder1.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert11 = builder1.create();
        alert11.show();
    }

This is the code:

package de.example.baum_projekt_5_punkt_fix;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;

public class SimulationView extends View implements SensorEventListener {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Display mDisplay;

private Bitmap mGrass;
private Bitmap mHole;
private Bitmap mBitmap;
private static final int BALL_SIZE = 32;
private static final int HOLE_SIZE = 40;

private float mXOrigin;
private float mYOrigin;

private float mHorizontalBound;
private float mVerticalBound;    

private float mSensorX;
private float mSensorY;
private float mSensorZ;
private long mSensorTimeStamp;

private Particle mBall = new Particle();
private Context context;
private int onlyonetime;

public SimulationView(Context context) {
    super(context);

    WindowManager mWindowManager = (WindowManager)                                              
    context.getSystemService(Context.WINDOW_SERVICE);
    mDisplay = mWindowManager.getDefaultDisplay();

    mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    Bitmap ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
    mBitmap = Bitmap.createScaledBitmap(ball, BALL_SIZE, BALL_SIZE, true);

    Bitmap hole = BitmapFactory.decodeResource(getResources(), R.drawable.hole);
    mHole = Bitmap.createScaledBitmap(hole, HOLE_SIZE, HOLE_SIZE, true);

    Options opts = new Options();
    opts.inDither = true;
    opts.inPreferredConfig = Bitmap.Config.RGB_565;
    mGrass = BitmapFactory.decodeResource(getResources(), R.drawable.wald, opts);        
}

public void startSimulation() {
    mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}

public void stopSimulation() {
    mSensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
        return;

    switch (mDisplay.getRotation()) {
    case Surface.ROTATION_0:
        mSensorX = event.values[0];
        mSensorY = event.values[1];
        break;
    case Surface.ROTATION_90:
        mSensorX = -event.values[1];
        mSensorY = event.values[0];
        break;
    case Surface.ROTATION_180:
        mSensorX = -event.values[0];
        mSensorY = -event.values[1];
        break;
    case Surface.ROTATION_270:
        mSensorX = event.values[1];
        mSensorY = -event.values[0];
        break;
    }
    mSensorZ = event.values[2];
    mSensorTimeStamp = event.timestamp;


    if (mSensorX >= 5){


        AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
        builder1.setMessage("Write your message here.");
        builder1.setCancelable(true);
        builder1.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder1.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert11 = builder1.create();
        alert11.show();
    }

}

 @Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    mXOrigin = w * 0.5f;
    mYOrigin = h * 0.5f;

    mHorizontalBound = (w - BALL_SIZE) * 0.5f;
    mVerticalBound = (h - BALL_SIZE) * 0.5f;
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawBitmap(mGrass, 0, 0, null);
    canvas.drawBitmap(mHole, 100+mXOrigin - HOLE_SIZE/2,  100+ mYOrigin - HOLE_SIZE/2, null);

    mBall.updatePosition(mSensorX, mSensorY, mSensorZ, mSensorTimeStamp);
    mBall.resolveCollisionWithBounds(mHorizontalBound, mVerticalBound);

    canvas.drawBitmap(mBitmap, 100+(mXOrigin - BALL_SIZE/2) + mBall.mPosX, 100+(mYOrigin - BALL_SIZE/2) - mBall.mPosY, null);

    invalidate();
 }  

}

And the MainActivity:

package de.example.baum_projekt_5_punkt_fix;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;


public class MainActivity extends Activity {

private static final String TAG = "appsrox.example.accelerometer.MainActivity";
private MediaPlayer mp;
int media_length;

//private WakeLock mWakeLock;
private SimulationView mSimulationView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mp = MediaPlayer.create(this, R.raw.bgmusic);
    //PowerManager mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);
    //mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, TAG);
    mp.seekTo(0);
    mp.start();
    mSimulationView = new SimulationView(this);
    setContentView(mSimulationView);
}

@Override
protected void onResume() {
    super.onResume();
    //mWakeLock.acquire();
    mSimulationView.startSimulation();
    mp.seekTo(0);
    mp.start();

}

@Override
protected void onPause() {
    super.onPause();
    mSimulationView.stopSimulation();
    media_length = mp.getCurrentPosition();
    mp.pause();
    //mWakeLock.release();
}   

@Override
protected void onDestroy() {

    mp.release();

    super.onDestroy();
    //mWakeLock.release();
 }  
}

The App crash and i get this LogCat:

02-06 21:50:06.515: E/AndroidRuntime(3314): FATAL EXCEPTION: main
02-06 21:50:06.515: E/AndroidRuntime(3314): Process:   de.example.baum_projekt_5_punkt_fix, PID: 3314
02-06 21:50:06.515: E/AndroidRuntime(3314): java.lang.NullPointerException
02-06 21:50:06.515: E/AndroidRuntime(3314):     at     android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:143)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at android.app.AlertDialog$Builder.<init>(AlertDialog.java:360)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at de.example.baum_projekt_5_punkt_fix.SimulationView.onSensorChanged(SimulationView.java:106)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:474)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at android.os.MessageQueue.nativePollOnce(Native Method)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at android.os.MessageQueue.next(MessageQueue.java:138)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at android.os.Looper.loop(Looper.java:123)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at android.app.ActivityThread.main(ActivityThread.java:5356)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at java.lang.reflect.Method.invokeNative(Native Method)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at java.lang.reflect.Method.invoke(Method.java:515)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-06 21:50:06.515: E/AndroidRuntime(3314):     at dalvik.system.NativeStart.main(Native Method)

Have anyone an idea? I think there is a problem with "context" but i dont know how to fix it.

yours faithfully

You're not initializing your local 'context' variable. Since you initialize the builder with the local context, the builder instance is null and can't be used properly. In the constructor, add:

this.context = context;

That should take care of it.

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