box2dlights not works in libgdx - android

I use https://github.com/libgdx/box2dlights in my game, But its not working,
I get the following error in eclipse
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.NoSuchMethodError: com.badlogic.gdx.graphics.glutils.FrameBuffer.getColorBufferTexture()Lcom/badlogic/gdx/graphics/GLTexture;
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Caused by: java.lang.NoSuchMethodError: com.badlogic.gdx.graphics.glutils.FrameBuffer.getColorBufferTexture()Lcom/badlogic/gdx/graphics/GLTexture;
at box2dLight.LightMap.render(LightMap.java:41)
at box2dLight.RayHandler.render(RayHandler.java:338)
at box2dLight.RayHandler.updateAndRender(RayHandler.java:269)
at com.mygdx.game.box2dTest.render(box2dTest.java:182)
at com.badlogic.gdx.Game.render(Game.java:46)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:207)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:114)
my java file is:
package com.mygdx.game;
import box2dLight.PointLight;
import box2dLight.RayHandler;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.FPSLogger;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
public class box2dTest implements Screen, InputProcessor {
MyGdxGame game;
OrthographicCamera camera;
World world;
Box2DDebugRenderer renderer;
float width,height;
FPSLogger logger;
Body circleBody;
RayHandler handler;
private TmxMapLoader maploader;
TiledMap map;
OrthogonalTiledMapRenderer maprenderer;
private Viewport gamePort;
public box2dTest(MyGdxGame game)
{
this.game=game;
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
//gamePort = new StretchViewport(MyGdxGame.V_WIDTH,MyGdxGame.V_HEIGHT,camera);
camera = new OrthographicCamera(600,440);
camera.position.set(0,220,0);
camera.update();
world = new World(new Vector2(0,-49.8f),false);
renderer = new Box2DDebugRenderer();
logger = new FPSLogger();
BodyDef circleDef = new BodyDef();
circleDef.type = BodyType.DynamicBody;
circleDef.position.set(width/2f,height/2f);
circleBody = world.createBody(circleDef);
CircleShape circleShape = new CircleShape();
circleShape.setRadius(13f);
FixtureDef circleFixture = new FixtureDef();
circleFixture.shape = circleShape;
circleFixture.density = 0.3f;
circleFixture.friction = 0.2f;
circleFixture.restitution = 0.0f;
circleBody.createFixture(circleFixture);
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(0,3);
Body groundBody = world.createBody(groundBodyDef);
PolygonShape groundBox = new PolygonShape();
groundBox.setAsBox((camera.viewportWidth)*2, 3.0f);
groundBody.createFixture(groundBox ,0.03f);
maploader = new TmxMapLoader();
map = maploader.load("f0c.tmx");
maprenderer = new OrthogonalTiledMapRenderer(map);
//-------grounds--------------------------------------------------------------
BodyDef bDef=new BodyDef();
Body body;
PolygonShape shape=new PolygonShape();
FixtureDef fDef = new FixtureDef();
for(MapObject object : map.getLayers().get(1).getObjects().getByType(RectangleMapObject.class))
{
Rectangle rect = ((RectangleMapObject) object).getRectangle();
bDef.type = BodyDef.BodyType.StaticBody;
bDef.position.set(rect.getX() + rect.getWidth()/2,rect.getY() + rect.getHeight()/2);
body = world.createBody(bDef);
shape.setAsBox(rect.getWidth()/2,rect.getHeight()/2);
fDef.shape=shape;
body.createFixture(fDef);
}
//---------------------------END OF GROUNDS-----------------------------
//--------BOX2D LIGHTS-----//
handler = new RayHandler(world);
handler.setCombinedMatrix(camera.combined);
new PointLight(handler, 5000, Color.CYAN, 100,( width/2)-50, (height/2)+15);
}
public void update(float dt)
{
HandleInput(dt);
camera.position.x = circleBody.getPosition().x;
camera.position.y = circleBody.getPosition().y;
camera.update();
maprenderer.setView(camera);
}
public void HandleInput(float dt)
{
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE) && circleBody.getLinearVelocity().y<10 && circleBody.getLinearVelocity().y>-14)
{
circleBody.applyLinearImpulse(new Vector2(0,19009),circleBody.getWorldCenter(), true);
}
if(Gdx.input.isKeyPressed(Input.Keys.A) && circleBody.getLinearVelocity().x<=122 || (Gdx.input.isTouched(0) && (Gdx.input.getX()>0 && Gdx.input.getX()<250)))
{
circleBody.applyLinearImpulse(new Vector2(-190,0),circleBody.getWorldCenter(), true);
}
if(Gdx.input.isKeyPressed(Input.Keys.D) && circleBody.getLinearVelocity().x>=-122 || (Gdx.input.isTouched(0) && (Gdx.input.getX()>550 && Gdx.input.getX()<840)))
{
circleBody.applyLinearImpulse(new Vector2(190,0),circleBody.getWorldCenter(), true);
}
}
#Override
public void render(float delta) {
Gdx.input.setInputProcessor(this);
update(delta);
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
maprenderer.render();
renderer.render(world, camera.combined);
//box2dlights
handler.updateAndRender();
//end
world.step(1/60f, 6, 2);
logger.log();
}
#Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void show() {
// TODO Auto-generated method stub
}
#Override
public void hide() {
// 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() {
world.dispose();
}
#Override
public boolean keyDown(int keycode) {
return false;
}
#Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(int X, int Y, int pointer, int button) {
if(X>250 && X<550 && circleBody.getLinearVelocity().y<10 && circleBody.getLinearVelocity().y>-14)
{
circleBody.applyLinearImpulse(new Vector2(0,19009),circleBody.getWorldCenter(), true);
}
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
}

I believe you have an old version of libGDX. Change gdxVersion field to gdxVersion = "1.7.0"in build.gradle in the root folder of your project.

Related

how to open another class by clicking on a button on libgdx? (android development eclipse)

I am making my own game. I have already made a splash screen and a main menu. I have made a button "Play" in my menu but I can't link it to my main game, while I can link it to other classes.
Here is the code of the class I can't open:
package com.mygdx.Papermadness.screens;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector2;
public class PaperMadness extends InputAdapter implements ApplicationListener, Screen {
float timer;
public static Preferences prefs;
public static int counter; // The variable you want to save
private BitmapFont font;
//public int counter = 0;
boolean touch = false;
SpriteBatch batch;
SpriteBatch spriteBatch;
Texture spriteTexture;
Sprite sprite;
float scrollTimer = 0.0f;
Player player;
Paper paper;
Huiz huiz;
Lijn lijn;
String money = String.valueOf(counter);
ShapeRenderer sr;
public boolean kukar = false;
public void create() {
font = new BitmapFont();
Gdx.input.setInputProcessor(this);
player = new Player(new Vector2(50, 100), new Vector2(100, 100));
huiz = new Huiz(new Vector2(200, 300), new Vector2(110, 110));
// huiz = new Huiz(new Vector2(200, 300), new Vector2(110, 110));
paper = new Paper(new Vector2(Gdx.input.getX(),
Gdx.graphics.getHeight() - Gdx.input.getY()), new Vector2(50,
50));
lijn = new Lijn(new Vector2(0, 200), new Vector2(600, 2));
// sr = new ShapeRenderer();
spriteBatch = new SpriteBatch();
spriteTexture = new Texture("b9.png");
spriteTexture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
sprite = new Sprite(spriteTexture);
sprite.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch = new SpriteBatch();
}
#Override
public void render(float delta) {
// bounds.set(Gdx.input.getX(),
// Gdx.graphics.getHeight() - Gdx.input.getY(),
// secondTexture.getWidth(), secondTexture.getHeight());
scrollTimer += Gdx.graphics.getDeltaTime();
if (scrollTimer > 1.0f)
scrollTimer = 0.0f;
sprite.setV(scrollTimer + 2);
sprite.setV2(scrollTimer);
player.update();
paper.update();
lijn.update();
huiz.update();
/*
* if (tree.getBounds().overlaps(ball.getBounds())) {
* System.out.println("Swendley Programinateur"); }
*
* if (tree.getBounds().overlaps(paper.getBounds())) {
* System.out.println("Souk Programinateur"); }
*/
spriteBatch.begin();
sprite.draw(spriteBatch);
spriteBatch.end();
batch.begin();
player.draw(batch);
huiz.draw(batch);
// paper.draw(batch);
if (Gdx.graphics.getHeight() / 1.25 < Gdx.input.getY()
&& Gdx.graphics.getWidth() / 2.7 < Gdx.input.getX()
&& Gdx.graphics.getWidth() / 1.7 > Gdx.input.getX()
&& Gdx.input.isTouched() && kukar == false && touch == false) {
kukar = true;
touch = true;
} else if (Gdx.input.isTouched() && kukar == true && touch == true) {
paper.draw(batch);
if (paper.getBounds().overlaps(huiz.getBounds())
|| paper.getBounds().overlaps(huiz.getBounds1())) {
// System.out.println("Huis Geraakt!");
touch = false;
counter++;
checkSpeed();
money = Integer.toString(counter);
// System.out.println(counter);
}
}
if (huiz.getBounds().overlaps(lijn.getBounds())
|| huiz.getBounds1().overlaps(lijn.getBounds())){
//System.out.println("Game Over");
}
font.draw(batch, money, Gdx.graphics.getWidth() / 2.06f,
Gdx.graphics.getHeight() / 1.05f);
font.setColor(Color.BLACK);
font.setScale(2, 2);
// house.draw(batch);
// house1.draw(batch);
lijn.draw(batch);
batch.end();
// sr.begin(ShapeType.Filled);
// sr.setColor(Color.YELLOW);
// sr.rect(Gdx.input.getX(), Gdx.graphics.getHeight() -
// Gdx.input.getY(),
// paper.getSize().x, paper.getSize().y);
// sr.setColor(Color.BLACK);
// sr.rect(huiz.getPosition().x, huiz.getPosition().y,
// huiz.getSize().x, huiz.getSize().y);
// sr.rect(house1.getPosition().x, house1.getPosition().y,
// house1.getSize().x, house1.getSize().y);
// sr.end();
}
public static void savePrefs(){
prefs = Gdx.app.getPreferences("game-prefs"); // The name of your prefs files
prefs.putInteger("counter", counter);
prefs.flush();
System.out.println(prefs);
}
public static void loadPrefs(){
prefs = Gdx.app.getPreferences("game-prefs");
counter = prefs.getInteger("counter",0); //Load counter, default to zero if not found
}
public void checkSpeed() {
if (counter <= 7) {
huiz.huisVelocity = 500f;
}
if (counter > 7 && counter <= 17) {
huiz.huisVelocity = 550f;
}
if (counter > 17 && counter <= 30) {
huiz.huisVelocity = 650f;
}
if (counter > 30 && counter <= 50) {
huiz.huisVelocity = 750;
}
if (counter > 50 && counter <= 75) {
huiz.huisVelocity = 900;
}
if (counter > 75 && counter <= 100) {
huiz.huisVelocity = 1000;
}
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
kukar = false;
touch = false;
return true;
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
#Override
public void render() {
}
}
Here is the menu class:
package com.mygdx.Papermadness.screens;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.mygdx.Papermadness.Papermadness;
public class MainMenu implements Screen {
private Stage stage;// done
private TextureAtlas atlas;// done
private Skin skin;// done
private Table table;// done
private TextButton buttonPlay, buttonExit;
private BitmapFont white, black;// done
private Label heading;
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Table.drawDebug(stage);
stage.act(delta);
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
stage = new Stage();
Gdx.input.setInputProcessor(stage);
atlas = new TextureAtlas("ui/button.pack");
skin = new Skin(atlas);
table = new Table(skin);
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
white = new BitmapFont(Gdx.files.internal("font/white.fnt"), false);
black = new BitmapFont(Gdx.files.internal("font/black.fnt"), false);
// maakt buttons
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.getDrawable("button.up");
textButtonStyle.down = skin.getDrawable("button.down");
textButtonStyle.pressedOffsetX = 1;
textButtonStyle.pressedOffsetY = -1;
textButtonStyle.font = black;
buttonExit = new TextButton("EXIT", textButtonStyle);
buttonExit.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
buttonExit.pad(15);
buttonPlay = new TextButton("PlAY", textButtonStyle);
buttonPlay.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
((Game) Gdx.app.getApplicationListener())
.setScreen(new PaperMadness());
}
});
buttonPlay.pad(15);
// maakt header
heading = new Label(Papermadness.TITLE, new LabelStyle(white,
Color.WHITE));
heading.setFontScale(2);
table.add(heading);
table.getCell(heading).spaceBottom(100);
table.row();
table.add(buttonPlay);
table.getCell(buttonPlay).spaceBottom(15);
table.row();
table.add(buttonExit);
// table.debug();
stage.addActor(table);
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
stage.dispose();
atlas.dispose();
skin.dispose();
white.dispose();
black.dispose();
}
}
public class MyGdxGame extends Game{
public static MenuScreen menuScreen;
public static GameScreen gameScreen;
#Override
public void create(){
menuScreen = new MenuScreen(this);
gameScreen = new GameScreen (this);
setScreen(menuScreen);
}
}
Here is MenuScreen
public class MenuScreen implements Screen{
MyGdxGame game;
public MenuScreen(MyGdxGame game){
this.game = game;
}
////////////when you want to change screen type game.setScreen(game.gameScreen)
...........
...........
}
and this is GameScreen
public class GameScreen implements Screen{
...........
...........
...........
}
this is a simple example , try to do the same in your code.
Here is a good tutorial
https://github.com/libgdx/libgdx/wiki/Extending-the-simple-game
If it helped , let me know about it.

Android: View cut off when moved out of screen

I am creating a custom view which can be moved on screen left and right. I am adding this view in a relative layout. Here is some of the code of my custom view:
The parent view of the SubtopicsView class:
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RelativeLayout;
import com.example.androidstackedview.R;
import com.example.androidstackedview.views.BaseView.ViewState;
public class StackedView extends RelativeLayout {
Context context;
View dashboardView;
TopicsView topicsView;
SubTopicsView subtopicsView;
DetailsView detailsView;
float widthFactor = 10;
public static int screenHeight;
public static int screenWidth;
public static float xDocked = 0;
public StackedView(Context context) {
super(context);
this.context = context;
init();
}
public StackedView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
private void init() {
initScreenDimenstions();
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int orientation = context.getResources().getConfiguration().orientation;
initColumnViews();
if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
topicsView.layout(dashboardView.getWidth(), 0, (int) (dashboardView.getWidth()+screenWidth/2 - screenWidth/2 * .30f), screenHeight);
}
else {
topicsView.layout(dashboardView.getWidth(), 0, (int) (dashboardView.getWidth()+screenWidth/2), screenHeight);
}
topicsView.setxNormal(dashboardView.getWidth());
topicsView.setxDocked(xDocked);
if(!topicsView.isAnimating) {
topicsView.changeState(topicsView.mViewState, false);
}
if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
subtopicsView.layout((int) (topicsView.getLeft()+topicsView.getWidth()), 0, (topicsView.getLeft()+topicsView.getWidth()) + topicsView.getWidth(), screenHeight);
subtopicsView.setxNormal(topicsView.getLeft()+topicsView.getWidth());
}
else {
subtopicsView.layout((int) (screenWidth/2), 0, screenWidth, screenHeight);
subtopicsView.setxNormal(screenWidth/2);
}
subtopicsView.setxDocked(xDocked);
subtopicsView.changeState(subtopicsView.mViewState, false);
// detailsView.layout((int) (xDocked), 0, screenWidth, screenHeight);
// detailsView.setxNormal(xDocked);
// detailsView.setxDocked(xDocked);
// detailsView.changeState(detailsView.mViewState, false);
if(orientation == Configuration.ORIENTATION_PORTRAIT) {
detailsView.layout((int) (xDocked), 0, screenWidth, screenHeight);
detailsView.setxNormal(xDocked + topicsView.getWidth());
detailsView.setxDocked(xDocked);
detailsView.changeState(ViewState.DOCKED, false);
}
else if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
detailsView.layout((int) (xDocked + topicsView.getWidth()/2), 0, screenWidth, screenHeight);
detailsView.setxNormal(xDocked + topicsView.getWidth());
detailsView.setxDocked(xDocked + topicsView.getWidth()/2);
detailsView.changeState(ViewState.DOCKED, false);
}
}
public void initColumnViews() {
if(dashboardView == null) {
dashboardView = findViewWithTag("dashboard");
}
if(dashboardView != null) {
View v = dashboardView.findViewById(R.id.testimg);
if(v != null) {
xDocked = v.getLeft() + v.getWidth();
}
}
if(topicsView == null) {
topicsView = (TopicsView) findViewWithTag("topics");
}
if(subtopicsView == null) {
subtopicsView = (SubTopicsView) findViewWithTag("subtopics");
}
if(detailsView == null) {
detailsView = (DetailsView) findViewWithTag("details");
}
}
private void initScreenDimenstions() {
DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
}
public void resetTo1stPhase() {
topicsView.setVisibility(View.VISIBLE);
// if(topicsView.mViewState == ViewState.DOCKED) {
// topicsView.changeState(ViewState.NORMAL, true);
// } else {
topicsView.changeState(ViewState.NORMAL, false);
// }
subtopicsView.setVisibility(View.GONE);
subtopicsView.changeState(ViewState.NORMAL, false);
detailsView.setVisibility(View.GONE);
detailsView.changeState(ViewState.NORMAL, false);
}
public void resetTo2ndPhase() {
topicsView.setVisibility(View.VISIBLE);
int orientation = context.getResources().getConfiguration().orientation;
if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
topicsView.changeState(ViewState.NORMAL, false);
}
else {
if(topicsView.mViewState == ViewState.DOCKED) {
topicsView.changeState(ViewState.DOCKED, false);
} else {
topicsView.changeState(ViewState.DOCKED, true);
}
}
subtopicsView.setVisibility(View.VISIBLE);
subtopicsView.changeState(ViewState.NORMAL, false);
detailsView.setVisibility(View.GONE);
detailsView.changeState(ViewState.NORMAL, false);
}
public void resetTo3rdPhase() {
// TODO Auto-generated method stub
subtopicsView.setVisibility(View.VISIBLE);
subtopicsView.changeState(ViewState.DOCKED, false);
detailsView.setVisibility(View.VISIBLE);
detailsView.changeState(ViewState.NORMAL, false);
}
public void loadFragmentInTopicsFrame(Fragment f) {
initColumnViews();
FragmentManager fm = ((FragmentActivity)context).getSupportFragmentManager();
FragmentTransaction t = fm.beginTransaction();
t.replace(topicsView.findViewById(R.id.fr1).getId(), f);
t.commit();
resetTo1stPhase();
}
public void loadFragmentInSubtopicsFrame(Fragment f) {
initColumnViews();
FragmentManager fm = ((FragmentActivity)context).getSupportFragmentManager();
FragmentTransaction t = fm.beginTransaction();
t.replace(subtopicsView.findViewById(R.id.fr2).getId(), f);
t.commit();
resetTo2ndPhase();
}
public void loadFragmentInDetailsFrame(Fragment f) {
initColumnViews();
FragmentManager fm = ((FragmentActivity)context).getSupportFragmentManager();
FragmentTransaction t = fm.beginTransaction();
t.replace(detailsView.findViewById(R.id.fr3).getId(), f);
t.commit();
resetTo3rdPhase();
}
}
...........
This is the BaseView i.e. parent of Subtopics class:
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
public class BaseView extends RelativeLayout {
float xNormal;
float xDocked;
float px;
boolean isAnimating = false;
public ViewState mViewState = ViewState.NORMAL;
final float TOUCH_FACTOR = 0.60f;
final long ANIMATION_DURATION = 100;
public BaseView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public BaseView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public BaseView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if(isAnimating) {
return true;
}
if(mViewState == ViewState.DOCKED) {
return true;
}
if(action == MotionEvent.ACTION_DOWN) {
px = event.getX();
}
else if(action == MotionEvent.ACTION_MOVE) {
float newX = event.getX();
float dx = newX - px;
if(Math.abs(dx) > 0) {
float value = getLeft()+(dx*TOUCH_FACTOR);
if(value < 0) {
value = 0;
}
layout((int)(value), 0, (int)(value+getWidth()), getHeight());
}
px = newX;
}
else if(action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
float toX = 0;
if(mViewState == ViewState.NORMAL) {
toX =xNormal-getLeft();
}
else if(mViewState == ViewState.DOCKED) {
toX = xDocked-getLeft();
}
StackedAnimation anim = new StackedAnimation(this, 0, toX, ANIMATION_DURATION);
anim.setListener(new OnHAnimationListener() {
#Override
public void onStart() {
isAnimating = true;
}
#Override
public void onEnd() {
isAnimating = false;
changeState(mViewState, false);
}
});
anim.start();
}
return true;
}
public void changeState(ViewState state, boolean animate) {
mViewState = state;
if(mViewState == ViewState.NORMAL) {
if(animate) {
StackedAnimation anim = new StackedAnimation(this, getLeft(), xNormal, ANIMATION_DURATION);
anim.setListener(new OnHAnimationListener() {
#Override
public void onStart() {
// TODO Auto-generated method stub
isAnimating = true;
}
#Override
public void onEnd() {
// TODO Auto-generated method stub
isAnimating = false;
layout((int) xNormal, 0, (int) (xNormal+getWidth()), getHeight());
}
});
anim.start();
} else {
layout((int) xNormal, 0, (int) (xNormal+getWidth()), getHeight());
}
}
else if(mViewState == ViewState.DOCKED) {
if(animate) {
StackedAnimation anim = new StackedAnimation(this, getLeft(), xDocked, ANIMATION_DURATION);
anim.setListener(new OnHAnimationListener() {
#Override
public void onStart() {
// TODO Auto-generated method stub
isAnimating = true;
}
#Override
public void onEnd() {
// TODO Auto-generated method stub
isAnimating = false;
layout((int) xDocked, 0, (int) (xDocked+getWidth()), getHeight());
}
});
anim.start();
} else {
layout((int) xDocked, 0, (int) (xDocked+getWidth()), getHeight());
}
}
}
public float getxNormal() {
return xNormal;
}
public void setxNormal(float xNormal) {
this.xNormal = xNormal;
}
public float getxDocked() {
return xDocked;
}
public void setxDocked(float xLocked) {
this.xDocked = xLocked;
}
public boolean isAnimating() {
return isAnimating;
}
public void setAnimating(boolean isAnimating) {
this.isAnimating = isAnimating;
}
public enum ViewState {
NORMAL,
DOCKED,
NONE;
}
public enum ColumnType {
TOPIC,
SUBTOPIC,
DETAILS;
}
}
......
And this is the Subtopics class:
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.FrameLayout;
public class SubTopicsView extends BaseView {
StackedView stackView;
Context context;
private int screenHeight;
private int screenWidth;
public SubTopicsView(Context context) {
super(context);
this.context = context;
// TODO Auto-generated constructor stub
setBackgroundColor(0xFF888888);
initScreenDimenstions();
}
public SubTopicsView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
// TODO Auto-generated constructor stub
setBackgroundColor(0xFF888888);
initScreenDimenstions();
}
public SubTopicsView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
// TODO Auto-generated constructor stub
setBackgroundColor(0xFF888888);
initScreenDimenstions();
}
private void initScreenDimenstions() {
DisplayMetrics displaymetrics = new DisplayMetrics();
((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if(findViewById(R.id.parent) != null) {
int orientation = context.getResources().getConfiguration().orientation;
FrameLayout.LayoutParams params;
if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
params = new FrameLayout.LayoutParams((int) (screenWidth/2 - screenWidth/2 * .30f), screenHeight);
}
else {
params = new FrameLayout.LayoutParams((int) (screenWidth/2), screenHeight);
}
findViewById(R.id.parent).setLayoutParams(params);
}
}
}
The view moves properly on touch but when the view starts going out of the screen either on left or right side, it starts to cut off from other side as in the below screenshot.
Any idea why the view is behaving like this?

How to flush previous input on resuming activity in android?

I have this app where when i enter some values in editText of 1st activity i.e ActivityA and then press a Button shows the result in next activity i.e ActivityB. But when i revert back to ActivityA and change some values and press button so that i want another ActivityC to be called, ActivityB only appears.
but if i restart my application and put values required to get ActivityC i will get it. how am i supposed solve this problem?
EDIT :
ActivityA
package com.example.iolcalci;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Selection extends Activity implements OnFocusChangeListener{
private EditText k1_e,k2_e,al_e,alconst_e,dr_e;
TextView k1_m,k2_m;
private float k1,k2,al,al_const,dr,Avg_k,v_k1,v_k2,v_dr;
private Float srkt_rnd,srk2_rnd,holladay_rnd,binkhorst_rnd,IOLPower_srkt,IOLPower_srk2,IOLPower_bink,IOLPower_holl;
private float srkt_rf2,srkt_rf3,srkt_rf4,srkt_rf5,srkt_rf6,srkt_rf7,srkt_rf8,srkt_rf9,srkt_rf10,srkt_rf11,srkt_rf12;
private float holladay_rf2,holladay_rf3,holladay_rf4,holladay_rf5,holladay_rf6,holladay_rf7,holladay_rf8,holladay_rf9,holladay_rf10,holladay_rf11,holladay_rf12;
private float binkhorst_rf2,binkhorst_rf3,binkhorst_rf4,binkhorst_rf5,binkhorst_rf6,binkhorst_rf7,binkhorst_rf8,binkhorst_rf9,binkhorst_rf10,binkhorst_rf11,binkhorst_rf12;
private Spinner spin;
private Button result;
private int spinSelected=-1;
int flag = 0;
String k1_s,k2_s,al_s,al_const_s,dr_s;
TextWatcher k1e,k2e,ale,dre;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selective);
setupUI(findViewById(R.id.form_layout));
spin=(Spinner)findViewById(R.id.formulae);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// TODO Auto-generated method stub
spinSelected=pos;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
spinSelected=-1;
}
});
dr_e=(EditText)findViewById(R.id.dr_editText);
k1_e=(EditText)findViewById(R.id.k1_editText);
k2_e=(EditText)findViewById(R.id.K2_editText);
al_e=(EditText)findViewById(R.id.al_editText);
alconst_e=(EditText)findViewById(R.id.al_const_editText);
k1_m=(TextView)findViewById(R.id.k1_metric);
k2_m=(TextView)findViewById(R.id.k2_metric);
dr_e.setText("0.0");
dr_e.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
dr_s=dr_e.getText().toString();
v_dr=Float.valueOf(dr_s);
}
});
al_e.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
al_s = al_e.getText().toString();
int dotPos = -1;
for (int i = 0; i < al_s.length(); i++) {
char c = al_s.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
if(al_s.length()==0){
al_e.setText("0.00");
}else{
al_e.setText(al_s + ".00");
}
} else {
if ( al_s.length() - dotPos == 1 ) {
al_e.setText(al_s + "00");
} else if ( al_s.length() - dotPos == 2 ) {
al_e.setText(al_s + "0");
}
}
}
}
});
k1_e.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String k1_s = k1_e.getText().toString();
int dotPos = -1;
for (int i = 0; i < k1_s.length(); i++) {
char c = k1_s.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
if(k1_s.length()==0){
k1_e.setText("0.00");
}else{
k1_e.setText(k1_s + ".00");
}
} else {
if ( k1_s.length() - dotPos == 1 ) {
k1_e.setText(k1_s + "00");
} else if ( k1_s.length() - dotPos == 2 ) {
k1_e.setText(k1_s + "0");
}
}
}
k1_s=k1_e.getText().toString().trim();
k1_e.setText(String.format(k1_s,"##.00"));
if(k1_s.length()!=0){
k1=Float.parseFloat(k1_s);
v_k1=Float.valueOf(k1);
Log.v("K1",""+v_k1);
if((v_k1>=(float)5.63)&&(v_k1<=(float)11.25)){
k1_m.setText("mm");
Log.v("CHECK1", "success1" +v_k1);
}else if((v_k1>=(float)30)&&(v_k1<=(float)60)){
k1_m.setText("D");
Log.v("CHECK1", "success1" +v_k1);
}else{
}
}
}
});
k2_e.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
if(!hasFocus){
String k2_s = k2_e.getText().toString();
int dotPos = -1;
for (int i = 0; i < k2_s.length(); i++) {
char c = k2_s.charAt(i);
if (c == '.') {
dotPos = i;
}
}
if (dotPos == -1){
if(k2_s.length()==0){
k2_e.setText("0.00");
}else{
k2_e.setText(k2_s + ".00");
}
} else {
if ( k2_s.length() - dotPos == 1 ) {
k2_e.setText(k2_s + "00");
} else if ( k2_s.length() - dotPos == 2 ) {
k2_e.setText(k2_s + "0");
}
}
}
k2_s=k2_e.getText().toString().trim();
if(k2_s.length()!=0){
k2=Float.parseFloat(k2_s);
v_k2=Float.valueOf(k2);
Log.v("K2",""+v_k2);
if((v_k2>=5.63)&&(v_k2<=11.25)){
k2_m.setText("mm");
Log.v("CHECK2", "success2" +v_k2);
}else if((v_k2>=30)&&(v_k1<=60)){
k2_m.setText("D");
Log.v("CHECK2", "success2" +v_k2);
}else{
}
}
}
});
result=(Button)findViewById(R.id.result);
result.setOnClickListener(new OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(dr_e.getText().toString().length()==0|al_e.getText().toString().length()==0|alconst_e.getText().toString().length()==0){
flag=1;
}else{
dr=Float.parseFloat(dr_e.getText().toString());
al=Float.parseFloat(al_e.getText().toString());
al_const=Float.parseFloat(alconst_e.getText().toString());
k1=Float.parseFloat(k1_e.getText().toString().trim());
k2=Float.parseFloat(k2_e.getText().toString().trim());
}
if((v_k1>=(float)5.63)&&(v_k1<=(float)11.25)){
k1=Round((float)(337.5/v_k1),2);
}
if((v_k2>=(float)5.63)&&(v_k2<=(float)11.25)){
k2=Round((float)(337.5/v_k2),2);
}
Avg_k=(k1+k2)/2;
if(spinSelected==0){
IOLPower_srkt=Srkt();
if(flag!=1){
Intent iSrkt=new Intent(Selection.this,Srkt.class);
iSrkt.putExtra("RESULT", IOLPower_srkt);
iSrkt.putExtra("DR", dr);
iSrkt.putExtra("IOL", srkt_rnd);
iSrkt.putExtra("REFER7", srkt_rf7);
iSrkt.putExtra("REFER2", srkt_rf2);
iSrkt.putExtra("REFER3", srkt_rf3);
iSrkt.putExtra("REFER4", srkt_rf4);
iSrkt.putExtra("REFER5", srkt_rf5);
iSrkt.putExtra("REFER6", srkt_rf6);
iSrkt.putExtra("REFER8", srkt_rf8);
iSrkt.putExtra("REFER9", srkt_rf9);
iSrkt.putExtra("REFER10", srkt_rf10);
iSrkt.putExtra("REFER11", srkt_rf11);
iSrkt.putExtra("REFER12", srkt_rf12);
startActivity(iSrkt);
}else{
Intent iSrktx=new Intent(Selection.this,Srkt_x.class);
startActivity(iSrktx);
}
}else if(spinSelected==1){
IOLPower_bink=Binkhorst();
if(flag!=1){
Intent iBinkhorst=new Intent(Selection.this,Binkhorst.class);
iBinkhorst.putExtra("RESULT", IOLPower_bink);
iBinkhorst.putExtra("DR", dr);
iBinkhorst.putExtra("IOL", binkhorst_rnd);
iBinkhorst.putExtra("REFER7", binkhorst_rf7);
iBinkhorst.putExtra("REFER2", binkhorst_rf2);
iBinkhorst.putExtra("REFER3", binkhorst_rf3);
iBinkhorst.putExtra("REFER4", binkhorst_rf4);
iBinkhorst.putExtra("REFER5", binkhorst_rf5);
iBinkhorst.putExtra("REFER6", binkhorst_rf6);
iBinkhorst.putExtra("REFER8", binkhorst_rf8);
iBinkhorst.putExtra("REFER9", binkhorst_rf9);
iBinkhorst.putExtra("REFER10", binkhorst_rf10);
iBinkhorst.putExtra("REFER11", binkhorst_rf11);
iBinkhorst.putExtra("REFER12", binkhorst_rf12);
startActivity(iBinkhorst);
}else{
Intent iBinkhorstx=new Intent(Selection.this,Binkhorst_x.class);
startActivity(iBinkhorstx);
}
}else if(spinSelected==2){
IOLPower_srk2=Srk2();
if((Math.ceil(IOLPower_srk2)-IOLPower_srk2)>0.5){
srk2_rnd=(float) Math.floor(IOLPower_srk2);
}else{
srk2_rnd=(float) Math.ceil(IOLPower_srk2);
}
if(flag!=1){
Intent iSrk2=new Intent(Selection.this,Srk2.class);
iSrk2.putExtra("RESULT", IOLPower_srk2);
iSrk2.putExtra("DR", dr);
iSrk2.putExtra("IOL", srk2_rnd);
startActivity(iSrk2);
}else{
Intent iSrk2x=new Intent(Selection.this,Srk2_x.class);
startActivity(iSrk2x);
}
}else{
IOLPower_holl=Holladay();
if(flag!=1){
Intent iHolladay=new Intent(Selection.this,Holladay.class);
iHolladay.putExtra("RESULT", IOLPower_holl);
iHolladay.putExtra("DR", dr);
iHolladay.putExtra("IOL", holladay_rnd);
iHolladay.putExtra("REFER7", holladay_rf7);
iHolladay.putExtra("REFER2", holladay_rf2);
iHolladay.putExtra("REFER3", holladay_rf3);
iHolladay.putExtra("REFER4", holladay_rf4);
iHolladay.putExtra("REFER5", holladay_rf5);
iHolladay.putExtra("REFER6", holladay_rf6);
iHolladay.putExtra("REFER8", holladay_rf8);
iHolladay.putExtra("REFER9", holladay_rf9);
iHolladay.putExtra("REFER10", holladay_rf10);
iHolladay.putExtra("REFER11", holladay_rf11);
iHolladay.putExtra("REFER12", holladay_rf12);
startActivity(iHolladay);
}else{
Intent iHolladayx=new Intent(Selection.this,Holladay_x.class);
startActivity(iHolladayx);
}
}
}
});
Button reset=(Button) findViewById(R.id.reset);
reset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dr_e.setText("0.0");
al_e.setText("");
k1_e.setText("");
k2_e.setText("");
alconst_e.setText("");
dr_e.requestFocus();
}
});
}
public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}
public float Srkt(){
float Rcor;
float Lcor;
float Crwdest;
float Corneal_H;
float Acd_Const;
float Offset;
float Acd_Est;
float Na=(float) 1.336;
float C2=(float) 0.3333;
float C3;
float C4;
float C5;
float C6;
float C8;
float C9;
float Iolam;
float Rcor1=(float)(337.5/Avg_k);Rcor=Round(Rcor1,2);
if(al<=24.2){
Lcor=al;
}else{
Lcor=(float) (-3.446+1.716*al-0.0237*(al*al));
}Lcor=Round(Lcor,2);
Crwdest=(float) (-5.41+0.58412*Lcor+0.098*Avg_k);Crwdest=Round(Crwdest,2);
Corneal_H=(float) (Rcor-(Math.sqrt(Rcor*Rcor-Crwdest*Crwdest/4)));Corneal_H=Round(Corneal_H,2);
Acd_Const=(float) (0.62467*al_const-68.747);
Offset=(float) (Acd_Const-3.336);Offset=Round(Offset,2);
Acd_Est=(Corneal_H+Offset); float Acd_Est1=Round(Acd_Est,2);
C3=(float) (0.97971*al+0.65696);C3=Round(C3,2);
C4=C3-Acd_Est1;C4=Round(C4,2);
C5=(float) ((Na*Rcor)-(C2*Acd_Est)); C5=Round(C5, 2);
C6=(float) ((Na*Rcor1)-(C2*C3));
C8=(float) ((12*C6)+(C3*Rcor1));C8=Round(C8,2);
C9=(float) ((12*C5)+(Acd_Est*Rcor1));C9=Round(C9,2);
Iolam=(float) ((1336*(C6-(0.001*C8*dr)))/(C4*(C5-(0.001*dr*C9))));Iolam=Round(Iolam,2);
if((Math.ceil(Iolam)-Iolam)>0.5){
srkt_rnd=(float) Math.floor(Iolam);
}else{
srkt_rnd=(float) Math.ceil(Iolam);
}
srkt_rf7=(float) (((1336*C6)-(srkt_rnd*C4*C5))/((1.336*C8)-(0.001*srkt_rnd*C4*C9)));
srkt_rf6=(float) (((1336*C6)-((srkt_rnd+0.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+0.5)*C4*C9)));
srkt_rf5=(float) (((1336*C6)-((srkt_rnd+1)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+1)*C4*C9)));
srkt_rf4=(float) (((1336*C6)-((srkt_rnd+1.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+1.5)*C4*C9)));
srkt_rf3=(float) (((1336*C6)-((srkt_rnd+2)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+2)*C4*C9)));
srkt_rf2=(float) (((1336*C6)-((srkt_rnd+2.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd+2.5)*C4*C9)));
srkt_rf8=(float) (((1336*C6)-((srkt_rnd-0.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-0.5)*C4*C9)));
srkt_rf9=(float) (((1336*C6)-((srkt_rnd-1)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-1)*C4*C9)));
srkt_rf10=(float) (((1336*C6)-((srkt_rnd-1.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-1.5)*C4*C9)));
srkt_rf11=(float) (((1336*C6)-((srkt_rnd-2)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-2)*C4*C9)));
srkt_rf12=(float) (((1336*C6)-((srkt_rnd-2.5)*C4*C5))/((1.336*C8)-(0.001*(srkt_rnd-2.5)*C4*C9)));
return(Iolam);
}
public float Binkhorst(){
float K1;
float LB2;
float ACDbnk;
float xb;
float yb;
float em;
K1=(float)(337.5/Avg_k);
LB2=(float) (al+0.1984);
if(LB2>=26){
ACDbnk=(float) (((0.58357*al_const)-63.896)*1.1087);
}else{
ACDbnk=(float) (((0.58357*al_const)-63.896)*LB2/23.45);
}
xb=(float) (1336*((1.336*K1-0.3333*LB2)-0.001*dr*(16.032*K1-4*LB2+LB2*K1)));
yb=(float) ((LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk-0.001*dr*(16.032*K1-4*ACDbnk+ACDbnk*K1)));
em=xb/yb;em=Round(em,2);
if((Math.ceil(em)-em)>0.5){
binkhorst_rnd=(float) Math.floor(em);
}else{
binkhorst_rnd=(float) Math.ceil(em);
}
binkhorst_rf7=(float) ((1336*((1.336*K1-0.3333*LB2))-binkhorst_rnd*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*binkhorst_rnd*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf6=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+0.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+0.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf5=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+1)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+1)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf4=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+1.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+1.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf3=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+2)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+2)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf2=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd+2.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd+2.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf8=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-0.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-0.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf9=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-1)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-1)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf10=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-1.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-1.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf11=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-2)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-2)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
binkhorst_rf12=(float) ((1336*((1.336*K1-0.3333*LB2))-(binkhorst_rnd-2.5)*(LB2-ACDbnk)*(1.336*K1-0.3333*ACDbnk))/(1.336*((16.032*K1)-(4*LB2)+(LB2*K1))-0.001*(binkhorst_rnd-2.5)*(LB2-ACDbnk)*((16.032*K1)-(4*ACDbnk)+(ACDbnk*K1))));
return(em);
}
public float Srk2(){
float X25 = 0;
float Avg_k=(k1+k2)/2;
if(al<20.0){
X25=al_const+3;
}else if((al>=20.0)&&(al<21.0)){
X25=al_const+2;
}else if((al>=21.0)&&(al<22.0)){
X25=al_const+1;
}else if((al>=22.0)&&(al<24.5)){
X25=al_const;
}else if(al>=24.5){
X25=(float) (al_const-(0.5));
}else{
Toast.makeText(getApplicationContext(), "Please enter valid AL value", Toast.LENGTH_SHORT).show();
}
float SRK2 = (float) (X25-(0.9*Avg_k+2.5*al));
return(SRK2);
}
public float Holladay(){
float K;
float Lhol;
float SF;
float Rag;
float AGx;
float AG;
float ACDH;
float CAhol;
float xh;
float yh;
float K1=(float)(337.5/Avg_k);K=Round(K1,2);
Lhol=(float) (al+0.2);
SF=(float) ((0.5663*al_const)-65.6);
if(K<7){
Rag=7;
}else{
Rag=K;
}
AGx=(float) (al*0.533);
if(AGx>13.5){
AG=(float) 13.5;
}else{
AG=AGx;
}
ACDH=(float) (0.56+Rag-(Math.sqrt(Rag*Rag-AG*AG/4)));
CAhol=ACDH+SF;
xh=(float) (1336*((1.336*K1-0.3333*Lhol)-0.001*dr*(16.032*K1-4*Lhol+Lhol*K1)));
yh=(float) ((Lhol-CAhol)*(1.336*K1-0.3333*CAhol-0.001*dr*(16.032*K1-4*CAhol+CAhol*K1)));
float em=xh/yh;em=Round(em,2);
if((Math.ceil(em)-em)>0.5){
holladay_rnd=(float) Math.floor(em);
}else{
holladay_rnd=(float) Math.ceil(em);
}
holladay_rf7=(float) ((1336*((1.336*K1-0.3333*Lhol))-holladay_rnd*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*holladay_rnd*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf6=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+0.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+0.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf5=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+1)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+1)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf4=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+1.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+1.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf3=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+2)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+2)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf2=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd+2.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd+2.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf8=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-0.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-0.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf9=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-1)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-1)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf10=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-1.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-1.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf11=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-2.0)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-2)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
holladay_rf12=(float) ((1336*((1.336*K1-0.3333*Lhol))-(holladay_rnd-2.5)*(Lhol-CAhol)*(1.336*K1-0.3333*CAhol))/(1.336*((16.032*K1)-(4*Lhol)+(Lhol*K1))-0.001*(holladay_rnd-2.5)*(Lhol-CAhol)*((16.032*K1)-(4*CAhol)+(CAhol*K1))));
return(em);
}
//when the back button is pressed from next activity
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dr_e.requestFocus();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if(!(view instanceof EditText)) {
view.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
hideSoftKeyboard(Selection.this);
return false;
}
});
}
//If a layout container, iterate over children and seed recursion.
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
View innerView = ((ViewGroup) view).getChildAt(i);
setupUI(innerView);
}
}
}
}
ActivityB
package com.example.iolcalci;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Srk2 extends Activity {
private Float Result,dr,Srk2_rnd7,Srk2_rnd2,Srk2_rnd3,Srk2_rnd4,Srk2_rnd5,Srk2_rnd6,Srk2_rnd8,Srk2_rnd9,Srk2_rnd10,Srk2_rnd11,Srk2_rnd12;
private Float Ref2,Ref3,Ref4,Ref5,Ref6,Ref7,Ref8,Ref9,Ref10,Ref11,Ref12;
private float Rf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_srk2);
Thread srk2=new Thread(){
public void run() {
TextView power=(TextView) findViewById(R.id.srk2_power);
TextView name=(TextView) findViewById(R.id.iolpower);
Result=getIntent().getExtras().getFloat("RESULT");
dr=getIntent().getExtras().getFloat("DR");
if(dr==0){
name.setText("EM :");
}else{
name.setText("AM :");
}
Srk2_rnd7=getIntent().getExtras().getFloat("IOL");
power.setText(String.valueOf(Result));
//some more calculation
}
};
srk2.start();
}
public float refraction(Float ans){
Rf=refer();
return((Result-ans)/Rf);
}
public float refer(){
float Refer;
if(Result>14){
Refer=(float) 1.25;
}else{
Refer=1;
}
return(Refer);
}
}
ActivityC
package com.example.iolcalci;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
#SuppressLint("NewApi")
public class Srk2_x extends Activity
{
Float result;
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_srk2_x);
TextView text = (TextView) findViewById(R.id.srk2_power);
text.setText("INVALID");
}
}
By maintaining visited activity Queue or use Activity stack to track the activity sequence.
As I can see the flag value is controlling which activity to start. I guess you should change flag to default value when you start a new activity, or override onPause method in your activity and change it there.

comparing int values in android

I am making an android game that is checking the players health value when this method is being runned. But however, it's not reacting. It doesn't do anything, when the value is less than 3, it shouldn't do anything, but when it is equal to 3, it should run a method. Please help me and thanks SO much in advance! This is the code that i am using:
private void checkLivesLeftValue() {
if (livesLeftValue == 3) {
//Message to display: "You lost!
onMethod();
}
else {
livesLeftValue = livesLeftValue + 1;
}
}
Full code:
package com.mysoftwaremobileapps.ParachuteHunter;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;
public class ExampleView extends SurfaceView implements SurfaceHolder.Callback
{
class ExampleThread extends Thread
{
private ArrayList<Parachuter> parachuters;
private Bitmap parachuter;
private Paint black;
private boolean running;
private SurfaceHolder mSurfaceHolder;
private Context mContext;
private Handler mHandler;
private GameScreenActivity mActivity;
private long frameRate;
private boolean loading;
public float x;
public float y;
public MediaPlayer mp1;
public int parachuterIndexToResetAndDelete;
public int canvasGetWidth;
public int livesLeftValue;
public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler)
{
mSurfaceHolder = sHolder;
mHandler = handler;
mContext = context;
mActivity = (GameScreenActivity) context;
parachuters = new ArrayList<Parachuter>();
parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman);
black = new Paint();
black.setStyle(Paint.Style.FILL);
black.setColor(Color.WHITE);
running = true;
// This equates to 26 frames per second.
frameRate = (long) (1000 / 26);
loading = true;
}
#Override
public void run()
{
while (running)
{
Canvas c = null;
try
{
c = mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder)
{
long start = System.currentTimeMillis();
doDraw(c);
long diff = System.currentTimeMillis() - start;
if (diff < frameRate)
Thread.sleep(frameRate - diff);
}
} catch (InterruptedException e)
{
}
finally
{
if (c != null)
{
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
protected void doDraw(Canvas canvas)
{
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black);
canvasGetWidth = canvas.getWidth();
//Draw
for (int i = 0; i < parachuters.size(); i++)
{
canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null);
parachuters.get(i).tick();
}
//Remove
for (int i = 0; i < parachuters.size(); i++)
{
if (parachuters.get(i).getY() > canvas.getHeight()) {
parachuters.remove(i);
onPlaySound();
checkLivesLeftValue();
}
}
}
public void onPlaySound()
{
try {
mp1 = MediaPlayer.create(getContext(), R.raw.bombsound);
mp1.start();
} catch (Exception e) {
e.printStackTrace();
mp1.release();
}
}
public void onMethod() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "You lost!", 15).show();
}
});
}
private void checkLivesLeftValue() {
// TODO Auto-generated method stub
if (livesLeftValue == 3) {
//Message to display: "You lost!
onMethod();
}
else {
livesLeftValue = livesLeftValue + 1;
}
}
public boolean onTouchEvent(MotionEvent event)
{
if (event.getAction() != MotionEvent.ACTION_DOWN)
return false;
float x1 = event.getX();
float y1 = event.getY();
initiateDrawParachuters();
return true;
}
public void initiateDrawParachuters()
{
drawParachuter1();
}
private void drawParachuter1() {
// TODO Auto-generated method stub
//Parachuter nr. 1
x = 68;
y = 40;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter2();
}
private void drawParachuter2() {
// TODO Auto-generated method stub
//Parachuter nr. 2
x = 100;
y = 80;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter3();
}
private void drawParachuter3() {
// TODO Auto-generated method stub
//Parachuter nr. 3
x = 150;
y = 120;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter4();
}
private void drawParachuter4() {
// TODO Auto-generated method stub
//Parachuter nr. 4
x = 170;
y = 150;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter5();
}
private void drawParachuter5() {
// TODO Auto-generated method stub
//Parachuter nr. 5
x = 180;
y = 170;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter6();
}
private void drawParachuter6() {
// TODO Auto-generated method stub
//Parachuter nr. 6
x = 200;
y = 180;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
}
public void drawParachuters()
{
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
}
public void setRunning(boolean bRun)
{
running = bRun;
}
public boolean getRunning()
{
return running;
}
}
/** Handle to the application context, used to e.g. fetch Drawables. */
private Context mContext;
/** Pointer to the text view to display "Paused.." etc. */
private TextView mStatusText;
/** The thread that actually draws the animation */
private ExampleThread eThread;
public ExampleView(Context context)
{
super(context);
// register our interest in hearing about changes to our surface
SurfaceHolder holder = getHolder();
holder.addCallback(this);
// create thread only; it's started in surfaceCreated()
eThread = new ExampleThread(holder, context, new Handler()
{
#Override
public void handleMessage(Message m)
{
// mStatusText.setVisibility(m.getData().getInt("viz"));
// mStatusText.setText(m.getData().getString("text"));
}
});
setFocusable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
return eThread.onTouchEvent(event);
}
public ExampleThread getThread()
{
return eThread;
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder)
{
if (eThread.getState() == Thread.State.TERMINATED)
{
eThread = new ExampleThread(getHolder(), getContext(), getHandler());
eThread.start();
}
else
{
eThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
boolean retry = true;
eThread.setRunning(false);
while (retry)
{
try
{
eThread.join();
retry = false;
}
catch (InterruptedException e)
{
}
}
}
}
I agree with the others, check the value via Log messages, so you can see the actual values.
Also, check if it might go over 3. I dont know what kind of game you are making but for example, say that livesLeftValue=2 for now, but something happens, and it increases by 2, reaching 4, without ever having the value 3. Lets say it never gets decreased, so you will never ever hit the value 3, thus never invoking the game over thingie, and livesLeftValue will just increase to the infinity.
put some debug in there and see if you really get the right value in here.
private void checkLivesLeftValue() {
Log.d("checkLivesLeftValue", "lives = " + livesLeftValue);
if (livesLeftValue == 3) {
Log.d("checkLivesLeftValue", "calling onMethod now");
onMethod();
} else {
livesLeftValue = livesLeftValue + 1;
Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue);
}
}
public void onMethod() {
Log.d("onMethod", "in onMethod");
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d("onMethod", "showing Toast now");
Toast.makeText(getContext(), "You lost!", 15).show();
}
});
}

Save object Android not working

onRestoreInstanceState(Bundle savedInstanceState)
is not geting called, I am pasting my code below. Actually I want to redraw all the points that are saved when my activity went in background.
package com.geniteam.mytest;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
public class Tutorial2D extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new Panel(this));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Panel panel = new Panel(this);
outState.putSerializable("test", panel._graphics);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Panel panel = new Panel(this);
panel.set_graphics((ArrayList<GraphicObject>) savedInstanceState.getSerializable("test"));
}
class Panel extends SurfaceView implements SurfaceHolder.Callback {
private TutorialThread _thread;
private ArrayList<GraphicObject> _graphics = new ArrayList<GraphicObject>();
public ArrayList<GraphicObject> get_graphics() {
return _graphics;
}
public void set_graphics(ArrayList<GraphicObject> graphics) {
_graphics = graphics;
}
public Panel(Context context) {
super(context);
getHolder().addCallback(this);
_thread = new TutorialThread(getHolder(), this);
setFocusable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
synchronized (_thread.getSurfaceHolder()) {
// if (event.getAction() == MotionEvent.ACTION_DOWN) {
GraphicObject graphic = new GraphicObject(BitmapFactory.decodeResource(getResources(), R.drawable.icon));
graphic.getCoordinates().setX((int) event.getX() - graphic.getGraphic().getWidth() / 2);
graphic.getCoordinates().setY((int) event.getY() - graphic.getGraphic().getHeight() / 2);
_graphics.add(graphic);
//}
return true;
}
}
#Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
Bitmap bitmap;
GraphicObject.Coordinates coords;
for (GraphicObject graphic : _graphics) {
bitmap = graphic.getGraphic();
coords = graphic.getCoordinates();
canvas.drawBitmap(bitmap, coords.getX(), coords.getY(), null);
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
try{
_thread.setRunning(true);
_thread.start();
}catch(Exception ex){
_thread = new TutorialThread(getHolder(), this);
_thread.start();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// simply copied from sample application LunarLander:
// we have to tell thread to shut down & wait for it to finish, or else
// it might touch the Surface after we return and explode
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
} catch (InterruptedException e) {
// we will try it again and again...
}
}
}
}
class TutorialThread extends Thread {
private SurfaceHolder _surfaceHolder;
private Panel _panel;
private boolean _run = false;
public TutorialThread(SurfaceHolder surfaceHolder, Panel panel) {
_surfaceHolder = surfaceHolder;
_panel = panel;
}
public void setRunning(boolean run) {
_run = run;
}
public SurfaceHolder getSurfaceHolder() {
return _surfaceHolder;
}
#Override
public void run() {
Canvas c;
while (_run) {
c = null;
try {
c = _surfaceHolder.lockCanvas(null);
synchronized (_surfaceHolder) {
_panel.onDraw(c);
}
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
_surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
class GraphicObject {
/**
* Contains the coordinates of the graphic.
*/
public class Coordinates {
private int _x = 100;
private int _y = 0;
public int getX() {
return _x + _bitmap.getWidth() / 2;
}
public void setX(int value) {
_x = value - _bitmap.getWidth() / 2;
}
public int getY() {
return _y + _bitmap.getHeight() / 2;
}
public void setY(int value) {
_y = value - _bitmap.getHeight() / 2;
}
public String toString() {
return "Coordinates: (" + _x + "/" + _y + ")";
}
}
private Bitmap _bitmap;
private Coordinates _coordinates;
public GraphicObject(Bitmap bitmap) {
_bitmap = bitmap;
_coordinates = new Coordinates();
}
public Bitmap getGraphic() {
return _bitmap;
}
public Coordinates getCoordinates() {
return _coordinates;
}
}
}
onRestoreInstanceState only gets called if the app is destroyed and re-created. Putting the app in the background then bringing it up again will call onResume, but not onRestoreInstanceState.

Categories

Resources