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. :)
Related
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");
}
}
});
I'm a beginner in android application. I want to make android quiz application with a timer. Every question has a timer and resets in every next question. How can I input countdown timer with my java activity?
Here's my code:
public class QuizHistoryActivity extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1, answerBtn2, answerBtn3;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 10;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData [][] = {
{"Question random", "correctanswer",
"choice a", "choice b", "choice c"},
{"Question random", "correct answer",
"choice a,""choice b","choice c"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_history);
countLabel = (TextView)findViewById(R.id.countlabel);
questionLabel= (TextView)findViewById(R.id.questionlabel);
answerBtn1 = (Button)findViewById(R.id.answerbtn1);
answerBtn2 = (Button)findViewById(R.id.answerbtn2);
answerBtn3 = (Button)findViewById(R.id.answerbtn3);
//Create quizArray from quizdata
for (int i = 0; i < quizData.length; i++) {
//Prepare array
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]);
tmpArray.add(quizData[i][1]);
tmpArray.add(quizData[i][2]);
tmpArray.add(quizData[i][3]);
tmpArray.add(quizData[i][4]);
//Add tmpArray to quizArray
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz () {
//Update quizCountLabel
countLabel.setText("Question #" + quizCount);
//Generate random number between 0 and 14 (Quiz Array's size -1)
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
//Pick ine quiz set
ArrayList<String> quiz = quizArray.get(randomNum);
//Set question and right answer
//array format
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
//remove "country" from quiz and shuffle choice
quiz.remove(0);
Collections.shuffle(quiz);
//Set Choices
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
//Remove this quiz from quizArray
quizArray.remove(randomNum);
}
public void checkAnswer (View view) {
//Get pushed button
Button answerBtn = (Button)findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if(btnText.equals(rightAnswer)) {
//Correct!
alertTitle = "Correct!";
rightAnswerCount++;
}else {
//Wrong
alertTitle = "Wrong";
}
//create Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer : \n \t \t" + rightAnswer);
builder.setPositiveButton("Got It!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
//Show Result
Intent resultintent = new Intent(getApplicationContext(), ResultQuizHistoryActivity.class);
resultintent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(resultintent);
}else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}
You can use a Chronometer from the Android framework to show the time in the UI, and:
long start = System.currentTimeMillis();
At the beginning of the quiz, and at the end
long end = System.currentTimeMillis();
long timeTranscurredInMillis = end - start;
...to get the time that the quiz lasted.
here is it
CountDownTimer countDown;
countDown= new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
//call nextQuestionMethod here
}
};
countDown.start();
A 30 Sec timer with 1 sec tick , you can change these values according to your choice. Refer to this link for more details.
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);
}
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(...);
I have a trivia game that is 10 timed questions. A wrong answer is supposed to output 0 points. A correct answer is supposed to output the remaining of the 20,000 milliseconds converted to a 100 point scale.
Right now the game works on the first game. Then, if the user keeps playing for a second time, the points for each question becomes incorrect. For example, incorrect answers begin to have a variety of points from 1 to 100 and also correct answers sometimes have 0 points and also sometimes wrong point totals. So I am guessing some variable is possibly not resetting on the second game so it is causing the points to be a little off.
I posted all the code that deals with the algorithm. My question is how I can get this code to output the correct answer no matter how many times the user plays before closing the app.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter, timeremaining;
AdView adView;
ArrayList<Question> queries;
public static ArrayList<Long> pointsPerQuestion = new ArrayList<Long>(10);
Timer cdTimer;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.questionview);
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);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
questionNumber = (TextView)findViewById(R.id.questionnumber);
timeremaining = (TextView)findViewById(R.id.timeremaining);
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(20000);
tracker.sendView("/QuestionView - Started Quiz");
loadQuestion();
}
public void loadQuestion() {
if(i == 10) {
cdTimer.cancel();
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
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++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
correct();
} else {
wrongAnswers++;
incorrect();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public static ArrayList<Long> getPointsPerQuestion() {
return pointsPerQuestion;
}
public void correct() {
pointsPerQuestion.add(points);
score = score + points;
i++;
loadQuestion();
}
public void incorrect() {
long zero = 0;
pointsPerQuestion.add(zero);
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
points = 0;
if(i >= 9) {
cdTimer.cancel();
pointsPerQuestion.add(points);
endQuiz();
} else {
wrongAnswers++;
incorrect();
}
}
#Override
public void onTick(long millisUntilFinished) {
bar.setProgress((int) millisUntilFinished);
points = millisUntilFinished / 200;
timeremaining.setText("Score remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putExtra("pointsPerQuestion", pointsPerQuestion);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
Here is a Question object:
exodus.add(new Question("6th", "3rd", "5th", "4th", 2, "Name that plague: All livestock dies", -1, "Exodus 9:6"));
In my Results class, which is where the points per question is displayed, this is the line that displays the points:
scoreTV.setText("You received " + QuestionView.getPointsPerQuestion().get(x) + " out of a possible 100 points.");
Everything else is pretty much in my QuestionView above. Let me know if you still need something else.
First 3 Strings are answers A (index 0), B (index 1), C (index 2) and D (index 3). The first int is the correct answer. The 5th String is the question. The second int is set to the answer selected by user during quiz. Last String is the bible verse where the answer is found.