Fatal Exception On going back to menu - java

So Im doing a little up, not a big deal, just learning graphics, but when i click on the back button, the app crashes and it gives me fatal error 11.
Code:
public class MyPachuSurface extends SurfaceView implements Runnable{
SurfaceHolder myHolder;
Thread myThread = null;
boolean isRunning = false;
public float x,y,startX,startY,finalX,finalY,dx,dy,tx,ty;
public MyPachuSurface(Context context)
{
super(context);
// TODO Auto-generated constructor stub
myHolder = getHolder();
this.x = 0;
this.y = 0;
this.startX = 0;
this.startY = 0;
this.finalX = 0;
this.finalY = 0;
this.dx = 0;
this.dy = 0;
this.tx = 0;
this.ty = 0;
}
public void pause()
{
isRunning = false;
try
{
myThread.join();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
myThread = null;
}
public void resume ()
{
isRunning = true;
myThread = new Thread(this);
myThread.start();
}
#Override
public void run()
{
// TODO Auto-generated method stub
while(isRunning)
{
if(!myHolder.getSurface().isValid())
continue;
Canvas canvas = myHolder.lockCanvas();
canvas.drawRGB(02, 02, 254);
if(this.x != 0 && this.y != 0)
{
Bitmap test = BitmapFactory.decodeResource(getResources(), R.drawable.plus1);
canvas.drawBitmap(test, this.x - test.getWidth()/2 - this.tx, this.y - test.getHeight()/2 - this.ty, null);
this.tx += this.dx/30;
this.ty += this.dy/30;
}
myHolder.unlockCanvasAndPost(canvas);
}
}
}
This is the view, and this is the activity :
public class MyGraphicsSurface extends Activity implements OnTouchListener{
MyPachuSurface pachuSurf;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
pachuSurf = new MyPachuSurface(this);
pachuSurf.setOnTouchListener(this);
setContentView(pachuSurf);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
pachuSurf.resume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
pachuSurf.resume();
}
#Override
public boolean onTouch(View v, MotionEvent event)
{
// TODO Auto-generated method stub
this.pachuSurf.x = event.getX();
this.pachuSurf.y = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
pachuSurf.startX = event.getX();
pachuSurf.startY = event.getY();
pachuSurf.tx = 0;
pachuSurf.ty = 0;
break;
case MotionEvent.ACTION_UP:
pachuSurf.finalX = event.getX();
pachuSurf.finalY = event.getY();
pachuSurf.dx = pachuSurf.finalX - pachuSurf.startX;
pachuSurf.dy = pachuSurf.finalY - pachuSurf.startY;
break;
}
return true;
}
}
And This is The Loc Cat:
06-06 17:37:20.104: E/AndroidRuntime(22781): FATAL EXCEPTION: Thread-29865
06-06 17:37:20.104: E/AndroidRuntime(22781): java.lang.NullPointerException
06-06 17:37:20.104: E/AndroidRuntime(22781): at com.example.myfirstapp.MyPachuSurface.run(MyPachuSurface.java:68)
06-06 17:37:20.104: E/AndroidRuntime(22781): at java.lang.Thread.run(Thread.java:856)

Related

seekbar using first 0.12 and 0.13 combination adding the value

seekbar using volume increment and decrement for 0.12 and 0.13 combination like 0.12,0.25,0.37,0.50,0.62,0.75,0.87 but i getting values like this 0.12,0.25,0.38,0.50,0.62,0.75,0.88 .Please suggest me how can i clear the issues.
public class MainActivity extends Activity {
Button b1;
SeekBar sk1;
double point=0.12;
double value=0.00;
int previous=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
sk1=(SeekBar) findViewById(R.id.seekBar1);
sk1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
// TODO Auto-generated method stub
int p = progress;
double f = progress;
double x = Double.parseDouble(b1.getText().toString());
if (point == 0.12)
{
if (previous > p)
{
if (x == -20.00 )
{
}
else {
float a = (float) (0.25 / 2 * 100) / 100;
f = value - a;
b1.setText(""+ String.format("%.2f",(f)));
value=f;
}
}
else if (previous < p)
{
if (x == 20.00)
{
}
else {
float a = (float) (0.25 / 2 * 100) / 100;
f = value + a;
b1.setText(""+ String.format("%.2f",(f)));
value=f;
}
}
}
previous = progress;
}
});
}

Error, if hide canvas-game

public class GameView extends SurfaceView
{
private GameThread mThread;
SurfaceHolder holder;
Bitmap fon = BitmapFactory.decodeResource(getResources(), R.drawable.fon);
ArrayList<Integer> lasers = new ArrayList<Integer>();
ArrayList<Integer> coordYlasers = new ArrayList<Integer>();
ArrayList<Integer> coordXlasers = new ArrayList<Integer>();
Bitmap laser = BitmapFactory.decodeResource(getResources(), R.drawable.laser);
int touchX = 0;
int touchY = 0;
int coordX = 0;
int coordY = 600;
int _coordX = 0;
private boolean running = false;
ArrayList<Bitmap> blocks = new ArrayList<Bitmap>();
public class GameThread extends Thread
{
private GameView view;
public GameThread(GameView view)
{
this.view = view;
}
public void setRunning(boolean run)
{
running = run;
}
public void run()
{
int i = 0;
while (running)
{
Canvas canvas = null;
try
{
canvas = view.getHolder().lockCanvas();
synchronized (view.getHolder())
{
onDraw(canvas);
}
}
catch (Exception e) { }
finally
{
if (canvas != null)
{
view.getHolder().unlockCanvasAndPost(canvas);
}
}
}
}
}
public GameView(Context context)
{
super(context);
mThread = new GameThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
mThread.setRunning(false);
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
mThread.setRunning(true);
mThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
});
}
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
_coordX = coordX;
X = (int) event.getX();
Y = (int) event.getY();
}
if(event.getAction() == MotionEvent.ACTION_MOVE)
{
touchX = ((int) event.getX());
touchY = (int) event.getY();
//if (Math.abs(touchX - X) > 10){
coordX = _coordX + (touchX - X);
invalidate();
//}
}
if(event.getAction() == MotionEvent.ACTION_UP)
{
_coordX = coordX;
Y = touchY;
}
return true;
}
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setTextSize(20);
canvas.drawColor(Color.WHITE);
canvas.drawBitmap(fon, 0, 0, null);
canvas.drawBitmap(player, coordX, coordY, null);
canvas.drawBitmap(laser, coordLaserX, coordLaserY, null);
for (int i = 1; i<coordYlasers.size(); ++i){
canvas.drawBitmap(laser, coordXlasers.get(i), coordYlasers.get(i), null);
}
canvas.drawText("" + V, 10, 25, paint);
}
}
Application is worked excellent, but....
If I hide app, game crashes. Help, please.
Logcat error.
5553-5553/com.example.thetronuo.pregame E/AndroidRuntime﹕ FATAL
EXCEPTION: main
java.lang.IllegalThreadStateException: Thread already started.
at java.lang.Thread.start(Thread.java:1045)
at com.example.thetronuo.pregame.GameView$1.surfaceCreated(GameView.java:161)
at android.view.SurfaceView.updateWindow(SurfaceView.java:569)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:231)
at android.view.View.dispatchWindowVisibilityChanged(View.java:7618)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1211)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4356)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5099)
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:803)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
at dalvik.system.NativeStart.main(Native Method)
It's activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GameView(this));
}
"wait()" - unhandled exception.
Where to write "resumeThread()"?
public class GameThread extends Thread
{
private GameView view;
private boolean pause = false;
private synchronized void check(){
while(pause){
wait();
}
}
public void pauseThread(){
pause = true;
}
public void resumeThread(){
pause = false;
notify();
}
public GameThread(GameView view)
{
this.view = view;
}
I think I had the same problem. But i fixed it.
Put a this in your Thread class:
private boolean pause = false;
private synchronized void check(){
while(pause){
wait();
}
}
public void pauseThread(){
pause = true;
}
public void resumeThread(){
pause = false;
notify();
}
And when onSurfaceDestroyed is called you need to pause the thread with the method youve created: pauseThread();
also call the method check(); in the while-loop, so:
while(true){
check();
... other code ...
}
and create a onResume() method in the activity class, so whenever the user turns back to the app, it will call this method automatically, and put this code into the method:
resumeThread();
I hope this would help you, im not sure if it is all the code you need as im not at home at the moment, if it doesnt work ill have a look and edit when im at home.

Null Pointer Exception with "getPackageName()"

I have been stuck on this problem for the past week and a half. I made a game using the "Kilobolt" framework, and I have been trying to implement in App Purchase's in my app and i've tried every way possible but I keep getting the same error, that there is a null pointer exception.
06-13 21:40:18.991: E/AndroidRuntime(16384): java.lang.NullPointerException
06-13 21:40:18.991: E/AndroidRuntime(16384): at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
I have 1 activity where I have my method levelTwoButtonClicked() and I am calling that method from a java class, this is where the null pointer exception is coming from and it is because of getPackageName().
I have this in a try catch statement:
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);.
I have done some research and I read that there could be a issue with the context and calling getPackageName() but havent been able to figure out the issue yet thanks for any one who can help me resolve this!
public abstract class AndroidGame extends Activity implements Game {
public static Context mContext;
IInAppBillingService mService;
ServiceConnection mServiceConn;
static final String ITEM_SKU = "android.test.purchased";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
int frameBufferWidth = isPortrait ? 480: 800;
int frameBufferHeight = isPortrait ? 800: 480;
Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
frameBufferHeight, Config.RGB_565);
float scaleX = (float) frameBufferWidth
/ getWindowManager().getDefaultDisplay().getWidth();
float scaleY = (float) frameBufferHeight
/ getWindowManager().getDefaultDisplay().getHeight();
renderView = new AndroidFastRenderView(this, frameBuffer);
graphics = new AndroidGraphics(getAssets(), frameBuffer);
fileIO = new AndroidFileIO(this);
audio = new AndroidAudio(this);
input = new AndroidInput(this, renderView, scaleX, scaleY);
screen = getInitScreen();
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(renderView);
setContentView(layout);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
mContext = getBaseContext();
mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
public void levelTwoButtonClicked(){
Assets.click.play(1.00f);
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("android.test.purchased");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
if (sku.equals("android.test.purchased")) {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (SendIntentException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1001) {
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString("android.test.purchased");
Toast.makeText(mContext,"You have bought the " + sku + ". Excellent choice,adventurer!", Toast.LENGTH_LONG).show();
}
catch (JSONException e) {
Toast.makeText(mContext,"Failed to parse purchase data.", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
}
public static Context getContext(){
return mContext;
}
#Override
public void onResume() {
super.onResume();
wakeLock.acquire();
screen.resume();
renderView.resume();
mAdView.resume();
if(Assets.mainmenuloop.isStopped()){
Assets.mainmenuloop.play();
}
}
#Override
public void onPause() {
super.onPause();
wakeLock.release();
renderView.pause();
screen.pause();
mAdView.pause();
if(Assets.mainmenuloop.isPlaying()){
Assets.mainmenuloop.stop();
}
SharedPreferences HighScoreData = getSharedPreferences("high", 0);
SharedPreferences.Editor editor = HighScoreData.edit();
editor.putInt("score", highScore);
editor.putInt("secondScore", secondHighScore);
editor.putInt("thirdScore", thirdHighScore);
editor.putInt("fourthScore", fourthHighScore);
editor.commit();
if (isFinishing())
screen.dispose();
}
#Override
public Input getInput() {
return input;
}
#Override
public FileIO getFileIO() {
return fileIO;
}
#Override
public Graphics getGraphics() {
return graphics;
}
#Override
public Audio getAudio() {
return audio;
}
#Override
public void onDestroy() {
super.onDestroy();
mAdView.destroy();
/*
if (mService != null) {
unbindService(mServiceConn);
}
*/
}
#Override
public void setScreen(Screen screen) {
if (screen == null)
throw new IllegalArgumentException("Screen must not be null");
this.screen.pause();
this.screen.dispose();
screen.resume();
screen.update(0);
this.screen = screen;
}
public Screen getCurrentScreen() {
return screen;
}
}
// END OF ACTIVITY CLASS
// BEGIN REGULAR JAVA CLASS
public class InAppPurchase extends Screen {
AndroidGame Buy = new PurchaseLevels();
public InAppPurchase(Game game) {
super(game);
}
#Override
public void update(float deltaTime) {
// TODO Auto-generated method stub
#SuppressWarnings("unused")
Graphics g = game.getGraphics();
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for(int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if(event.type == TouchEvent.TOUCH_UP) {
if(inBounds(event, 195, 142, 235, 55)) {
// UNLOCK LEVEL TWO
Buy.levelTwoButtonClicked();
}
if(inBounds(event, 195, 310, 235, 55)) {
// UNLOCK LEVEL THREE
}
if(inBounds(event, 195, 490, 235, 55)) {
// UNLOCK LEVEL FOUR
}
if(inBounds(event, 70, 630, 210, 55)) {
// RESTORE BUTTON
Assets.click.play(1.00f);
}
if(inBounds(event, 330, 635, 130, 130)) {
game.setScreen(new MainMenuScreen(game));
Assets.click.play(1.00f);
}
}
}
}
private boolean inBounds(TouchEvent event, int x, int y, int width,
int height) {
if (event.x > x && event.x < x + width - 1 && event.y > y
&& event.y < y + height - 1){
return true;
} else {
return false;
}
}
public void updateUI(){
}
#Override
public void paint(float deltaTime) {
// TODO Auto-generated method stub
}
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
#Override
public void backButton() {
// TODO Auto-generated method stub
}
}
// MAIN ACTIVITY SUBCLASS HAD TO MAKE THIS TO CREATE AN INSTANCE OF MY ABSTRACT MAIN ACTIVITY "ANDROIDGAME" IN MY IN APP PURCHASE CLASS, IN ORDER TO CALL "LEVELTWOBUTTONCLICKED"
public class PurchaseLevels extends AndroidGame {
#Override
public Screen getInitScreen() {
// TODO Auto-generated method stub
return null;
}
}

Not able to draw in my drawing ANDROID APP

I am developing an Android drawing app.
When I run this code it says application is doing too much work on it's main thread in logcat.I am not able to draw.PLEASE HELP ME.Thank you
THIS IS MY DRAWIT CLASS
public class Drawit extends Activity {
LinearLayout linearLayout;
ImageButton oclear,save,ocancel;
View mview;
DrawCanvas drawCanvas;
public static String tempDir;
public static String unique_id;
public static String current=null;
public Bitmap mBitmap;
public EditText yourName;
File myPath;
protected void onCreate(Bundle savedInsatnceState) {
// TODO Auto-generated method stub
super.onCreate(savedInsatnceState);
setContentView(R.layout.drawit);
linearLayout = (LinearLayout) findViewById(R.id.linearLayout11);
tempDir = Environment.getExternalStorageDirectory()+"/"+getResources().getString(R.string.external_dir);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory= contextWrapper.getDir(getResources().getString(R.string.external_dir),MODE_PRIVATE);
preparedirectory();
yourName = (EditText) findViewById(R.id.editText1);
myPath = new File(directory,current);
drawCanvas = new DrawCanvas(this, null);
drawCanvas.setBackgroundColor(Color.WHITE);
linearLayout.addView(drawCanvas,LayoutParams.FILL_PARENT);
}
}
THIS IS MY DRAW CANVAS METHOD
public class DrawCanvas extends View
{
public Paint paint = new Paint();
public Path path = new Path();
public final RectF dirtyRect = new RectF();
public float lastTouchX;
public float lastTouchY;
public DrawCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5f);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setAntiAlias(true);
}
protected void ondraw(Canvas canvas) {
canvas.drawPath(path,paint);
}
public void save(View mview) throws IOException{
// TODO Auto-generated method stub
if(mBitmap == null)
{
mBitmap = Bitmap.createBitmap(linearLayout.getWidth(),linearLayout.getHeight(),Bitmap.Config.RGB_565);
}
Canvas canvas = new Canvas(mBitmap);
try {
FileOutputStream fileoutputstream = new FileOutputStream(myPath);
mview.draw(canvas);
mBitmap.compress(Bitmap.CompressFormat.PNG , 90, fileoutputstream);
fileoutputstream.flush();
fileoutputstream.close();
String uri = Images.Media.insertImage(getContentResolver(),mBitmap,"title",null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void clear() {
// TODO Auto-generated method stub
path.reset();
invalidate();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
lastTouchX = eventX;
lastTouchY = eventY;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
resetDirtyRect(eventX,eventY);
int historyRectSize = event.getHistorySize();
for(int i=0;i<historyRectSize;i++)
{
float historicalx = event.getHistoricalX(i);
float historicaly = event.getHistoricalY(i);
expandDirtyRect(historicalx,historicaly);
path.lineTo(historicalx, historicaly);
}
break;
}
return true;
}
private void expandDirtyRect(float historicalx, float historicaly) {
// TODO Auto-generated method stub
if(historicalx < dirtyRect.left)
{
dirtyRect.left = historicalx;
} else if(historicalx >dirtyRect.right)
{
dirtyRect.left = historicalx;
}
if(historicaly < dirtyRect.top)
{
dirtyRect.top = historicaly;
} else if(historicaly >dirtyRect.bottom)
{
dirtyRect.bottom = historicaly;
}
}
private void resetDirtyRect(float eventX, float eventY) {
// TODO Auto-generated method stub
dirtyRect.left = Math.min(lastTouchX,eventX);
dirtyRect.right = Math.max(lastTouchX,eventX);
dirtyRect.top = Math.min(lastTouchY,eventY);
dirtyRect.bottom = Math.max(lastTouchY,eventY);
}
}
}

moving a ball with help of accelerometer in android

I had written a code to move a ball with the help of accelerometer in android such that if it touches any of 4 edges it reappears on opposide edge my problems are
1.ball is not reappearing on opposite edge
2.orientation changes to lanscape
here is my code
public class Accelerate extends Activity implements SensorEventListener {
float x, y, sensorX, sensorY, a, b, centerX, centerY;
Bitmap ball;
SensorManager sm;
NixSurface ourSurfaceView;
public class NixSurface extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public NixSurface(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause() {
isRunning = false;
while (true) {
try {
ourThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume() {
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawRGB(255, 255, 255);
centerX = canvas.getWidth() / 2;
centerY = canvas.getHeight() / 2;
x += sensorX;
y += sensorY;
a = centerX + x;
b = centerY + y;
if (a > canvas.getWidth())
a = 0;
if (b > canvas.getHeight())
b = 0;
if (a < 0)
a = canvas.getWidth();
if (b < 0)
b = canvas.getHeight();
canvas.drawBitmap(ball, a, b, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sm.getSensorList(Sensor.TYPE_ACCELEROMETER).size() != 0) {
Sensor s = sm.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
sm.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
}
x = y = sensorY = sensorX = 0;
ball = BitmapFactory.decodeResource(getResources(), R.drawable.nix);
ourSurfaceView = new NixSurface(this);
ourSurfaceView.resume();
setContentView(ourSurfaceView);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
sm.unregisterListener(this);
super.onStop();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
// nothing to do here
}
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sensorX = -event.values[0];
sensorY = event.values[1];
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
I guess your problem is that you assume that the sensor origin (x=0,y=0) is the screen center. The sensor origin is the top left corner of the screen (X pointing left and Y pointing down), so comparing a & b to canvas.getWidth() & canvas.getHeight() is not correct since you already added centerX & centerY. Also, negating sensorX will cause the condition a > canvas.getWidth() to never occur since X is never negative.

Categories