Show button after time (handler?) - java

I'm developing a little app, the idea is that the user clicks a buton in 15 seconds, there's textview which counts how many clicks he does. Now I want to add a restart button, but I want to show it after 15 seconds. Do you guys have any idea how to do that? Here's my code:
final TextView textic = (TextView) findViewById(R.id.textView2);
Typeface fac=Typeface.createFromAsset(getAssets(),"fonts/fipps.otf");
textic.setTypeface(fac);
final int oldscore = getSharedPreferences("myPrefs", MODE_PRIVATE).getInt("highscore", 0);
count = new CountDownTimer(15000, 1000) { // MOVED UP
public void onTick(long millisUntilFinished) {
int seconds = (int) ((millisUntilFinished / 1000));
textic.setText("Time Left: " + millisUntilFinished / 1000);
}
public void onFinish() {
String message;
textic.setText("Time's Up!");
buttonCount.setEnabled(false);
if (clicks > oldscore) {
getSharedPreferences("myPrefs", MODE_PRIVATE).edit().putInt("highscore", clicks).commit();
}
}
};
final TextView textView = (TextView) findViewById(R.id.clicks);
Typeface face=Typeface.createFromAsset(getAssets(),"fonts/fipps.otf");
textView.setTypeface(face);
buttonCount = (ImageButton) findViewById(R.id.button);
buttonCount.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
clicks++;
textView.setText("" + clicks);
TextView textVie = (TextView) findViewById(R.id.topScoreView);
Typeface fa=Typeface.createFromAsset(getAssets(),"fonts/fipps.otf");
textVie.setTypeface(fa);
textVie.setText("Best: " + oldscore);
if(!started){
count.start(); // START COUNTDOWN TIMER
started = true;
timerProcessing = true;
}
}
});
}
}
Could someone please help me, what should I do?

just add the button in your layout like your textview and set it unvisible.Set it visible when time's out(in onfinish()).

This is my code. I used this to hide a layout after 5 seconds,, use this. Hope this will help u
private void HideLayout()
{
swiper=(RelativeLayout)findViewById(R.id.llSwiper);
header=(LinearLayout)findViewById(R.id.llHeader);
swiper.postDelayed(new Runnable()
{
public void run()
{
if(!swiper.isPressed())
{
swiper.setVisibility(View.GONE);
}
else
{
HideLayout();
}
}
}, 5000);
}

Related

Dynamic Text view Adroid Game

I wanted to have a textview that will show the money of the player. But
myMoneyTextView.setText(String.valueOf(acc.getMoney))
doesn't update it I need to reopen the intent to see those changes. I want to change it when the player spend or gain money.
EDIT.
private SubsamplingScaleImageView imageView;
private CustomButton up, down, menu, employ, sales, social, schedule, chart, states, mail;
private TextView comMon, comName;
private DataBase db;
Handler handler = new Handler(Looper.getMainLooper());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_screen);
officeRender();
updateGame();
butThread thread = new butThread();
new Thread(thread).start();
comName = findViewById(R.id.companyname);
comMon = findViewById(R.id.money);
}
public void updateGame() {
handler.post(new Runnable() {
#Override
public void run() {
db = new DataBase(GameScreen.this);
Account acc = db.getAcc();
comName.setText(acc.getName() + " Ent.");
String mon = String.valueOf(acc.getMoney());
if (acc.getMoney() < 100000) {
comMon.setText(mon);
}
else if (acc.getMoney() >= 100000) {
comMon.setText(mon.substring(0, 3) + "k");
}
else if (acc.getMoney() >= 1000000) {
comMon.setText(mon.substring(0, 3) + "m");
}
}
});

First and Second guessings are the same

I am new to Java and I am developing a Number Guessing Game. When I click the random button , I get a random number that's okay but When I try this second time, second and first random numbers are the same.
How can I solve it? Here is my code:
int KullaniciTahmini;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView Sayi = (TextView) findViewById(R.id.Sayi);
Button Tamam = (Button) findViewById(R.id.Tamam);
final Button Rastgele = (Button) findViewById(R.id.Rastgele);
final EditText Tahmin = (EditText) findViewById(R.id.Tahmin);
final int gizliSayi = 0 + (int)(Math.random() * 100);
Rastgele.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int)(Math.random() * 100);
Sayi.setText("Lutfen 0 ile 100 arasinda bir deger giriniz!");
}
});
Tamam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int KullaniciTahmini = Integer.parseInt(Tahmin.getText().toString());
if (KullaniciTahmini < gizliSayi) {
Sayi.setText("Degeri Buyult");
}
if (KullaniciTahmini > gizliSayi) {
Sayi.setText("Degeri Kucult");
}
if (KullaniciTahmini == gizliSayi) {
Sayi.setText("Dogru Cevap!");
}
}
});
}
You only assign to gizliSayi once, in onCreate:
final int gizliSayi = 0 + (int)(Math.random() * 100);
I think you want to remove the final there and then update that value in Rastgele.setOnClickListener by changing this line:
int random = (int)(Math.random() * 100);
to this:
gizliSayi = (int)(Math.random() * 100);

Timer code crashes my app

I'm learning android development, and what I'm trying to do is to have a label that counts down from 40 minutes, and when it reaches 0 it would stop counting and do something else. This is my code:
#Override
protected void onStart() {
super.onStart();
count = 2400;
final Timer t = new Timer();//Create the object
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
minLeft = (int) Math.floor(count / 60);
secLeft = count - minLeft * 60;
counter = minLeft + ":" + secLeft;
TextView tv = (TextView) findViewById(R.id.timer);
Log.i(MainActivity.TAG,minLeft+", "+secLeft+", "+counter);
tv.setText(counter);
count--;
if (minLeft <= 0 && secLeft <= 0) {
t.cancel();
count = 2400;
onFinish();
}
}
}, 1000, 1000);
}
But, when I go to that activity by clicking a button in the main activity, the label has the text "Timer" (its original text), and after a few seconds the app crashes with CalledFromWrongThreadException, but the line that causes the problem seems to be the one where I set the text of the TextView.
Please help, thanks in advance.
Your scheduled task runs on the background thread.
And you try to set the text to the textview from this background thread.
However in Android all view related operations have to be done on the main thread.
That is way in your scheduled task you have to use something like:
#Override
protected void onStart() {
super.onStart();
count = 2400;
final Timer t = new Timer();//Create the object
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
minLeft = (int) Math.floor(count / 60);
secLeft = count - minLeft * 60;
counter = minLeft + ":" + secLeft;
// the name of your actual activity
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
TextView tv = (TextView) findViewById(R.id.timer);
Log.i(MainActivity.TAG,minLeft+", "+secLeft+", "+counter);
tv.setText(counter);
}
});
count--;
if (minLeft <= 0 && secLeft <= 0) {
t.cancel();
count = 2400;
onFinish();
}
}
}, 1000, 1000);
}
Please also note, that this code can be written more elegantly, without all/so many anonymous classes, but it should do the trick.

CountDownTimer Android issue

I'm trying to implement a CountDownTimer in an Android Application. This timer will, while running, countdown from a value, than reset, than countdown from a different value. Switching back and force between values until either a set number of rounds have elapsed or the stop button has been pressed. I can get the CountDownTimer samples to work, but I guess I'm missing something here. Below is the applicable button press code;
CounterState state = CounterState.WORKOUT;
private WorkoutTimer workoutTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_stopwatch);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set up OnClickListeners
((Button) findViewById(R.id.start_button)).setOnClickListener(this);
((Button) findViewById(R.id.stop_button)).setOnClickListener(this);
((Button) findViewById(R.id.reset_button)).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.start_button:
if (!timer_running) {
timer_running = true;
Log.d(TAG, "clicked on Start Button");
// If the state is unknown, set it to Workout first
int State = state.getStateValue();
if (State == 0) {
state.setStateValue(1);
}
workoutTimer.start();
}
break;
case R.id.stop_button:
Log.d(TAG, "clicked on Stop Button");
if (timer_running); {
timer_running = false;
workoutTimer.cancel();
}
break;
private class WorkoutTimer extends CountDownTimer{
public WorkoutTimer(long interval) {
super(getThisTime(), interval);
Log.d(TAG, "WorkoutTimer Constructed...");
}
TextView digital_display = (TextView) findViewById(R.id.digital_display);
TextView numOfRounds = (TextView) findViewById(R.id.number_of_rounds);
public void onFinish() {
int State = state.getStateValue();
int roundsLeft = 0;
if (State == 1) {
state.setStateValue(2);
} else {
state.setStateValue(1);
}
decrementRounds();
try {
roundsLeft = Integer.parseInt(numOfRounds.getText().toString());
} catch(NumberFormatException nfe) {
roundsLeft = 999;
}
if (roundsLeft > 0 || roundsLeft != 999) {
workoutTimer.start();
}
}
public void onTick(long millisUntilFinished) {
final long minutes_left = ((millisUntilFinished / 1000) / 60);
final long seconds_left = (millisUntilFinished / 1000) - (minutes_left * 60);
final long millis_left = millisUntilFinished % 100;
String time_left = String.format("%02d:%02d.d", minutes_left, seconds_left,
millis_left);
digital_display.setText(time_left);
}
}
private long getThisTime() {
long time = 0;
TextView workout_time = (TextView) findViewById(R.id.workout_time);
TextView rest_time = (TextView) findViewById(R.id.rest_time);
switch(state) {
case WORKOUT:
try {
time = Integer.parseInt(workout_time.getText().toString());
} catch(NumberFormatException nfe) {
time = 999;
}
// time = 90;
Log.d(TAG, "Workout time = " + time);
break;
case REST:
try {
time = Integer.parseInt(rest_time.getText().toString());
} catch(NumberFormatException nfe) {
time = 999;
}
// time = 30;
Log.d(TAG, "Rest time = " + time);
break;
case UNKNOWN:
time = 0;
break;
}
return time;
}
Everything starts up okay, but crashes when I click either button. If I comment out my calls to the workoutTimer, no crash. I never see my log in the constructor of the workoutTimer class, so obviously I'm missing something here. Any help would be appreciated.
-Ian
You have not initialized your workoutTimer. You need to add the following line in your onCreate method.
workoutTimer = new WorkoutTimer(...);

CountDownTimer trivia game score - Android (java)

I have a trivia game that displays 10 questions and they each have a 10 second timer. I have 2 problems that do not function correctly.
Firstly, If the timer runs out on a question, it displays the next question but the timer does not reset. The textviews stay at "Time's up!" and "Time Elapsed: 10000" instead of restarting the timer on the new question that is displayed.
Lastly, on the Results page the correct score is not displayed in the textview. The percentage textview displays correctly but the score textview displays "android.widget.TextView#416473c" or some other random memory location.
The program never crashes just functions incorrectly. Any code structure or other suggestions is much appreciated! This is my first android mobile app attempt and I am slowly and strugglingly through it. Yet enjoying it! :)
QuesteionView.java
public class QuestionView extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
queries = getIntent().getParcelableArrayListExtra("queries");
timer = (TextView)findViewById(R.id.timer);
timeElapsedView = (TextView)findViewById(R.id.timeElapsedView);
cdTimer = new Timer(startTime, interval);
loadQuestion();
}
public void loadQuestion() {
if(i == 9) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.cancel();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
//same type of code for buttons for answers 2 through 4.
}
}
public void nextQuestion() {
score = score + timeElapsed;
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
if(i == 9) {
cdTimer.cancel();
} else {
timer.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
wrongAnswers++;
nextQuestion();
}
}
public void onTick(long millisUntilFinished) {
timer.setText("Time remain: " + Long.toString(millisUntilFinished));
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + Long.toString(timeElapsed));
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
startActivity(intent);
}
}
Results.java
public class Results extends Activity {
QuestionView qv = new QuestionView();
ArrayList<Question> queryList = qv.getQueries();
int cAnswers;
int wAnswers;
long score;
ArrayList<Question> qs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultsmain);
cAnswers = getIntent().getIntExtra("correctAnswers", -1);
wAnswers = getIntent().getIntExtra("wrongAnswers", -1);
score = getIntent().getLongExtra("score", -1);
qs = getIntent().getParcelableArrayListExtra("queries");
Button mainmenuBtn = (Button)findViewById(R.id.mainmenuBtn);
mainmenuBtn.setText("Main Menu");
mainmenuBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
restart();
}
});
showResults();
}
public void showResults() {
ArrayList<TextView> tList = new ArrayList<TextView>(9);
TextView header = (TextView)findViewById(R.id.header);
header.setText("SUMMARY");
TextView percentage = (TextView)findViewById(R.id.percentage);
percentage.setText(Integer.toString(10 * cAnswers) + "%");
TextView score = (TextView)findViewById(R.id.score);
String s = "" + score;
score.setText(s);
TextView q1 = (TextView)findViewById(R.id.q1);
TextView q2 = (TextView)findViewById(R.id.q2);
TextView q3 = (TextView)findViewById(R.id.q3);
TextView q4 = (TextView)findViewById(R.id.q4);
TextView q5 = (TextView)findViewById(R.id.q5);
TextView q6 = (TextView)findViewById(R.id.q6);
TextView q7 = (TextView)findViewById(R.id.q7);
TextView q8 = (TextView)findViewById(R.id.q8);
TextView q9 = (TextView)findViewById(R.id.q9);
TextView q10 = (TextView)findViewById(R.id.q10);
tList.add(q1);
tList.add(q2);
tList.add(q3);
tList.add(q4);
tList.add(q5);
tList.add(q6);
tList.add(q7);
tList.add(q8);
tList.add(q9);
tList.add(q10);
for(int i = 0; i < tList.size(); i++) {
tList.get(i).setText(qs.get(i).getQuery());
if(qs.get(i).getSelectedAnswer() == qs.get(i).getCorrectAnswer()) {
tList.get(i).setTextColor(Color.GREEN);
} else {
tList.get(i).setTextColor(Color.RED);
}
}
}
public void restart() {
Intent intent = new Intent(Results.this, MainMenu.class);
startActivity(intent);
}
}
From all of that code, this is what I think is happening
Firstly, If the timer runs out on a question, it displays the next question but the timer does not reset. The textviews stay at "Time's up!" and "Time Elapsed: 10000" instead of restarting the timer on the new question that is displayed.
This appears to be due to you not setting your timerHasStarted variable to false after the time runs out so I would set that to false probably when you load your next question or after you show the results.
Lastly, on the Results page the correct score is not displayed in the textview. The percentage textview displays correctly but the score textview displays "android.widget.TextView#416473c" or some other random memory location.
This is because you are setting your q variables to the textview and getting the id. You need something like q1.getText().toString()
You have multiple variables with the same name score. So change it to
TextView score2 = (TextView)findViewById(R.id.score);
String s = "" + score;
score2.setText(s);
the score displays not what you expected because you assigned the String s = "" + score where score is what you named for the Textview which obviously not an integer and not equivalent to the score that the user has. :)

Categories

Resources