order and timing of command execution bug - java

I'm making a "Simon says" game as my final project for highschool, and it's mostly done but I have one problem.
Currently, I'm trying to make the buttons light when I press them.
However, they don't seem to light up and the sleep function doesn't really work.
They only change color when the function that displays the next sequence of colors lights up.
Here's the code:
package com.gabie212.simonsays;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class GameActivity extends AppCompatActivity implements View.OnClickListener {
private int i = 0, pNum = 0, pIndex = 0,score;
private Thread t = new Thread();
private Thread bt = new Thread();
private Button greenButton;
private Button redButton;
private Button blueButton;
private Button yellowButton;
private Button startButton;
private TextView Score;
private boolean startActivated = false;
private MediaPlayer greenBeep;
private MediaPlayer redBeep;
private MediaPlayer blueBeep;
private MediaPlayer yellowBeep;
private ArrayList<Integer> userColors = new ArrayList<Integer>();
private GameManger gm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Score = (TextView) findViewById(R.id.ScoreNum);
greenButton = (Button) findViewById(R.id.btnGreen);
redButton = (Button) findViewById(R.id.btnRed);
blueButton = (Button) findViewById(R.id.btnBlue);
yellowButton = (Button) findViewById(R.id.btnYellow);
startButton = (Button) findViewById(R.id.btnStart);
greenButton.setOnClickListener(this);
redButton.setOnClickListener(this);
blueButton.setOnClickListener(this);
yellowButton.setOnClickListener(this);
startButton.setOnClickListener(this);
greenBeep = MediaPlayer.create(this, R.raw.greenbeep);
redBeep = MediaPlayer.create(this, R.raw.redbeep);
blueBeep = MediaPlayer.create(this, R.raw.bluebeep);
yellowBeep = MediaPlayer.create(this, R.raw.yellowbeep);
/*
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.apply();
*/
}
public void start() {
startActivated=true;
gm = new GameManger(this);
Score.setText("0");
lightUp(0);
}
public void beepStop(){
greenBeep.stop();
redBeep.stop();
blueBeep.stop();
yellowBeep.stop();
}
public void lightUp(final int i) {
android.os.Handler handler = new android.os.Handler();
if (i < gm.getRandomColors().size()) //light up code
{
switch (gm.getRandomColors().get(i)) {
case 1:
greenButton.setBackgroundResource(R.drawable.greenlightup);
greenBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
greenButton.setBackgroundResource(R.drawable.green);
lightUp(i+1);
}
}, 500);
break;
case 2:
redButton.setBackgroundResource(R.drawable.redlightup);
redBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
redButton.setBackgroundResource(R.drawable.red);
lightUp(i+1);
}
}, 500);
break;
case 3:
blueButton.setBackgroundResource(R.drawable.bluelightup);
blueBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
blueButton.setBackgroundResource(R.drawable.blue);
lightUp(i+1);
}
}, 500);
break;
case 4:
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
yellowBeep.start();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
yellowButton.setBackgroundResource(R.drawable.yellow);
lightUp(i+1);
}
}, 500);
break;
}
}
pIndex = 0;
}
#Override
public void onClick(View v) {
if (v.getId() == startButton.getId()) {
start();
} else {
if (startActivated) {
if (v.getId() == greenButton.getId()) {//here is the part where i try to make the buttons change colors
greenBeep.start();
greenButton.setBackgroundResource(R.drawable.greenlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
greenButton.setBackgroundResource(R.drawable.green);
pNum = 1;
}
if (v.getId() == redButton.getId()) { //here is the part where i try to make the buttons change colors
redBeep.start();
redButton.setBackgroundResource(R.drawable.redlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
redButton.setBackgroundResource(R.drawable.red);
pNum = 2;
}
if (v.getId() == blueButton.getId()) { //here is the part where i try to make the buttons change colors
blueBeep.start();
blueButton.setBackgroundResource(R.drawable.bluelightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
blueButton.setBackgroundResource(R.drawable.blue);
pNum = 3;
}
if (v.getId() == yellowButton.getId()) {//here is the part where i try to make the buttons change colors
yellowBeep.start();
yellowButton.setBackgroundResource(R.drawable.yellowlightup);
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
yellowButton.setBackgroundResource(R.drawable.yellow);
pNum = 4;
}
if (!gm.check(pNum, pIndex)) {
beepStop();
SharedPreferences sp = getSharedPreferences("score", Context.MODE_PRIVATE);
Intent i = null;
score = gm.getRandomColors().size()-1;
if(score > sp.getInt("scoreP3",0)) {
i = new Intent(GameActivity.this, InsertScoreActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
else {
i = new Intent(GameActivity.this, GameOverActivity.class);
i.putExtra("score", gm.getRandomColors().size() - 1);
startActivity(i);
}
}
pIndex++;
if (pIndex == gm.getRandomColors().size()) {
Score.setText("" + gm.getRandomColors().size() + "");
gm.addColor();
try {
t.sleep(1000);
// Do some stuff
} catch (Exception e) {
e.getLocalizedMessage();
}
lightUp(0);//it either performs the color change here beofre the lightup function or it just sleeps and doesn't perform the color change at all
}
}
}
}
}
here's the game helper class:
package com.gabie212.simonsays;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by Ronit on 21/02/2018.
*/
public class GameManger {
private GameActivity gActivity;
static Random rnd = new Random();
private ArrayList<Integer> randomColors;
public GameManger(GameActivity mA)
{
randomColors = new ArrayList<Integer>();
this.gActivity =mA;
randomColors.add(getColor());
}
public void addColor()
{
randomColors.add(getColor());
}
public int getColor()
{
return rnd.nextInt(4)+1;
}
public ArrayList<Integer> getRandomColors()
{
return randomColors;
}
public boolean check(int num, int index)
{
return(randomColors.get(index)==num);
}
}
enter code here
I have some problems.
The sleep doesn't perform, does it have something to do with the way I did it in the if statements? Sleep just doesn't happen in the code I have written.
Color change doesn't happen for some reason and I don't know why it doesn't, maybe it has something to do with the thread.sleep.
Color change happens later in the program than its supposed to. Again, I think it has something to do with the sleep but when I removed the sleep, the color change still happens later in the code.

Related

libgdx interstitial ads with admob [duplicate]

I found a Flappy Bird GitHub project and changed it a little bit.
I successfully implemented the AdMob Banner.
But now I also want a Interstitial Ad which pops up when the Game is over (not every time of course) so here is my GitHub project: https://github.com/DaFaack/FlappyBibi
Please explain me how to do it because I can't find a good explanation on the internet.
I want to display the ad in the run() method. You can find it in the core package -> GameplayScreen.java File -> renderPlaying() method and then the run() method.
This is the method i am talking about:
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
What do I have to do to display the Interstitial Ad when the game is over?
This is my AndroidLauncher.java file:
package com.pentagames.flappybibi.android;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.pentagames.flappybibi.FlappyGame;
public class AndroidLauncher extends AndroidApplication{
private static final String TAG = "AndroidLauncher";
protected AdView adView;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView=initializeForView(new FlappyGame(), config);
layout.addView(gameView);
adView = new AdView(this);
adView.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
int visibility = adView.getVisibility();
adView.setVisibility(AdView.GONE);
adView.setVisibility(AdView.VISIBLE);
Log.i(TAG, "Ad Loaded...");
}
});
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXX/XXXXXXXXX");
AdRequest.Builder builder = new AdRequest.Builder();
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
layout.addView(adView, adParams);
adView.loadAd(builder.build());
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
adView.resume();
}
#Override
protected void onPause() {
super.onPause();
adView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
}
And this the GameplayScreen file:
package com.pentagames.flappybibi;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
public class GameplayScreen extends ScreenAdapter{
public static final float PIPE_SPACING = 200f;
public static final int PIPE_SETS = 3;
protected OrthographicCamera camera;
protected com.pentagames.flappybibi.FlappyGame game;
private Stage gameplayStage;
private Stage uiStage;
private Label scoreLabel;
private Label tapToRetry;
private Label best;
private Label tapToFlap;
private Image whitePixel;
private Image backgroundBuildings;
private int score;
private Bird bird;
private Array<PipePair> pipePairs;
private com.pentagames.flappybibi.Ground ground;
private boolean justTouched;
private Color backgroundColor;
private State screenState = State.PREGAME;
private boolean allowRestart = false;
private enum State {PREGAME, PLAYING, DYING, DEAD}
public GameplayScreen(com.pentagames.flappybibi.FlappyGame game) {
this.game = game;
camera = new OrthographicCamera(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT, camera));
uiStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT));
bird = new Bird();
bird.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH * .25f, com.pentagames.flappybibi.FlappyGame.HEIGHT / 2, Align.center);
bird.addAction(Utils.getFloatyAction());
bird.setState(Bird.State.PREGAME);
whitePixel = new Image(com.pentagames.flappybibi.Assets.whitePixel);
scoreLabel = new Label("0", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
uiStage.addActor(scoreLabel);
tapToRetry = new Label("Nochmal?", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToRetry.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(tapToRetry);
best = new Label("Highscore: ", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
best.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(best);
tapToFlap = new Label("Fass mich an!", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToFlap.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom);
uiStage.addActor(tapToFlap);
initBackgroundBuildings();
pipePairs = new Array<PipePair>();
ground = new com.pentagames.flappybibi.Ground();
ground.setPosition(0, 0);
backgroundColor = Utils.getRandomBackgroundColor();
// The order actors are added determines the order they are drawn so make sure the background is first
gameplayStage.addActor(ground);
gameplayStage.addActor(backgroundBuildings);
gameplayStage.addActor(bird);
// Setup the input processor
initInputProcessor();
}
private void initBackgroundBuildings() {
backgroundBuildings = new Image(com.pentagames.flappybibi.Assets.backgroundBuildings);
backgroundBuildings.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
backgroundBuildings.setHeight(backgroundBuildings.getHeight()*2f);
backgroundBuildings.setY(com.pentagames.flappybibi.Ground.HEIGHT);
}
#Override
public void show() {
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y + 100f, Align.center, .75f, Interpolation.sine));
com.pentagames.flappybibi.Assets.playWooshSound();
}
#Override
public void render(float delta) {
Gdx.graphics.getGL20().glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1f);
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
switch (screenState) {
case PREGAME:
updateAndDrawStages();
break;
case PLAYING:
renderPlaying();
break;
case DYING:
case DEAD:
renderDeadOrDying();
break;
}
}
private void renderDeadOrDying() {
if (bird.getState() == Bird.State.DEAD) {
screenState = State.DEAD;
}
updateAndDrawStages();
}
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
SequenceAction actions = Actions.sequence(Actions.delay(1f), playWooshAction, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.bottom,
.75f, Interpolation.sine), Actions.run(new Runnable() {
#Override
public void run() {
// Allow the player to restart the game once the tap to retry finishes coming up
allowRestart = true;
}
}));
tapToRetry.addAction(actions);
best.setText("Highscore: " + com.pentagames.flappybibi.SavedDataManager.getInstance().getHighScore());
best.setWidth(best.getTextBounds().width);
best.setPosition(com.pentagames.flappybibi.FlappyGame.CENTER_X, 0, Align.top);
best.addAction(Actions.delay(1f, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.top,
.75f, Interpolation.sine)));
screenState = State.DYING;
}
gameplayStage.draw();
uiStage.draw();
}
private void updateAndDrawStages() {
gameplayStage.act();
gameplayStage.draw();
uiStage.act();
uiStage.draw();
}
#Override
public void resize(int width, int height) {
camera.setToOrtho(false, width, height);
com.pentagames.flappybibi.Assets.batch.setProjectionMatrix(camera.combined);
gameplayStage.getViewport().update(width, height, true);
uiStage.getViewport().update(width, height, true);
}
#Override
public void dispose() {
gameplayStage.dispose();
uiStage.dispose();
}
private void checkCollisions() {
for (int i = 0; i < pipePairs.size; i++) {
PipePair pair = pipePairs.get(i);
if (pair.getBottomPipe().getBounds().overlaps(bird.getBounds()) || pair.getTopPipe().getBounds().overlaps(bird.getBounds())) {
stopTheWorld();
com.pentagames.flappybibi.SavedDataManager.getInstance().setHighScore(score);
showWhiteScreen();
} else if (bird.isBelowGround()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.GROUND_LEVEL);
bird.clearActions();
bird.setToDying();
showWhiteScreen();
} else if (bird.isAboveCeiling()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.HEIGHT - bird.getHeight());
bird.setToDying();
showWhiteScreen();
} else if (pair.getRuby().getBounds().overlaps(bird.getBounds())) {
score++;
updateScoreLabel();
pair.moveCoinOffscreen();
com.pentagames.flappybibi.Assets.playBingSound();
}
}
}
private void showWhiteScreen() {
whitePixel.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
whitePixel.setHeight(com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage.addActor(whitePixel);
whitePixel.addAction(Actions.fadeOut(.5f));
}
private void updateScoreLabel() {
scoreLabel.setText(String.valueOf(score));
scoreLabel.setWidth(scoreLabel.getTextBounds().width);
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
}
private void stopTheWorld() {
bird.setToDying();
killPipePairs();
stopTheGround();
screenState = State.DYING;
}
private void stopTheGround() {
ground.vel.x = 0;
}
private void killPipePairs() {
for (PipePair pair : pipePairs) {
pair.getBottomPipe().setState(Pipe.State.dead);
pair.getTopPipe().setState(Pipe.State.dead);
pair.getRuby().setVel(0, 0);
}
}
private void updatePipePairs() {
for (int i = 0; i < pipePairs.size; i++) {
pipePairs.get(i).update();
}
}
private void addPipes(Stage gameplayStage) {
for (int i = 0; i < pipePairs.size; i++) {
gameplayStage.addActor(pipePairs.get(i).getBottomPipe());
gameplayStage.addActor(pipePairs.get(i).getTopPipe());
gameplayStage.addActor(pipePairs.get(i).getRuby());
}
}
private void initThirdSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initThird();
// add the pair to the list
pipePairs.add(pair);
}
private void initSecondSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initSecond();
// add the pair to the list
pipePairs.add(pair);
}
private void initFirstSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initFirst();
// add the pair to the list
pipePairs.add(pair);
}
/**
* Tells libgdx to listen for inputs coming from the InputAdapter we give it
*/
private void initInputProcessor() {
Gdx.input.setInputProcessor(new InputAdapter() {
// We only care about the touch down event
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
switch (screenState) {
case DYING:
justTouched = true;
break;
case DEAD:
if (allowRestart) {
game.setScreen(new GameplayScreen(game));
}
justTouched = true;
break;
case PLAYING:
justTouched = true;
break;
case PREGAME:
justTouched = true;
screenState = State.PLAYING;
bird.setState(Bird.State.ALIVE);
bird.clearActions();
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom, .75f, Interpolation.sine));
initFirstSetOfPipes();
initSecondSetOfPipes();
initThirdSetOfPipes();
addPipes(gameplayStage);
gameplayStage.addActor(ground);
gameplayStage.addActor(bird);
break;
}
return true;
}
});
}
}
This is the first time that I'm working with LibGDX, would be great if you can explain me how to implement the Interstitial Ad in this project.
Sorry for my bad English.
You already integrated banner Ad so no need to injected dependent artifact in your project.
Follow these steps for Interstitial Ad integration.
AndroidManifest.xml
Make an entry of AdActivity for Interstitial Ad
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
Create an interface inside your core module
public interface AdService {
boolean isInterstitialLoaded();
void showInterstitial();
}
Create a parameterized constructor of FlappyGame class
public AdService adService;
public FlappyGame(AdService ads){
adService=ads;
}
Implement AdService interface to your AndroidLauncher class
public class AndroidLauncher extends AndroidApplication implements AdService {
private static final String AD_UNIT_ID_INTERSTITIAL = "ca-app-pub-XXXXX/XXXXX";
private InterstitialAd interstitialAd;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
View gameView=initializeForView(new FlappyGame(this), config);
...
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {}
#Override
public void onAdClosed() {
loadIntersitialAd();
}
});
loadIntersitialAd();
}
private void loadIntersitialAd(){
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
#Override
public void showInterstitial() {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded())
interstitialAd.show();
else
loadIntersitialAd();
}
});
}
#Override
public boolean isInterstitialLoaded() {
return interstitialAd.isLoaded();
}
}
GameScreen class
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
game.adService.showInterstitial();
}
});
I integrated Interstitial Ad in your project, created a pull request for the same. You can merge my pull request.

How to display a Interstitial Ad in a LibGDX project?

I found a Flappy Bird GitHub project and changed it a little bit.
I successfully implemented the AdMob Banner.
But now I also want a Interstitial Ad which pops up when the Game is over (not every time of course) so here is my GitHub project: https://github.com/DaFaack/FlappyBibi
Please explain me how to do it because I can't find a good explanation on the internet.
I want to display the ad in the run() method. You can find it in the core package -> GameplayScreen.java File -> renderPlaying() method and then the run() method.
This is the method i am talking about:
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
What do I have to do to display the Interstitial Ad when the game is over?
This is my AndroidLauncher.java file:
package com.pentagames.flappybibi.android;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.pentagames.flappybibi.FlappyGame;
public class AndroidLauncher extends AndroidApplication{
private static final String TAG = "AndroidLauncher";
protected AdView adView;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView=initializeForView(new FlappyGame(), config);
layout.addView(gameView);
adView = new AdView(this);
adView.setAdListener(new AdListener(){
#Override
public void onAdLoaded(){
int visibility = adView.getVisibility();
adView.setVisibility(AdView.GONE);
adView.setVisibility(AdView.VISIBLE);
Log.i(TAG, "Ad Loaded...");
}
});
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXX/XXXXXXXXX");
AdRequest.Builder builder = new AdRequest.Builder();
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
layout.addView(adView, adParams);
adView.loadAd(builder.build());
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
adView.resume();
}
#Override
protected void onPause() {
super.onPause();
adView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
}
And this the GameplayScreen file:
package com.pentagames.flappybibi;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.viewport.StretchViewport;
public class GameplayScreen extends ScreenAdapter{
public static final float PIPE_SPACING = 200f;
public static final int PIPE_SETS = 3;
protected OrthographicCamera camera;
protected com.pentagames.flappybibi.FlappyGame game;
private Stage gameplayStage;
private Stage uiStage;
private Label scoreLabel;
private Label tapToRetry;
private Label best;
private Label tapToFlap;
private Image whitePixel;
private Image backgroundBuildings;
private int score;
private Bird bird;
private Array<PipePair> pipePairs;
private com.pentagames.flappybibi.Ground ground;
private boolean justTouched;
private Color backgroundColor;
private State screenState = State.PREGAME;
private boolean allowRestart = false;
private enum State {PREGAME, PLAYING, DYING, DEAD}
public GameplayScreen(com.pentagames.flappybibi.FlappyGame game) {
this.game = game;
camera = new OrthographicCamera(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT, camera));
uiStage = new Stage(new StretchViewport(com.pentagames.flappybibi.FlappyGame.WIDTH, com.pentagames.flappybibi.FlappyGame.HEIGHT));
bird = new Bird();
bird.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH * .25f, com.pentagames.flappybibi.FlappyGame.HEIGHT / 2, Align.center);
bird.addAction(Utils.getFloatyAction());
bird.setState(Bird.State.PREGAME);
whitePixel = new Image(com.pentagames.flappybibi.Assets.whitePixel);
scoreLabel = new Label("0", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
uiStage.addActor(scoreLabel);
tapToRetry = new Label("Nochmal?", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToRetry.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(tapToRetry);
best = new Label("Highscore: ", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
best.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, 0, Align.top);
uiStage.addActor(best);
tapToFlap = new Label("Fass mich an!", new Label.LabelStyle(com.pentagames.flappybibi.Assets.fontMedium, Color.WHITE));
tapToFlap.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom);
uiStage.addActor(tapToFlap);
initBackgroundBuildings();
pipePairs = new Array<PipePair>();
ground = new com.pentagames.flappybibi.Ground();
ground.setPosition(0, 0);
backgroundColor = Utils.getRandomBackgroundColor();
// The order actors are added determines the order they are drawn so make sure the background is first
gameplayStage.addActor(ground);
gameplayStage.addActor(backgroundBuildings);
gameplayStage.addActor(bird);
// Setup the input processor
initInputProcessor();
}
private void initBackgroundBuildings() {
backgroundBuildings = new Image(com.pentagames.flappybibi.Assets.backgroundBuildings);
backgroundBuildings.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
backgroundBuildings.setHeight(backgroundBuildings.getHeight()*2f);
backgroundBuildings.setY(com.pentagames.flappybibi.Ground.HEIGHT);
}
#Override
public void show() {
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y + 100f, Align.center, .75f, Interpolation.sine));
com.pentagames.flappybibi.Assets.playWooshSound();
}
#Override
public void render(float delta) {
Gdx.graphics.getGL20().glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, 1f);
Gdx.graphics.getGL20().glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
switch (screenState) {
case PREGAME:
updateAndDrawStages();
break;
case PLAYING:
renderPlaying();
break;
case DYING:
case DEAD:
renderDeadOrDying();
break;
}
}
private void renderDeadOrDying() {
if (bird.getState() == Bird.State.DEAD) {
screenState = State.DEAD;
}
updateAndDrawStages();
}
private void renderPlaying() {
if (justTouched) {
bird.jump();
justTouched = false;
}
updatePipePairs();
gameplayStage.act();
uiStage.act();
checkCollisions();
if (bird.getState() == Bird.State.DYING) {
stopTheWorld();
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
//Here I want to display the Interstitial Ad!
}
});
SequenceAction actions = Actions.sequence(Actions.delay(1f), playWooshAction, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.bottom,
.75f, Interpolation.sine), Actions.run(new Runnable() {
#Override
public void run() {
// Allow the player to restart the game once the tap to retry finishes coming up
allowRestart = true;
}
}));
tapToRetry.addAction(actions);
best.setText("Highscore: " + com.pentagames.flappybibi.SavedDataManager.getInstance().getHighScore());
best.setWidth(best.getTextBounds().width);
best.setPosition(com.pentagames.flappybibi.FlappyGame.CENTER_X, 0, Align.top);
best.addAction(Actions.delay(1f, Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.CENTER_Y, Align.top,
.75f, Interpolation.sine)));
screenState = State.DYING;
}
gameplayStage.draw();
uiStage.draw();
}
private void updateAndDrawStages() {
gameplayStage.act();
gameplayStage.draw();
uiStage.act();
uiStage.draw();
}
#Override
public void resize(int width, int height) {
camera.setToOrtho(false, width, height);
com.pentagames.flappybibi.Assets.batch.setProjectionMatrix(camera.combined);
gameplayStage.getViewport().update(width, height, true);
uiStage.getViewport().update(width, height, true);
}
#Override
public void dispose() {
gameplayStage.dispose();
uiStage.dispose();
}
private void checkCollisions() {
for (int i = 0; i < pipePairs.size; i++) {
PipePair pair = pipePairs.get(i);
if (pair.getBottomPipe().getBounds().overlaps(bird.getBounds()) || pair.getTopPipe().getBounds().overlaps(bird.getBounds())) {
stopTheWorld();
com.pentagames.flappybibi.SavedDataManager.getInstance().setHighScore(score);
showWhiteScreen();
} else if (bird.isBelowGround()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.GROUND_LEVEL);
bird.clearActions();
bird.setToDying();
showWhiteScreen();
} else if (bird.isAboveCeiling()) {
bird.setY(com.pentagames.flappybibi.FlappyGame.HEIGHT - bird.getHeight());
bird.setToDying();
showWhiteScreen();
} else if (pair.getRuby().getBounds().overlaps(bird.getBounds())) {
score++;
updateScoreLabel();
pair.moveCoinOffscreen();
com.pentagames.flappybibi.Assets.playBingSound();
}
}
}
private void showWhiteScreen() {
whitePixel.setWidth(com.pentagames.flappybibi.FlappyGame.WIDTH);
whitePixel.setHeight(com.pentagames.flappybibi.FlappyGame.HEIGHT);
gameplayStage.addActor(whitePixel);
whitePixel.addAction(Actions.fadeOut(.5f));
}
private void updateScoreLabel() {
scoreLabel.setText(String.valueOf(score));
scoreLabel.setWidth(scoreLabel.getTextBounds().width);
scoreLabel.setPosition(com.pentagames.flappybibi.FlappyGame.WIDTH / 2, com.pentagames.flappybibi.FlappyGame.HEIGHT * .9f, Align.center);
}
private void stopTheWorld() {
bird.setToDying();
killPipePairs();
stopTheGround();
screenState = State.DYING;
}
private void stopTheGround() {
ground.vel.x = 0;
}
private void killPipePairs() {
for (PipePair pair : pipePairs) {
pair.getBottomPipe().setState(Pipe.State.dead);
pair.getTopPipe().setState(Pipe.State.dead);
pair.getRuby().setVel(0, 0);
}
}
private void updatePipePairs() {
for (int i = 0; i < pipePairs.size; i++) {
pipePairs.get(i).update();
}
}
private void addPipes(Stage gameplayStage) {
for (int i = 0; i < pipePairs.size; i++) {
gameplayStage.addActor(pipePairs.get(i).getBottomPipe());
gameplayStage.addActor(pipePairs.get(i).getTopPipe());
gameplayStage.addActor(pipePairs.get(i).getRuby());
}
}
private void initThirdSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initThird();
// add the pair to the list
pipePairs.add(pair);
}
private void initSecondSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initSecond();
// add the pair to the list
pipePairs.add(pair);
}
private void initFirstSetOfPipes() {
Pipe topPipe = new Pipe();
Pipe bottomPipe = new Pipe();
topPipe.getRegion().flip(false, true);
PipePair pair = new PipePair(topPipe, bottomPipe);
pair.initFirst();
// add the pair to the list
pipePairs.add(pair);
}
/**
* Tells libgdx to listen for inputs coming from the InputAdapter we give it
*/
private void initInputProcessor() {
Gdx.input.setInputProcessor(new InputAdapter() {
// We only care about the touch down event
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
switch (screenState) {
case DYING:
justTouched = true;
break;
case DEAD:
if (allowRestart) {
game.setScreen(new GameplayScreen(game));
}
justTouched = true;
break;
case PLAYING:
justTouched = true;
break;
case PREGAME:
justTouched = true;
screenState = State.PLAYING;
bird.setState(Bird.State.ALIVE);
bird.clearActions();
tapToFlap.addAction(Actions.moveToAligned(com.pentagames.flappybibi.FlappyGame.CENTER_X, com.pentagames.flappybibi.FlappyGame.HEIGHT, Align.bottom, .75f, Interpolation.sine));
initFirstSetOfPipes();
initSecondSetOfPipes();
initThirdSetOfPipes();
addPipes(gameplayStage);
gameplayStage.addActor(ground);
gameplayStage.addActor(bird);
break;
}
return true;
}
});
}
}
This is the first time that I'm working with LibGDX, would be great if you can explain me how to implement the Interstitial Ad in this project.
Sorry for my bad English.
You already integrated banner Ad so no need to injected dependent artifact in your project.
Follow these steps for Interstitial Ad integration.
AndroidManifest.xml
Make an entry of AdActivity for Interstitial Ad
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
Create an interface inside your core module
public interface AdService {
boolean isInterstitialLoaded();
void showInterstitial();
}
Create a parameterized constructor of FlappyGame class
public AdService adService;
public FlappyGame(AdService ads){
adService=ads;
}
Implement AdService interface to your AndroidLauncher class
public class AndroidLauncher extends AndroidApplication implements AdService {
private static final String AD_UNIT_ID_INTERSTITIAL = "ca-app-pub-XXXXX/XXXXX";
private InterstitialAd interstitialAd;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
View gameView=initializeForView(new FlappyGame(this), config);
...
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {}
#Override
public void onAdClosed() {
loadIntersitialAd();
}
});
loadIntersitialAd();
}
private void loadIntersitialAd(){
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
#Override
public void showInterstitial() {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded())
interstitialAd.show();
else
loadIntersitialAd();
}
});
}
#Override
public boolean isInterstitialLoaded() {
return interstitialAd.isLoaded();
}
}
GameScreen class
RunnableAction playWooshAction = Actions.run(new Runnable() {
#Override
public void run() {
com.pentagames.flappybibi.Assets.playWooshSound();
game.adService.showInterstitial();
}
});
I integrated Interstitial Ad in your project, created a pull request for the same. You can merge my pull request.

ProgressDialog not starting - Android (java)

I'm trying to make simple app on Android.
EDIT
New code:
package com.sirseni.simpleandroidwebviewexample;
/**
* Created by otsma on 26.05.2017.
*/
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Hack extends Activity {
Button b1;
private ProgressDialog progress;
// Splash screen timer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hack);
b1 = (Button) findViewById(R.id.button);
}
private int jumpTime = 0;
public void download() {
//initializing progress dialog
progress = new ProgressDialog(this);
progress.setMessage("Changing Files");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.show();
final int totalProgressTime = 100;
//creating a thread
final Thread t = new Thread() {
#Override
public void run() {
while(jumpTime < totalProgressTime) {
try {
jumpTime += 5;
// if we have to update the view, we have to execute the code in UI thread. runOnUiThread() gives us that functionality
runOnUiThread(new Runnable() {
#Override
public void run() {
// updating view in UI thread
progress.setProgress(jumpTime);
progress.setMessage("Hello" + jumpTime);
}
});
sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}}
Now it's working like that, user tap on button, the progressdialog is appearing but everytime it is 0% and 0/100. How to fix it? For example after 20 seconds will be 100% and how to make, that when it reach 100% the new activity is starting?
Thanks guys for help!
Please update the download method by the below code:
private int jumpTime = 0;
public void download() {
//initializing progress dialog
progress = new ProgressDialog(this);
progress.setMessage("Changing Files");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.show();
final int totalProgressTime = 100;
//creating a thread
final Thread t = new Thread() {
#Override
public void run() {
while(jumpTime < totalProgressTime) {
try {
jumpTime += 5;
// if we have to update the view, we have to execute the code in UI thread. runOnUiThread() gives us that functionality
runOnUiThread(new Runnable() {
#Override
public void run() {
// updating view in UI thread
progress.setProgress(jumpTime);
progress.setMessage("Hello" + jumpTime);
}
});
sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
t.start();
}
Try this.
progress = new ProgressDialog(this);
progress.setMessage("Changing Files");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setMax(100);
progress.setProgress(0);
progress.show();
int jumpTime = 0;
Handler ha = new Handler();
ha.post(new Runnable() {
#Override
public void run() {
//call function
jumpTime += 5;
progress.setProgress(jumpTime);
progress.setMessage("Hello" + jumpTime);
if(jumpTime < 100){
ha.postDelayed(this, 200);
}
else{
//do code
}
}
});

Two-Dimensional Array with JSON data - Data is downloaded, but I can't access it (?)

So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.

why handlemessage not working

i have a problem with handler in android, i don't understand not display result, this's code:
public class Main extends Activity implements OnClickListener {
private EditText nhap;
private Button btTinh;
private Button btHuy;
private TextView kq;
private ProgressDialog progress;
private Handler handle = new Handler();
private int count = 0;
private String s = "";
private long n;
handlemessage:
Handler mhandle = new Handler() {
#Override
public void handleMessage(Message msg) {
kq.setText(msg.obj.toString());
}
};
onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nhap = (EditText) findViewById(R.id.nhap);
btTinh = (Button) findViewById(R.id.btTinh);
btHuy = (Button) findViewById(R.id.btHuy);
kq = (TextView) findViewById(R.id.kq);
btTinh.setOnClickListener(this);
btHuy.setOnClickListener(this);
}
public boolean checkPrime(long n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
outprime:
public void outPrime(long t) {
// String s="";
progress.setCancelable(true);
progress.setMessage("File downloading ...");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(Integer.parseInt(nhap.getText().toString()));
progress.show();
n = t;
new Thread() {
public void run() {
for (int i = 2; i < n; i++) {
count = i;
if (checkPrime(i))
s = s + i + " ";
handle.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
progress.setProgress(count);
}
});
}
if (count == n - 1) {
progress.dismiss();
Message msg = handle.obtainMessage(1, (String)s);
handle.sendMessage(msg);
}
}
}.start();
}
onclick:
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btTinh:
progress = new ProgressDialog(this);
outPrime(Long.parseLong(nhap.getText().toString()));
break;
case R.id.btHuy:
nhap.setText("");
break;
}
}}
this's handlemessage:
Handler mhandle = new Handler() {
#Override
public void handleMessage(Message msg) {
kq.setText(msg.obj.toString());
}
};
i don't understand handlemessage don't return value, "kq.setText(msg.obj.toString());" don't display to screen, sorry because my english not good
I think the answer for your question is "Watch out your variable's names!" Look - you've created 2 Handlers - named "mhandle" and "handle". You want to parse message in Handler named "mhandle", but in your Thread send it to "handle", which is doing nothing from your code.
Hope it will help if you still trying to find the answer.

Categories

Resources