How to count number of asked questions? - java

I have this activity with question and 4 possible answers, and after each user answer it reloads itself with another question. I placed a textView in the bottom right corner with start value of 1/10 (rezultat.setText(counter+"/10");). I want to increase that value to 2/10, 3/10 and so on, after each question, but I don't know where to put counter++; in my code, and I tried everywhere. Here's my code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class Kviz extends Activity implements View.OnClickListener{
Runnable mLaunchTask = new Runnable() {
public void run() {
startActivity(getIntent());
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4;
TextView question, proba, rezultat;
int counter = 1;
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) {
mHandler.postDelayed(mLaunchTaskFinish, 1200);
mHandler.postDelayed(mLaunchTask,1000);
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
}else{
mHandler.postDelayed(mLaunchTaskFinish, 2200);
mHandler.postDelayed(mLaunchTask,2000);
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.POGRESANODGOVOR");
startActivity(i);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.kviz);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKviza);
rezultat = (TextView) findViewById(R.id.tvBrojPitanja);
question = (TextView) findViewById(R.id.tvPitanje);
bOdgovor1 = (Button) findViewById(R.id.bOdgovor1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovor2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovor3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovor4);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
rezultat.setTypeface(dugmad);
question.setTypeface(pitanje);
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData();
question.setText(c.getString(1));
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);
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);
rezultat.setText(counter+"/10");
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void onClick(View v) {
}
}

what is the mean of "each user answer it reloads itself with another question." ? Are you using different Activities for diff question ?
You can use same activity for all the questions, when user press any of answer's button, just call a method
public void nextQuestion() {
counter++;
question.setText("");
bOdgovor1.setText("");
bOdgovor2.setText("");
bOdgovor3.setText("");
bOdgovor4.setText("");
//reset your next question and all four options here
rezultat.setText(counter + "/10");
}

It's hard to test from here, but it looks like adding counter++ before the line
Answer ans = (Answer) v.getTag();
Should work fine, as this sets counter to increment whenever the button that seems to be responsible for answering questions is clicked. Remember that you'll also need to call
rezultat.setText(counter+"/10");
Again, to update the text to reflect the new value of counter.

To expand my problem a little bit. I did manage to count questions with counter class, it goes to 2/10, but because I reload my activity after each question, my textView also reloads to 1/10. I think that's the main cause of my problem.

Related

Where should I call a method to remove items from a ListView if those items were added through user input from a Popup window?

I have the following code in Android Studio. I'm able to open a popup whenever the "+ New Semester" button is clicked and a new semester is added to the Main Activity once the user types in the semester name in the popup and clicks on the "Done" button. Now, I want to implement a method that removes semesters that are no longer wanted. I made a method called removeSemesters() that I think that does what I want it to do, I haven't been able to test it because I'm not sure where I need to call that method in order to do what I want it to do. Any help would be appreciated! Thank you!
package com.example.gradecalculator;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText semesterName;
private ListView semesterList;
private ArrayList<String> semesterArray = new ArrayList<String>();
private ArrayAdapter<String> semesterAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = new Dialog(this);
}
// When user clicks on "+ New Semester" button open a popup where the user is prompted to
// type in the Semester Name and when "Done" is clicked the new semester appears in the Main
// Activity
public void newSemesterPopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_semester_popup);
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterList = (ListView) findViewById(R.id.semesterList);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSemesters();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adds semesters to Main Activity
public void addSemesters() {
String getSemesterName = semesterName.getText().toString();
if(semesterArray.contains(getSemesterName)) {
Toast.makeText(getBaseContext(), "Semester Name already exists.", Toast.LENGTH_LONG).show();
}
else if(getSemesterName == null || getSemesterName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot add empty Semester Name", Toast.LENGTH_LONG).show();
}
else {
semesterAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, semesterArray);
semesterList.setAdapter(semesterAdapter);
semesterAdapter.add(getSemesterName);
d.dismiss();
}
}
// Removes unwanted semesters from Main Activity
public void removeSemesters() {
semesterList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
SparseBooleanArray positionChecker = semesterList.getCheckedItemPositions();
int counter = semesterList.getCount();
for(int i = counter - 1; i > 1; i--) {
if(positionChecker.get(i)) {
semesterAdapter.remove(semesterArray.get(i));
Toast.makeText(MainActivity.this, "Semester deleted successfully.", Toast.LENGTH_LONG).show();
}
}
positionChecker.clear();
semesterAdapter.notifyDataSetChanged();
return false;
}
});
}
// Opens Main Activity
public void openMainActivity() {
Intent main = new Intent(this, MainActivity.class);
startActivity(main);
}
}
I was able to fix this by myself so in case anyone needs the answer in the future I'll leave it here.
I added the following to the onCreate method and it fixed my problem:
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterList = (ListView) findViewById(R.id.semesterList);
removeSemesters();
Not a hard fix, I thought of it right after posting the questions. Don't know if this is the most efficient way to do it. If not, feel free to give another answer.

Using shared preferences to store high score

It gives me a error cannot resolve symbol sharedpreferences, I'm trying to add a high score for every time the user take the quiz it records the high score of the quiz. I dont know what happen. Please help me with this one and I'll help you with ur reputation.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
public class CS_Assembly_Easy extends Activity{
TextView topscore;
public static final String mypreference = "mypref";
public static final String Topscore = "topKey";
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore) > score) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
public void Save(View view) {
String n = topscore.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Topscore, n);
editor.commit();
}
public void clear(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
topscore.setText("");
}
public void Get(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore)) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > -10){
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}
sharedpreferences is not defined in your CS_Assembly_Easy class.
Try changing your code to this:
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);

how to delay the process/incrementation in Android

I'm creating a android quiz application and what I want to do and know is how to delay the process or incrementation
i want to delay 2seconds before it adds another question
here is my code, i have qid++ there which will add question after the user answer a question. I want to delay it for 2 seconds.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class CS_Assembly_Easy extends Activity{
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
livess = (TextView) findViewById(R.id.livess);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > 1){
lives--;
livess.setText("Lives: " + lives);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}
You might try scheduling a Runnable with Handler.postDelayed(runnable, timeInMilliseconds)
Put the code that should be delayed inside a Runnable.run() method like this:
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// TODO your code here
}
}, 2000L);
See this link Android sleep() without blocking UI
you can use :
handler=new Handler();
Runnable r=new Runnable() {
public void run() {
//your code here
}
};
handler.postDelayed(r, 2000); // waiting for 2s

Android CountDown Timer in Quiz Application

I have made a quiz application which include 5 questions. I have made a ResultActivity page which displays result of the quiz.
I have added a countDown timer of 20 sec for each question. When the Countdown timer finishes it moves to the next question automatically. When the questions are finished it should move to the ResultActivity page to display result.
I have only one issue...
Afetr reaching my last Question..if i does not select any answer and timer is finished the applicaton is not moving to my ResultActivity page..The timer is getting started again and again on the same question until i select any option
Here is my code:
QuizActivity.java
package com.example.triviality;
import java.util.LinkedHashMap;
import java.util.List;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends Activity {
List<question> quesList;
public static int score, correct, wrong, wronganswers;
public boolean isCorrect;
static int qid = 0;
int totalCount = 5;
Question currentQ;
TextView txtQuestion;
RadioGroup radioGroup1;
RadioButton rda, rdb, rdc;
Button butNext;
TextView rt;
boolean nextFlag = false;
boolean isTimerFinished = false;
static LinkedHashMap lhm = new LinkedHashMap();
MyCountDownTimer countDownTimer = new MyCountDownTimer(10000 /* 20 Sec */,
1000);
// final MyCountDownTimer timer = new MyCountDownTimer(20000,1000);
public static String[] Correctanswers = new String[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
DbHelper db = new DbHelper(this);
quesList = db.getAllQuestions();
currentQ = quesList.get(qid);
txtQuestion = (TextView) findViewById(R.id.textView1);
rda = (RadioButton) findViewById(R.id.radio0);
rdb = (RadioButton) findViewById(R.id.radio1);
rdc = (RadioButton) findViewById(R.id.radio2);
butNext = (Button) findViewById(R.id.button1);
// radioGroup1=(RadioGroup)findViewById(R.id.radioGroup1);
setQuestionView();
// timer.start();
rt = (TextView) findViewById(R.id.rt);
rt.setText("20");
countDownTimer.start();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
}
});
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
Log.e("Times up", "Times up");
countDownTimer.cancel();
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
}
#Override
public void onTick(long millisUntilFinished) {
rt.setText((millisUntilFinished / 1000) + "");
Log.e("Second Gone", "Another Second Gone");
Log.e("Time Remaining", "seconds remaining: " + millisUntilFinished
/ 1000);
}
}
boolean getNextQuestion(boolean c) {
nextFlag = true;
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
// grp.clearCheck();
RadioButton answer = (RadioButton) findViewById(grp
.getCheckedRadioButtonId());
if (rda.isChecked() || rdb.isChecked() || rdc.isChecked()) {
qid++;
Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());
grp.clearCheck();
// wronganswers=
if (!c && currentQ.getANSWER().equals(answer.getText())) {
correct++;
} else {
lhm.put(currentQ.getQUESTION(), currentQ.getANSWER());
wrong++;
}
if (qid < 5) {
currentQ = quesList.get(qid);
setQuestionView();
} else {
score = correct;
Intent intent = new Intent(QuizActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next Intent
startActivity(intent);
return false;
}
} else {
lhm.put(currentQ.getQUESTION(), currentQ.getANSWER());
qid++;
if (qid < 5) {
currentQ = quesList.get(qid);
//currentQ.getANSWER().equals(wrong);
wrong++;
Log.e("yourans", currentQ.getANSWER());
setQuestionView();
}
// wrong++;
// Log.e("Without Any Selection ", "without "+wrong);
// Toast.makeText(getApplicationContext(),
// "Please select atleast one Option",Toast.LENGTH_SHORT).show();
}
return true;
}
}
ResultActivity.java:
package com.example.triviality;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ResultActivity extends Activity {
Button restart;
Button check;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView t=(TextView)findViewById(R.id.textResult);
TextView t1=(TextView)findViewById(R.id.textResult1);
TextView t2=(TextView)findViewById(R.id.textResult2);
restart=(Button)findViewById(R.id.restart);
check=(Button)findViewById(R.id.check);
StringBuffer sb=new StringBuffer();
sb.append("Correct ans: "+QuizActivity.correct+"\n");
StringBuffer sc=new StringBuffer();
sc.append("Wrong ans : "+QuizActivity.wrong+"\n");
StringBuffer sd=new StringBuffer();
sd.append("Final Score : "+QuizActivity.score);
t.setText(sb);
t1.setText(sc);
t2.setText(sd);
QuizActivity.correct=0;
QuizActivity.wrong=0;
check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent(getApplicationContext(),CheckActivity.class);
startActivity(in);
}
});
restart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//QuizActivity quiz=new QuizActivity();
// TODO Auto-generated method stub
Intent intent=new Intent(getApplicationContext(),QuizActivity.class);
QuizActivity.lhm.clear();
QuizActivity.qid=0;
startActivity(intent);
//quiz.countDownTimer.onTick(19);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}
This is because Your return false statement will never be reached if the user has made no choice:
if (rda.isChecked() || rdb.isChecked() || rdc.isChecked()){}
in this if else statement You will return false later. But if none is selected, You automatically will return true because the code block inside this statement above will not be rached. And then in Your timer You say:
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
getNextQuestion is allways true if the user makes no choice, so the timer starts again and again.

The method getSystemService(String) is undefined for the type new Thread(){}

I'm attempting to multithread my code, and there are no errors apart from the one which reads in the title. I'm quite new to coding, so now that I have to supposedly turn my code inside out to allow the app to run smoothly, I'm unsure how to tackle the problem.
My Java code:
package com.bipbapapps.leagueclickerapp;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
public class MainClass extends Activity implements OnClickListener {
public float goldCount;
Button minionClick;
Button storeClick;
Button storeDismiss;
TextView textGoldCount;
ImageView spinningBars;
String textTotal;
private SharedPreferences prefs;
PopupWindow pw;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set full-screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mainlayout);
// Initialize variables from popup window
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.storemenu,
null, false));
storeDismiss = (Button) pw.getContentView().findViewById(
R.id.menudismissid);
prefs = getSharedPreferences("LeagueClicker", Context.MODE_PRIVATE);
goldCount = prefs.getFloat("goldCount", 0.0f);
// Linking the variables
minionClick = (Button) findViewById(R.id.minioncentreid);
storeClick = (Button) findViewById(R.id.storeimageid);
textGoldCount = (TextView) findViewById(R.id.textviewtop);
spinningBars = (ImageView) findViewById(R.id.spinningbarsid);
// String which will display at the top of the app
textTotal = goldCount + " Gold";
// Setting TextView to the String
textGoldCount.setText(textTotal);
textGoldCount.setGravity(Gravity.CENTER);
Typeface tf = Typeface.createFromAsset(getAssets(), "mechanical.ttf");
textGoldCount.setTypeface(tf);
textGoldCount.setTextSize(35);
// Setting onClickListeners
minionClick.setOnClickListener(this);
storeClick.setOnClickListener(this);
storeDismiss.setOnClickListener(this);
}
#Override
public void onPause() {
super.onPause();
prefs.edit().putFloat("goldCount", goldCount).commit();
}
#Override
public void onResume() {
super.onResume();
goldCount = prefs.getFloat("goldCount", 0.0f);
t.start();
}
#Override
public void onStop() {
super.onStop();
prefs.edit().putFloat("goldCount", goldCount).commit();
Log.d(prefs.getFloat("goldCount", 0.0f) + "derprolw", "ejwfjbrea");
}
public void barsAnimation() {
Animation rotation = AnimationUtils.loadAnimation(this,
R.anim.spinningbarsanimation);
rotation.setRepeatCount(Animation.INFINITE);
spinningBars.startAnimation(rotation);
}
Thread t = new Thread(){
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.minioncentreid:
goldCount += 1.0;
prefs.edit().putFloat("goldCount", goldCount).commit();
textTotal = goldCount + " Gold";
textGoldCount.setText(textTotal);
textGoldCount.setGravity(Gravity.CENTER);
break;
case R.id.storeimageid:
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupview = inflater.inflate(R.layout.storemenu, null);
final PopupWindow pw = new PopupWindow(popupview, 300, 450);
pw.showAtLocation(v, Gravity.CENTER, 0, 0);
storeDismiss = (Button) pw.getContentView().findViewById(
R.id.menudismissid);
storeDismiss.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pw.dismiss();
}
});
pw.showAsDropDown(storeClick, 0, 0);
break;
}
};
};
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The thread is at "Thread t = new Thread(){". Does anyone know what I can do to solve this problem?
this is the context of the Thread, while you are actually looking to use .getSystemService of the Activity.
Use instead:
MainClass.this.getSystemService

Categories