I'm developing a game for android, and I've been trying to implement a dialog to show a webview for web banner ads. (I'm using cocos2d for my development). Im using the static method ads() to open the dialog statically. Since doing this, however, I've started having problems launching.
On first launch, it runs fine, but when the app is closed and reopened, the "openscreen" scene starts but then doesn't play run its fade in and fade outs or continue into the menu scene.
Activity (where the ads() method is)
package wingdev.defence;
import java.util.Timer;
import java.util.TimerTask;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
public class DefenceActivity extends Activity{
protected CCGLSurfaceView _glSurfaceView;
public static int highscore = 0;
public static int mode= Activity.MODE_PRIVATE;
public static SharedPreferences mySharedPreferences ;
public static String CurrentLevel = "";
public static boolean firstlaunch=true;
public static int screenforchoice = 0;
public static boolean choicemade=false;
public static boolean choice=false;
public static DefenceActivity context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
_glSurfaceView = new CCGLSurfaceView(this);
setContentView(_glSurfaceView);
CCScene scene = OpenScreen.scene();
CCDirector.sharedDirector().runWithScene(scene);
}
#Override
public void onStart()
{
super.onStart();
CCDirector.sharedDirector().attachInView(_glSurfaceView);
CCDirector.sharedDirector().setDeviceOrientation(CCDirector.kCCDeviceOrientationLandscapeLeft);
CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
mySharedPreferences=getSharedPreferences("HighScore",mode);
highscore= mySharedPreferences.getInt("HighScore",0);
SharedPreferences.Editor editor= mySharedPreferences.edit();
editor.remove("HighScore");
editor.putInt("HighScore", highscore);
editor.commit();
CCScene scene = OpenScreen.scene();
CCDirector.sharedDirector().runWithScene(scene);
Config.context = this;
context = this;
}
public void startgame()
{
CCDirector.sharedDirector().attachInView(_glSurfaceView);
CCDirector.sharedDirector().setDeviceOrientation(CCDirector.kCCDeviceOrientationLandscapeLeft);;
CCDirector.sharedDirector().setAnimationInterval(1.0f / 60.0f);
CCScene scene = GameLayerSurvival.scene();
CCDirector.sharedDirector().runWithScene(scene);
}
#Override
public void onPause()
{
super.onPause();
CCDirector.sharedDirector().pause();
}
#Override
public void onResume()
{
super.onResume();
}
#Override
public void onStop()
{
super.onStop();
finish();
CCDirector.sharedDirector().end();
}
static public void newhighscore()
{if(GameLayerSurvival.score>highscore){
highscore=GameLayerSurvival.score;
}
SharedPreferences.Editor editor= mySharedPreferences.edit();
editor.remove("HighScore");
editor.putInt("HighScore", highscore);
editor.commit();
}
public static void ads(){
context.runOnUiThread(new Runnable() {
public void run() {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.main);
dialog.setTitle("Advert");
dialog.setCancelable(true);
WebView mWebView = (WebView) dialog.findViewById(R.id.webbanner);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.example.co.uk/");
Button bc_btn1 = (Button) dialog.findViewById(R.id.button1);
bc_btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
killDialog(dialog);
}
});
dialog.show();
}
});
}
public static void killDialog(Dialog dialog){
dialog.cancel();
}
}
Openscreen- the first scene used on launch
package wingdev.defence;
import org.cocos2d.actions.instant.CCCallFunc;
import org.cocos2d.actions.interval.CCDelayTime;
import org.cocos2d.actions.interval.CCFadeIn;
import org.cocos2d.actions.interval.CCFadeOut;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor4B;
public class OpenScreen extends CCColorLayer {
CCLabel _start;
CCLabel _easy;
CCLabel _normal;
CCLabel _highscore;
CCLabel _howto;
CCLabel _hard;
CCLabel _reset;
CCSprite wingdev = CCSprite.sprite("wingdevpresents.png");
CCSprite darkorange = CCSprite.sprite("PirateTea.png");
CCSprite plane = CCSprite.sprite("plane.png");
CCSprite back2 = CCSprite.sprite("black.png");
public static CCScene scene()
{
//
CCScene scene = CCScene.node();
CCColorLayer layer = new OpenScreen(ccColor4B.ccc4(255, 255, 255, 255));
scene.addChild(layer);
return scene;
}
protected OpenScreen(ccColor4B color) {
super(color);
CGSize winSize = CCDirector.sharedDirector().displaySize();
this.setIsTouchEnabled(true);
back2.setPosition(winSize.width / 2.0f, winSize.height / 2.0f);
back2.setScaleX(winSize.width / back2.getContentSize().width);
back2.setScaleY(winSize.height / back2.getContentSize().height);
addChild(back2);
wingdev.setPosition(winSize.width / 2.0f, winSize.height / 2.0f);
wingdev.setScaleX(winSize.width / wingdev.getContentSize().width);
wingdev.setScaleY(winSize.height / wingdev.getContentSize().height);
addChild(wingdev);
wingdev.runAction(CCSequence.actions(CCFadeIn.action(1.0f),CCDelayTime.action(2.0f),CCFadeOut.action(1.0f), CCCallFunc.action(this,"openscreen2")));
}
public void openscreen()
{
CCDirector.sharedDirector().replaceScene(Menu.scene());
}
public void openscreen2(){
CGSize winSize = CCDirector.sharedDirector().displaySize();
removeChild(wingdev,true);
darkorange.setPosition(winSize.width / 2.0f, winSize.height / 2.0f);
darkorange.setScaleX(winSize.width / darkorange.getContentSize().width);
darkorange.setScaleY(winSize.height / darkorange.getContentSize().height);
addChild(darkorange);
darkorange.runAction(CCSequence.actions(CCFadeIn.action(1.0f),CCDelayTime.action(2.0f),CCFadeOut.action(1.0f),CCCallFunc.action(this,"openscreen")));
}
}
Any help in understanding where I'm going wrong would be very appreciated!
You pause your CCDirector in
#Override
public void onPause()
{
super.onPause();
CCDirector.sharedDirector().pause();
}
I think you need to start it again in onResume()
#Override
public void onResume()
{
super.onResume();
CCDirector.sharedDirector().resume();
}
onStart() won't get called if the app is not killed.
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
Related
I'm facing an issue regarding cameraview. Do I have to import something since the error goes "cannot resolve flurgle" for import com.flurgle.camerakit.CameraView;
My permissions in manifest file are already set.
Heres the code using cameraview(taken from "https://blog.mindorks.com/android-tensorflow-machine-learning-example-ff0e9b2654cc.html" )
package com.example.mujtaba.basicai.Machine_Learning;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mujtaba.basicai.R;
import com.flurgle.camerakit.CameraListener;
import com.flurgle.camerakit.CameraView;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ImageRecognition extends AppCompatActivity {
private static final int INPUT_SIZE = 224;
private static final int IMAGE_MEAN = 117;
private static final float IMAGE_STD = 1;
private static final String INPUT_NAME = "input";
private static final String OUTPUT_NAME = "output";
private static final String MODEL_FILE = "file:///android_asset/tensorflow_inception_graph.pb";
private static final String LABEL_FILE =
"file:///android_asset/imagenet_comp_graph_label_strings.txt";
private Classifier classifier;
private Executor executor = Executors.newSingleThreadExecutor();
private TextView textViewResult;
private Button btnDetectObject, btnToggleCamera;
private ImageView imageViewResult;
private cameraView cameraView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_recognition);
cameraView = (CameraView) findViewById(R.id.cameraView);
imageViewResult = (ImageView) findViewById(R.id.imageViewResult);
textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setMovementMethod(new ScrollingMovementMethod());
btnToggleCamera = (Button) findViewById(R.id.btnToggleCamera);
btnDetectObject = (Button) findViewById(R.id.btnDetectObject);
cameraView.setCameraListener(new CameraListener() {
#Override
public void onPictureTaken(byte[] picture) {
super.onPictureTaken(picture);
Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
bitmap = Bitmap.createScaledBitmap(bitmap, INPUT_SIZE, INPUT_SIZE, false);
imageViewResult.setImageBitmap(bitmap);
final List<Classifier.Recognition> results = classifier.recognizeImage(bitmap);
textViewResult.setText(results.toString());
}
});
btnToggleCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.toggleFacing();
}
});
btnDetectObject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.captureImage();
}
});
initTensorFlowAndLoadModel();
}
#Override
protected void onResume() {
super.onResume();
cameraView.start();
}
#Override
protected void onPause() {
cameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
executor.execute(new Runnable() {
#Override
public void run() {
classifier.close();
}
});
}
private void initTensorFlowAndLoadModel() {
executor.execute(new Runnable() {
#Override
public void run() {
try {
classifier = TensorFlowImageClassifier.create(
getAssets(),
MODEL_FILE,
LABEL_FILE,
INPUT_SIZE,
IMAGE_MEAN,
IMAGE_STD,
INPUT_NAME,
OUTPUT_NAME);
makeButtonVisible();
} catch (final Exception e) {
throw new RuntimeException("Error initializing TensorFlow!", e);
}
}
});
}
private void makeButtonVisible() {
runOnUiThread(new Runnable() {
#Override
public void run() {
btnDetectObject.setVisibility(View.VISIBLE);
}
});
}
}
something is wrong with it
package com.sahandxx3.Countries;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
/**
* Created by Setude on 17-Dec-15.
*/
public class Setting extends Activity {
SharedPreferences sh;
TextView txtflag,txt_test;
SeekBar sbflag;
int progress = 10;
float size=10;
float txt_size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
init();
txtflag.setText("Flag size : "+sbflag.getProgress());
sbflag.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
txt_size=sh.getFloat("size",0);
progress= i;
size=(progress*5)+5;
txtflag.setText("Flag size : "+progress);
txt_test.setTextSize(size);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
txtflag.setText("Flag size : "+progress);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
txtflag.setText("Flag size : "+progress);
sh=PreferenceManager.getDefaultSharedPreferences(Setting.this);
SharedPreferences.Editor edit=sh.edit();
edit.putFloat("size",size);
edit.commit();
}
});
}
private void init() {
txtflag= (TextView) findViewById(R.id.txtflag);
sbflag= (SeekBar) findViewById(R.id.sbflag);
txt_test= (TextView) findViewById(R.id.btn_test);
}
}
so my problem is with this line:
txt_size=sh.getFloat("size",0);
When I try to change the seekbar,It stops working.
then I want to use txt_size in txt_test();
My best guess is that your SharedPreferences instance sh is null at the moment you try to access it. Try to move sh=PreferenceManager.getDefaultSharedPreferences(Setting.this); to your onCreate().
Put below code on onCreate():
sh=PreferenceManager.getDefaultSharedPreferences(Setting.this);
Your onCreate() method should looks like below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
sh=PreferenceManager.getDefaultSharedPreferences(Setting.this);
..
..
}
Hope this will help you.
I think you should use
float size=10f;
txt_size=sh.getFloat("size",0f);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting);
sh=PreferenceManager.getDefaultSharedPreferences(this);
}
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.........
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));
}
}
When I run my application on the emulator, it run right and no problem happens. But when I run it on the phone, a problem appear "stop unexpectedly".
In my application:
The main activity (Background) can exchange to 4 activities: LivingRoom, DiningRoom, Wc, Garage. The problem "stop unexpectedly" just happens when i try to go to the DiningRoom activity.
This is my code :
1.Background
package com.example.background;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import at.abraxas.amarino.Amarino;
public class BackgroundActivity extends Activity {
private Button Wc, Dining_Room, Living_Room, Garage;
private Intent D_intent, L_intent, G_intent, W_intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Amarino.connect(this, DEVICE_ADDRESS);
Living_Room = (Button) findViewById(R.id.living);
//Living_Room.setBackgroundColor(Color.TRANSPARENT);
Living_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
L_intent = new Intent(view.getContext(), LivingRoom.class);
startActivityForResult(L_intent, 0);
}
});
Dining_Room = (Button) findViewById(R.id.dining);
// Dining_Room.setBackgroundColor(Color.TRANSPARENT);
Dining_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
D_intent = new Intent(view.getContext(), DiningRoom.class);
startActivityForResult(D_intent, 0);
}
});
Wc = (Button) findViewById(R.id.wc);
//Wc.setBackgroundColor(Color.TRANSPARENT);
Wc.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
W_intent = new Intent(view.getContext(), Wc.class);
startActivityForResult(W_intent, 0);
}
});
Garage = (Button) findViewById(R.id.garage);
// Garage.setBackgroundColor(Color.TRANSPARENT);
Garage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
G_intent = new Intent(view.getContext(), Garage.class);
startActivityForResult(G_intent, 0);
}
});
}
}
2.DiningRoom
package com.example.background;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ToggleButton;
import at.abraxas.amarino.Amarino;
public class DiningRoom extends Activity implements OnCheckedChangeListener, OnSeekBarChangeListener{
private static final String DEVICE_ADDRESS = "00:06:66:43:9B:56";
final int DELAY = 150;
ToggleButton button;
SeekBar seekbar1;
SeekBar seekbar2;
boolean light2;
int light1;
int fan;
long lastchange;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diningroom);
//back ve trang chinh
Button backhome = (Button) findViewById(R.id.D_backhome);
backhome.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
Amarino.connect(this, DEVICE_ADDRESS);
button = (ToggleButton) findViewById(R.id.Dbutton);
seekbar1 = (SeekBar) findViewById(R.id.Dseekbar1);
seekbar2 = (SeekBar) findViewById(R.id.Dseekbar2);
button.setOnCheckedChangeListener(this);
seekbar1.setOnSeekBarChangeListener(this);
seekbar2.setOnSeekBarChangeListener(this);
}
//---START----------------------------------------------------------------------------------------------
#Override
protected void onStart(){
super.onStart();
// load last state
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
light2 = pref.getBoolean("light2", true);
light1 = pref.getInt("light1", 0);
fan = pref.getInt("fan", 0);
button.setChecked(light2);
seekbar1.setProgress(light1);
seekbar2.setProgress(fan);
new Thread(){
public void run(){
try{
Thread.sleep(6000);
}catch (InterruptedException e) {}
update_light2();
update_light1_fan();
}
}.start();
}
//STOP--------------------------------------------------------------------------------
#Override
protected void onStop(){
super.onStop();
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean("light2", light2)
.putInt("light1", light1)
.putInt("fan", fan)
.commit();
Amarino.disconnect(this, DEVICE_ADDRESS);
}
//UPDATE LIGHT2--------------------------------------------------------------------------------
private void Update_Light2_State(final CompoundButton button){
light2 = button.isChecked();
update_light2();
}
private void update_light2(){
int a;
a = (light2 == true)? 255:0;
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'o', a);
}
//UPDATE LIGHT1 FAN-------------------------------------------------------------------------------------
private void Update_Light1_Fan_State(final SeekBar seekbar){
switch (seekbar.getId()){
case R.id.Dseekbar1:
light1 = seekbar.getProgress();
update_light1();
break;
case R.id.Dseekbar2:
fan = seekbar.getProgress();
update_fan();
break;
}
}
private void update_light1_fan(){
update_light1();
update_fan();
}
private void update_light1(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'p', light1);
}
private void update_fan(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'q', fan);
}
//---TRACE--------------------------------------------------------------------------------------
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (System.currentTimeMillis() - lastchange > DELAY ){
Update_Light2_State(button);
lastchange = System.currentTimeMillis();
}
}
#Override
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
if (System.currentTimeMillis() - lastchange > DELAY ){
Update_Light1_Fan_State(seekbar);
lastchange = System.currentTimeMillis();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekbar) {
lastchange = System.currentTimeMillis();
}
#Override
public void onStopTrackingTouch(SeekBar seekbar) {
Update_Light1_Fan_State(seekbar);
}
}
3.Logcat
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.background/com.example.background.DiningRoom}: java.lang.ClassCastException:
java.lang.Boolean
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2685)
at android.app.ActivityThread.access$2300(ActivityThread.java:126)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4633)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Boolean
at android.app.ContextImpl$SharedPreferencesImpl.getInt(ContextImpl.java:2721)
at com.example.background.DiningRoom.onStart(DiningRoom.java:80)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
at android.app.Activity.performStart(Activity.java:3781)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2642)
... 11 more
Force finishing activity com.example.background/.DiningRoom
Force finishing activity com.example.background/.BackgroundActivity
I also try to wrote another application similar to the above application. But I just have only 1 sub activity: DiningRoom, then it ran well on the phone.
The Background when I just have one sub activity
[CODE]
public class Test1Activity extends Activity {
private Button Dining_Room;
private Intent D_intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Dining_Room = (Button) findViewById(R.id.dining);
// Dining_Room.setBackgroundColor(Color.TRANSPARENT);
Dining_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
D_intent = new Intent(view.getContext(), Dining.class);
startActivityForResult(D_intent, 0);
}
});
}
}
[/CODE]
Careful reading of logcat reveals that:
Caused by: java.lang.ClassCastException: java.lang.Boolean
at android.app.ContextImpl$SharedPreferencesImpl.getInt(ContextImpl.java:2721)
at com.example.background.DiningRoom.onStart(DiningRoom.java:80)
This means, that shared preference was boolean instead of int on line 80.
PS: I develop lightweight dependency injection framework for android, and it already covers
loading / saving preferences. Just grab it here:
https://github.com/ko5tik/andject
I would guess that the value "light1" in your shared preferences was not saved as an integer (but as a boolean).
From the docs:
Throws ClassCastException if there is a preference with this name that
is not an int.