I don't know how to explain better. I have this timer, and after it finish counting it should call another class (popup) and after that other function in the same class where the counter is.
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
brojacPogresnihOdgovora++;
}
After first pass, my score is 2 instead of 1, then 6, the 14...This delayed method is simply the next question:
Runnable mLaunchTask = new Runnable() {
public void run() {
nextQuestion();
brojacVremena.start();
}
};
I call exactly the same method as the one in onFinish() when user answer wrong and it works fine.
MyCount brojacVremena = new MyCount(6000, 1000);
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
brojacVremena.cancel();
brojacTacnihOdgovora = brojacTacnihOdgovora + 5;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,1200);
}
else{
brojacVremena.cancel();
brojacPogresnihOdgovora++;
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}
};
I found my error. I called my counter twice. Here:
nextQuestion();
brojacVremena.start();
and below in the very same nextQuestion method:
public void nextQuestion() {
brojacVremena.start();
.
.
.
I don't know how that happened.
Related
Two situation for Splash Screen
if ads is enable then Splash Screen time will be 2 seconds and Ads_Fullscreen time will be 8 seconds then final Main Activity will come.
if ads is not enable then Splash Screen time will be 5 seconds and then Main Activity will come.
This is code for splash screen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i;
if (prefManager.isFirstTimeLaunch()){
i = new Intent(SplashScreen.this,WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
}else if(bn_bstatus.equals("enable")) {
i = new Intent(SplashScreen.this,Ads_Fullscreen.class);
}else{
i = new Intent(SplashScreen.this,MainActivity.class);
}
startActivity(i);
finish();
}
},SPLASH_TIME_OUT);
set default SPLASH_TIME_OUT as 5000 milliseconds.
public final int SPLASH_TIME_OUT = 5000;
For SplashScreen Activity
final Intent intent;
if (ads.enable()) {
intent = new Intent(SplashScreen.this, WelcomeActivity.class);
prefManager.setFirstTimeLaunch(false);
} else if (bn_bstatus.equals("enable")) {
intent = new Intent(SplashScreen.this, Ads_Fullscreen.class);
SPLASH_TIME_OUT = 2000;
} else {
intent = new Intent(SplashScreen.this, MainActivity.class);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
For Ads_Fullscreen Activity
SPLASH_TIME_OUT = 8000;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// start MainActivity
}
}, SPLASH_TIME_OUT);
I try auto next activity with countdown timer but not work if use cancel method.
//Next Activity
CountDownTimer myCountDownTimer = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Intent startActivity = new Intent(ActivityNew1.this,ActivityNew2.class);
startActivity(startActivity);
}
}.start();
myCountDownTimer.cancel();
Above java code auto next activity every 1s not working. And I try remove myCountDownTimer.cancel();
//Next Activity
new CountDownTimer(30000, 1000) {
public void onFinish() {
Intent startActivity = new Intent(ActivityNew1.this,ActivityNew2.class);
startActivity(startActivity);
finish();
}
public void onTick(long millisUntilFinished) {
}
}.start();
This java code work for auto next activity but auto next activity run after back to home, auto next not stop.
Solved
I just Add this code on backpress method.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent i = new Intent (this, MainActivity.class);
i.setFlags( Intent.FLAG_ACTIVITY_NO_HISTORY | FLAG_ACTIVITY_CLEAR_TOP );
startActivity( i );
finish();
finishAffinity();
System.exit( 0 );
}
Initialize a global boolean variable
boolean isPause = false;
Declare countdown timer
MyCountDownTimer myCountDownTimer;
Initialize CountDownTimer
myCountDownTimer = new MyCountDownTimer(5000, 1000);
myCountDownTimer.start();
Countdown Timer code
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
if(isPause){
startActivity(new Intent(LoginActivity.this, ForgotPasswordActivity.class));
myCountDownTimer.cancel();
}
}
#Override
public void onFinish() {
// startActivity(new Intent(ConsumerHomeActivity.this, ForgotPasswordCustomerActivity.class));
}
}
When you want to cancel the timer, just do this
isPause = true;
and then the code in onTick will hit and you will be in next activity as countdown timer does not invoke onFinish method.
I've googled already, and all topics say the same solution handler.removeCallbacks(null) or handler.removeCallbacksAndMessages(null). But none of them worked for me.
Handler handler;
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
time -= 100;
if(time == 0){
Intent i = new Intent(Question.this, WrongAnswer.class);
startActivity(i);
finish();
}
else{
handler.postDelayed(this, 100);
}
}
};
handler.postDelayed(runnable,3000);
//...
}
And here is the case where the activity exits before the time runs out:
if(myAnswer == correctAnswer)
{
Intent i = new Intent(this, CorrectAnswer.class);
startActivity(i);
handler.removeCallbacksAndMessages(null);
finish();
}
You need to make your runnable global before handler.removeCallbacks(runnable) would work. Also, you can use a global variable for checking if you cancelled already (this is just for safety)
private boolean isCancelled = false;
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
if (isCancelled) return;
time -= 100;
if(time == 0){
Intent i = new Intent(Question.this, WrongAnswer.class);
startActivity(i);
finish();
}
else{
handler.postDelayed(this, 100);
}
}
};
and then:
isCancelled = true;
handler.removeCallbacks(mRunnable);
Hello it's my first time to develop android color game. However I'd like to put 3 trials in each question. I'm a bit confused how or where to put my while loop in my code. Please have a look on what I have tried so far:
int trial = 0;
private void getCorrectObject() {
List<Integer> objects = new ArrayList<Integer>();
objects.add(1);
objects.add(2);
objects.add(3);
objects.add(4);
objects.add(5);
objects.add(6);
objects.add(7);
objects.add(8);
objects.add(9);
Collections.shuffle(objects);
int correctObject = objects.get(0);
Log.d("test", String.valueOf(correctObject));
while(trial <=3){
trial++;
switch(correctObject)
{
case 1:
bObjectCorrect.setImageResource(R.drawable.stage1_1_object1);
bObjectCorrect.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 2:
bObject1.setImageResource(R.drawable.stage1_1_object1);
bObject1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 3:
bObject2.setImageResource(R.drawable.stage1_1_object1);
bObject2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 4:
bObject3.setImageResource(R.drawable.stage1_1_object1);
bObject3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 5:
bObject4.setImageResource(R.drawable.stage1_1_object1);
bObject4.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 6:
bObject5.setImageResource(R.drawable.stage1_1_object1);
bObject5.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 7:
bObject6.setImageResource(R.drawable.stage1_1_object1);
bObject6.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 8:
bObject7.setImageResource(R.drawable.stage1_1_object1);
bObject7.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
case 9:
bObject8.setImageResource(R.drawable.stage1_1_object1);
bObject8.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Stage1_2.class);
startActivity(i);
new Thread(){
public void run(){
MediaPlayer mp = MediaPlayer.create(Stage1_2.this, R.raw.brown);
mp.start();
}
}.start();
finish();
}
});
break;
} // Last of switch statement
if(trial == 3){
new AlertDialog.Builder(this)
.setTitle("Game Over")
.setMessage("Sorry you reached your 3rd trial")
.setPositiveButton("Try Again?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_2.this, Stage1_1.class);
startActivity(i);
}
})
.setNegativeButton("Back to Menu", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_2.this, ShapingColors.class);
startActivity(i);
}
})
.show();
}
} // end of while loop
I really like to finish this thing so I can continue with the game. Any help is truly appreciated. Thanks in advance.
I added a new method called guessedWrong()
private void guessedWrong(){
trial++;
if(trial == 3){
new AlertDialog.Builder(this)
.setTitle("Game Over")
.setMessage("Sorry you reached your 3rd trial")
.setPositiveButton("Try Again?", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_1.this, Stage1_1.class);
startActivity(i);
}
})
.setNegativeButton("Back to Menu", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Stage1_1.this, ShapingColors.class);
startActivity(i);
}
})
.show();
}
}
The reason you're confused is that you can't use a loop for this task. When using the Java Android framework, each of your callback functions (for example, an onClick listener, or your Activity's onResume) has to run and finish within one frame of the application. Only after the function returns does your app update the screen. This means that if you're doing something like responding to a series of clicks, you can't do that in a loop. You have to handle each click in a separate call to the callback. for and while loops are appropriate if you want to iterate over a list of items to decide what should happen right now (for example, if you're adding items to a ListView), but you can't iterate over things that happen at different times (such as the user's guesses).
You have to think about your Activity like a state machine. Make trial a member variable (field) of the Activity, which starts out at 0. You might have a function guessedWrong() which increments trial, and goes to the "game over" screen if it's greater than 2. The onClick listener for the wrong answers will call this function. When moving to a new question, reset trial to 0.
You also need to make sure the number of trials (which state you're in) is preserved if your Activity is restarted. The lesson Recreating an Activity in the Android Developers' Training offered by Google shows you how to do this.
I accidently discovered this. I have a quiz game, and i have a popup for correct answer, for wrong answer and after the game finish I have a popup for result. BUT, today i went back with back button in the middle of the game, to my home screen (not game home screen, my OS home screen) and the game was still in the background, like every other android app. After a few second my wrong answer popped up. :) Time was up, and automatically the answer was wrong. After that my final result popup went on. So, how can I kill that activity when I press back button? I don't know if you guys need any of my code, but just in case here's my game activity:
public class NeogranicenoPetGresaka extends Activity implements OnClickListener{
MyCount brojacVremena = new MyCount(6000, 1000);
LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();
private String generateWhereClause(){
StringBuilder result = new StringBuilder();
for (Long l : mAnsweredQuestions){
result.append(" AND _ID <> " + l);
}
return result.toString();
}
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4;
TextView question, netacniOdg, score, countdown;
int brojacPogresnihOdgovora = 0;
int brojacTacnihOdgovora = 0;
public static String tacanOdg;
Runnable mLaunchTask = new Runnable() {
public void run() {
nextQuestion();
brojacVremena.start();
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
brojacVremena.cancel();
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
brojacVremena.cancel();
brojacTacnihOdgovora = brojacTacnihOdgovora + 5;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,1200);
}
/*else{
brojacVremena.cancel();
brojacPogresnihOdgovora++;
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}*/
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.neograniceno);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "myriad.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKvizaN);
netacniOdg = (TextView) findViewById(R.id.tvBrojPitanjaN);
question = (TextView) findViewById(R.id.tvPitanjeN);
bOdgovor1 = (Button) findViewById(R.id.bOdgovorN1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovorN2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovorN3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovorN4);
score = (TextView) findViewById(R.id.tvSkor2N);
countdown = (TextView) findViewById(R.id.tvCountdownN);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
netacniOdg.setTypeface(dugmad);
question.setTypeface(pitanje);
score.setTypeface(dugmad);
countdown.setTypeface(dugmad);
nextQuestion(); //startuje prvo pitanje!
brojacVremena.start(); //startuje brojac vremena
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
brojacPogresnihOdgovora++;
Intent i = new Intent(getApplicationContext(), PogresanOdgovor.class);
i.putExtra("tacanOdgovor", tacanOdg);
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}
#Override
public void onTick(long millisUntilFinished) {
countdown.setText("" + millisUntilFinished / 1000);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void nextQuestion() {
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
tacanOdg = c.getString(2);
if(brojacPogresnihOdgovora < 20){
question.setText(c.getString(1));
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
netacniOdg.setText("" + brojacPogresnihOdgovora);
score.setText("Score: " + brojacTacnihOdgovora);
}
else{
brojacVremena.cancel();
Intent i = new Intent(getApplicationContext(), Rezultat.class);
i.putExtra("noviRezultat", brojacTacnihOdgovora);
startActivity(i);
String brojacTacnihOdgovoraString = String.valueOf(brojacTacnihOdgovora);
mHandler.postDelayed(mLaunchTaskFinish,4000);
//SwarmLeaderboard.submitScore(6863, brojacTacnihOdgovora);
HeyzapLib.submitScore(this, brojacTacnihOdgovoraString, "Osvojili ste " + brojacTacnihOdgovoraString + " poena!", "1T3");
}
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
I tried placing this in my code, but it didn't work:
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
Also tried this, it didn't work:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
finish();
}
return super.onKeyDown(keyCode, event);
}
The issue us that the activity is stopped but the background threads you've created are left running. So you need to override onStop and cancel any background threads.
Something like:
#Override public void onStop() {
super.onStop();
brojacVremena.cancel();
}
Intent a = new Intent(this,"another activity class to go to");
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)|Intent.FLAG_ACTIVITY_NO_HISTORY);//leaves no history of the activity and clears the backstack.
startActivity(a);
finish();
Also have a look at this link http://developer.android.com/training/basics/activity-lifecycle/index.html.
To learn about activity back stack http://developer.android.com/guide/components/tasks-and-back-stack.html. The combination of the link above should give you an insight of what you want to do to solve your problem