Starting new activity triggered by boolean in GameThread (android) - android

I am making a "Defend the castle" style android application. The game is complete, however I just need help closing my surfaceview and starting a new activity for when the the player has lost the game.
The condition for losing the game is just a boolean variable in my GameThread class. The variable is called "lost" and is by default set to false. When the life of the castle drops below 1, lost is set to true and a sound effect plays.
Ideally, I would like to stop the currently looping sound effects and open a new activity (which is already made and working) upon lost=true.
The main activity is as follows:
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
try {
mGameView.mThread.onTouch(event);
} catch(Exception e) {}
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
}
The surfaceview is created in this class called GameView:
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class GameView extends SurfaceView implements Callback {
Context mContext;
GameThread mThread;
public GameView(Context context) {
super(context);
this.mContext = context;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d(this.getClass().toString(), "in SurfaceChanged()");
}
//#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceCreated()");
mThread.running = true;
mThread.start();
}
//#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceDestroyed()");
boolean retry = true;
mThread.running = false;
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
GameThread.music.stop();
GameThread.groan1.stop();
GameThread.groan2.stop();
GameThread.walk.stop();
GameThread.music.release();
GameThread.groan1.release();
GameThread.groan2.release();
GameThread.walk.release();
GameThread.shoot.release();
}
}
}
The GameThread class contains all of the drawing, the logic and all a run method (below).
#Override
public void run() {
// check if condition here
if(lost){
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(mContext, LoseActivity.class);
mContext.startActivity(intent);
}
});
}
else{
if (running == true) {
while (running) {
Canvas c = null;
try {
c = mHolder.lockCanvas();
if (width == 0) {
width = c.getWidth();
height = c.getHeight();
player.x = 50;
player.y = 45;
}
synchronized (mHolder) {
long now = System.currentTimeMillis();
update();
draw(c);
ifps++;
if (now > (mLastTime + 1000)) {
mLastTime = now;
fps = ifps;
ifps = 0;
}
}
} finally {
if (c != null) {
mHolder.unlockCanvasAndPost(c);
}
}
}
}
}
The activity that I want to start is called LoseActivity.class. Thank you in advance for any and all help. If anybody needs any further code/explanations, I will be more than happy to post it.

Use runOnUiThread for starting Activity from Thread as:
Change your main Activity as:
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity,MainActivity.this);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
///your code.....
Change your GameView class as:
public class GameView extends SurfaceView implements Callback {
Context mContext;
Activity contextx;
GameThread mThread;
public GameView(Context context,Activity contextx) {
super(context);
this.mContext = context;
this.contextx=contextx;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//your code here..........
#Override
public void run() {
// check if condition here
if(lost){
contextx.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(contextx, LoseActivity.class);
contextx.startActivity(intent);
}
});
}
else{
//your code here.........

Related

Method loadVideoFromAsset must be called from UI thread

I am trying to implement 360 Video Viewer in my project but I am getting an error for the line:
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
This is the error
Method loadVideoFromAsset must be called from the UI thread, currently inferred
thread is worker
Following is my code:
package com.example.jal.jp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import com.google.vr.sdk.widgets.video.VrVideoEventListener;
import com.google.vr.sdk.widgets.video.VrVideoView;
import java.io.IOException;
public abstract class VR_Video extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private VrVideoView mVrVideoView;
private SeekBar mSeekBar;
private Button mVolumeButton;
private boolean mIsPaused;
private boolean mIsMuted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vr__video);
initViews();
}
public void onPlayPausePressed() {
}
public void onVolumeToggleClicked() {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
class VideoLoaderTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
return true;
}
}
public void playPause() {
}
#Override
protected void onPause() {
super.onPause();
mVrVideoView.pauseRendering();
mIsPaused = true;
}
#Override
protected void onResume() {
super.onResume();
mVrVideoView.resumeRendering();
mIsPaused = false;
}
#Override
protected void onDestroy() {
mVrVideoView.shutdown();
super.onDestroy();
}
private class ActivityEventListener extends VrVideoEventListener {
#Override
public void onLoadSuccess() {
super.onLoadSuccess();
}
#Override
public void onLoadError(String errorMessage) {
super.onLoadError(errorMessage);
}
#Override
public void onClick() {
super.onClick();
}
#Override
public void onNewFrame() {
super.onNewFrame();
}
#Override
public void onCompletion() {
super.onCompletion();
}
}
}
Please help. I tried my best but couldn't fix.
Remove AsyncTask Implementation And Call Required Methods From UI Thread
Use Below Code :
private void initViews() {
mVrVideoView = (VrVideoView) findViewById(R.id.video_view);
mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
mVolumeButton = (Button) findViewById(R.id.btn_volume);
mVrVideoView.setEventListener(new ActivityEventListener());
try {
VrVideoView.Options options = new VrVideoView.Options();
options.inputType = VrVideoView.Options.TYPE_MONO;
mVrVideoView.loadVideoFromAsset("sea.mp4", options);
} catch( IOException e ) {
//Handle exception
}
mSeekBar.setOnSeekBarChangeListener(this);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onVolumeToggleClicked();
}
});
}
I dont know much about videoview but I show in your code that you are trying to access some the features in doInbackground method. The doINbackground method runs on a separate thread from the UI thread so that complex ant time consuming tasks do not block the UI thread. You can implement the features you are implementing in doINbackground method in the onCreate method or if you still need to use doInbackground you can access the UI thread inside doInbackground using runOnUiThread as follows
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});

Android: surfaceView can't resume activity from pause()

I am testing surfaceView, basically the app jsut changes the color of the background.
The app starts with no issue but when I "pause" the activity and "resume" it, the app is blocked in the "pause()" method loop.
this is my code:
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class SurfaceViewTest extends Activity {
FastRenderView renderView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surface_view_test);
renderView= new FastRenderView(this);
setContentView(renderView);
}
protected void onResume() {
super.onResume();
renderView.resume();
}
#Override
protected void onPause() {
super.onPause();
renderView.pause();
}
public class FastRenderView extends SurfaceView implements Runnable {
Thread renderThread=null;
SurfaceHolder holder;
volatile boolean running=false;
Random rand= new Random(); //random number creator----
public FastRenderView(Context context) {
super(context);
holder=getHolder(); //<<-check the this statement
}
public void resume() {
Log.d("ZR", "in resume");
running=true;
renderThread=new Thread(this);
renderThread.start(); //<<<--AVVIA IL THREAD
}
#Override
public void run() {
Log.d("ZR", "in running");
while(running){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!holder.getSurface().isValid())
continue;
Canvas canvas = holder.lockCanvas();
canvas.drawRGB(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
holder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
running = false;
Log.d("ZR", "in pause");
while(true){ //<<<<<<<<<<<<<<CHECKKKKKK
try {
renderThread.join();
Log.d("ZR", "in pause end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
The while(true) loop without a break in it will never stop in method pause(). I would expect something like a return after succesfully joined the rendering thread (waited till it ended)
With your volatile declaration of running the while-loop in run() should be ok.

Delay after the splash screen

My problem is, if I set my splash as a Dialog by adding this line in the manifest there's a delay: android:theme="#android:style/Theme.Holo.Dialog.NoActionBar"
After the splash screen disappears it takes around 6 seconds or more to the main activity to appear.
How can I make this delay disappear?
Splash code:
public class SplashActivity extends Activity {
private final int DURATION = 3000;
private Thread mSplashThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mSplashThread = new Thread() {
#Override
public void run() {
synchronized (this) {
try {
wait(DURATION);
} catch (InterruptedException e) {
} finally {
finish();
Intent intent = new Intent(getBaseContext(),
MainActivity.class);
startActivity(intent);
}
}
}
};
mSplashThread.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (mSplashThread) {
mSplashThread.notify();
}
}
return true;
}
}
Rather than using splash as dialogue you can do all your background work in a splash screen activity and then start your main activity..if you need dialogue animation then you can use animation like this.
overridePendingTransition( R.anim.come_up, R.anim.go_down );
By this you can manage your activity switching time.
i am not sure that this answer is appropriate but i have done it like this :
#Override
public void run()
{
// TODO Auto-generated method stub
startActivity( new Intent ( SplashActivity.this , MainActivity.class ) ) ;
}
#Override
protected void onStart()
{
super.onStart();
if(!isClosed)
splashHandler.postDelayed(this, "putYourTimeHere");
}
This is working for me at its best..
final int splashTimeOut = 3000;
Thread splashThread = new Thread(){
int wait = 0;
#Override
public void run() {
try {
super.run();
while(wait < splashTimeOut){
sleep(100);
wait += 100;
}
} catch (Exception e) {
}finally{
startActivity(new Intent(SplashScreen.this,LoginActivity.class));
finish();
}
}
};
splashThread.start();
this is the code for splashscreen display with some time delay
..
here set splash image in drawable in splash_screen.xml.
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class SplashScreen extends Activity {
LocationManager locationManager;
String provider, formattedDate, imeid;
double lat, lon;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_screen);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formattedDate = df.format(c.getTime());
new Handler().postDelayed(new Runnable() {
public void run() {
Log.i("JO", "run");
Intent in = new Intent(SplashScreen.this,SecondActivity.class);
//in.putExtra("refreshclick", clickRefreshButton);
//in.putExtra("Current_Date", formattedDate);
// in.putExtra("ImeiId", imeid);
//Log.i("JO", "Current_Date"+formattedDate+";
ImeiId"+imeid+";lat"+lat+"lon"+lon);
startActivity(in);
finish();
}
}, 1000);
}
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, DURATION);
}

Need help fixing my class: 'This Handler class should be static or leaks might occur'

I created a simple crossfade image class for use in my app. But... i have an error i can't fix due to lack of knowledge. I found this post This Handler class should be static or leaks might occur: IncomingHandler but i have no clue how to fix this in my class. It is a very straightforward class. Create, initialize and start to use it.
I hope someone can help me fix this warning and while we are at it, some hints and tips on my code or comments are very welcome too ;)
MainActivity.java
package com.example.crossfadeimage;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
Xfade xfade = new Xfade();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// INIT(current activity, image id's, time between fades, fade speed)
xfade.init(this, new int[]{ R.id.image1, R.id.image2, R.id.image3 }, 3000, 500);
xfade.start();
}
}
Xfade.java
package com.example.crossfadeimage;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
public class Xfade {
private Activity activity;
// Handler
private Handler handlerTimer = new Handler();
private static final int UPDATE_STUFF_ON_DIALOG = 999;
private int updateTime;
private Animation fadeIn;
private Animation fadeOut;
public int[] xfadeImages;
public int xfadeCounter = 1;
public void init(Activity thisActivity, int[] images, int time,
int animationSpeed) {
activity = thisActivity;
xfadeImages = images;
updateTime = time;
// Set Animations
fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(animationSpeed);
fadeOut = new AlphaAnimation(1, 0);
fadeOut.setDuration(animationSpeed);
// Hide all images except the first
// which is always visible
for (int image = 1; image < xfadeImages.length; image++) {
ImageView thisImage = (ImageView) activity
.findViewById(xfadeImages[image]);
thisImage.setVisibility(4);
}
}
public void start() {
handlerTimer.removeCallbacks(taskUpdateStuffOnDialog);
handlerTimer.postDelayed(taskUpdateStuffOnDialog, updateTime);
}
private Runnable taskUpdateStuffOnDialog = new Runnable() {
public void run() {
Message msg = new Message();
msg.what = UPDATE_STUFF_ON_DIALOG;
handlerEvent.sendMessage(msg);
// Repeat this after 'updateTime'
handlerTimer.postDelayed(this, updateTime);
}
};
private Handler handlerEvent = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_STUFF_ON_DIALOG: {
crossFade();
}
break;
default: {
super.handleMessage(msg);
}
break;
}
}
};
public void crossFade() {
if (xfadeCounter == 0) {
ImageView lastImage = (ImageView) activity
.findViewById(xfadeImages[xfadeImages.length - 1]);
lastImage.setVisibility(4);
}
if (xfadeCounter < xfadeImages.length) {
ImageView thisImage = (ImageView) activity
.findViewById(xfadeImages[xfadeCounter]);
thisImage.setVisibility(0);
thisImage.startAnimation(fadeIn);
xfadeCounter++;
} else {
// Hide all images except the first
// before fading out the last image
for (int image = 1; image < xfadeImages.length; image++) {
ImageView thisImage = (ImageView) activity
.findViewById(xfadeImages[image]);
thisImage.setVisibility(4);
}
// Fadeout
ImageView lastImage = (ImageView) activity
.findViewById(xfadeImages[xfadeImages.length - 1]);
lastImage.startAnimation(fadeOut);
// LastImage is faded to alpha 0 so it doesn't have to be hidden
// anymore
xfadeCounter = 1;
}
}
}
This allows you to modify views and have your handler set to static.
package com.testing.test;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity implements Runnable {
private static final int THREAD_RESULT = 1000;
private TextView mTextView;
private static Handler mHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
}
#Override
protected void onResume() {
super.onResume();
mHandler = new CustomHandler(this);
new Thread(this).start();
}
#Override
public void run() {
// Do some threaded work
// Tell the handler the thread is finished
mHandler.post(new Runnable() {
#Override
public void run() {
mHandler.sendEmptyMessage(THREAD_RESULT);
}
});
}
private class CustomHandler extends Handler {
private MainActivity activity;
public CustomHandler(MainActivity activity) {
super();
this.activity = activity;
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case THREAD_RESULT:
activity.mTextView.setText("Success!");
break;
}
}
}
}

I want to change from an xml layout to surfaceview using java

OK so I'm using xml to set this menu which is supported by the following java code
package starting.rt;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Menu extends Activity implements OnClickListener{
View.OnTouchListener gestureListener;
TextView display;
Button begin;
Button random;
Button game;
TextView counter;
Button next;
Button previous;
Button moreapps;
Button rate;
Random myRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(starting.rt.R.layout.menu);
begin = (Button) findViewById(starting.rt.R.id.Begin);
random = (Button) findViewById(starting.rt.R.id.Random);
display = (TextView) findViewById(starting.rt.R.id.tvResults);
counter = (TextView) findViewById(starting.rt.R.id.tvCounter);
next = (Button) findViewById(starting.rt.R.id.Next);
previous = (Button) findViewById(starting.rt.R.id.Previous);
moreapps = (Button)findViewById(R.id.More);
rate = (Button) findViewById(R.id.rate);
game = (Button) findViewById(R.id.game);
// display.setOnTouchListener(this.gestureListener);
begin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.RelationshipTipsActivity");
startActivity(openStartingPoint);
}});
moreapps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:\"Wompa\""));
startActivity(goToMarket);
}});
game.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.GameView");
startActivity(openStartingPoint);
}});
rate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);
}});}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Now what's supposed to be happening is when they click on the game which starts a new java class called GameView it crashes on clicked. Every other button works.
This is the code from GameView
package starting.rt;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread gameLoopThread;
private List<Sprite> sprites = new ArrayList<Sprite>();
private List<TempSprite> temps = new ArrayList<TempSprite>();
private long lastClick;
private Bitmap bmpBlood;
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameLoopThread.setRunning(false);
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.bad1));
// sprites.add(createSprite(R.drawable.bad2));
// sprites.add(createSprite(R.drawable.bad3));
// sprites.add(createSprite(R.drawable.bad4));
// sprites.add(createSprite(R.drawable.bad5));
// sprites.add(createSprite(R.drawable.bad6));
// sprites.add(createSprite(R.drawable.good1));
// sprites.add(createSprite(R.drawable.good2));
// sprites.add(createSprite(R.drawable.good3));
// sprites.add(createSprite(R.drawable.good4));
// sprites.add(createSprite(R.drawable.good5));
// sprites.add(createSprite(R.drawable.good6));
}
private Sprite createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 300) {
lastClick = System.currentTimeMillis();
float x = event.getX();
float y = event.getY();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isCollition(x, y)) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
break;
}
}
}
}
return true;
}
}
The GameView calls a few other classes for things part of the game but it crashes before it can start. I think it's crashing because it's switching from xml layout to the java surfaceview. Help would be appreciated :) Thanks!
First of all, you should always post in your questions the stacktrace with the exception from the Logcat if your app crashes.
You can't start a SurfaceView directly, instead your custom SurfaceView must be embedded in an Activity like any other view in android. For example:
public class GameViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(new GameView(this));
}
}

Categories

Resources