Check the correct answer - android

I am developing an app that is a question's game. I managed to show the answers to each question to a different button each time but i am having trouble to check the right answer. My approach is: I created an extra column to the database where i indicate the column where the right answer is(1,2,3 or 4). I use this code for showing the answers in different buttons.
cur = dbHelper.getRandomQuestion();
String corrans = cur.getString(cur.getColumnIndex("CorrectAnswer"));
a = Integer.parseInt(corrans);
String question = cur.getString(cur.getColumnIndex("QUESTIONS"));
String answer0 = cur.getString(cur.getColumnIndex("ANSWER1"));
String answer1 = cur.getString(cur.getColumnIndex("ANSWER2"));
String answer2 = cur.getString(cur.getColumnIndex("ANSWER3"));
String answer3 = cur.getString(cur.getColumnIndex("ANSWER4"));
txtQuest.setText(question);
ArrayList<String> lstAnswers = new ArrayList<String>();
lstAnswers.add(answer0);
lstAnswers.add(answer1);
lstAnswers.add(answer2);
lstAnswers.add(answer3);
score.setText("Your score is " + b +","+ a);
Random random = new Random();
int[] textViews = new int[] { R.id.button1, R.id.button2, R.id.button3, R.id.button4 };
int textViewIndex = 0;
while (lstAnswers.size() > 0) {
int index = random.nextInt(lstAnswers.size());
if(a == index){ b = index;}
else{}
String randomAnswer = lstAnswers.remove(index);
((TextView)findViewById(textViews[textViewIndex])).setText(randomAnswer);
++textViewIndex;
}
To each button call to compare the values of a and b and then act accordingly. But it doesnt seem to work. I understand why but i cannot figure it out. Any help appeciated.

use Collections.shuffle(list) to shuffle your answer array and then display the answer
Set a tag as "right" to your button where anwer is correct and later compare the the tagvalue and disply right or wrong
EDIT: below thing is just an outline
Here im displaying answers in buttons....
List<Integer> intList = new ArrayList<Integer>(Arrays.asList(0,1,2,3));
Collections.shuffle(intList);
Log.d("ERR","List after shuffling: " + intList);
// below answers will be assiagned randomly to buttons...
btn_cmpTagline[intList.get(0)].setText(answr1);
btn_cmpTagline[intList.get(0)].setTag("right");
btn_cmpTagline[intList.get(1)].setText(answr2);
btn_cmpTagline[intList.get(1)].setTag("wrong");
btn_cmpTagline[intList.get(2)].setText(answr3);
btn_cmpTagline[intList.get(2)].setTag("wrong");
btn_cmpTagline[intList.get(3)].setText(answr4);
btn_cmpTagline[intList.get(3)].setTag("wrong");
//On Click
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn_tag1:
Log.d("ERR", v.getTag().toString());
if(v.getTag().toString().equalsIgnoreCase("right")){
//this button has right answer .. do anything
}
break;
case R.id.btn_tag2:
Log.d("ERR", v.getTag().toString());
if(v.getTag().toString().equalsIgnoreCase("right")){
//this button has right answer .. do anything
}
break;
case R.id.btn_tag3:
Log.d("ERR", v.getTag().toString());
if(v.getTag().toString().equalsIgnoreCase("right")){
//this button has right answer .. do anything
}
--
--
}

When you remove items from the list the the index of the correct answer will change, so you have to update where the correct answer is located.

you can get the value of the right answer instead of the index. then, as you add the answers to buttons you can check if it is the same with the correct answer and keep the new index.

Related

Want to loop through questions and count correct answers

I'd like to show a series of 10 questions and have the user answer, and have the app show whether the answer is correct, and then show the next question.
Right now I can show the first question, check whether it's correct, and then display the second question. I don't know how to get this looping, however, to show all questions. Here is the relevant code:
public class MathTestActivity extends AppCompatActivity {
int i = 0;
int n = 20; /*How many rows this test*/
String[] mathTest = new String[40];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mathtest);
final TextView mathProblem = (TextView) findViewById(R.id.mathProblem);
final EditText mathAnswer = (EditText) findViewById(R.id.mathAnswer);
//Styling for the question text
mathProblem.setTextSize(40);
mathProblem.setTextColor(Color.rgb(0, 0, 0));
//Try to read the problem and answers text file
try {
InputStream is = this.getResources().openRawResource(R.raw.mediummath);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
int n = 20; /*How many rows this test has*/
/*read in file to array*/
for (i = 0; i < n; i=i+2) {
if ((line = reader.readLine()) != null)
mathTest[i] = line;
if ((line = reader.readLine()) != null)
mathTest[i+1] = line;
}
} catch (IOException e) {
e.printStackTrace();
}
mathProblem.setText(mathTest[0]);
Button enterButton = (Button) findViewById(R.id.enterButton);
enterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int correctcount = 0;
i = 0;
String answer = mathAnswer.toString() ;
String correctAnswer = mathTest[i+1];
if (answer.equals(correctAnswer)){
Toast.makeText(MathTestActivity.this,
R.string.correct_toast,
Toast.LENGTH_SHORT).show();
correctcount++;
i = i + 2;
mathProblem.setText(mathTest[i]);
correctAnswer = mathTest[i+1];
}
else{
Toast.makeText(MathTestActivity.this,
correctAnswer,
Toast.LENGTH_SHORT).show();
i = i + 2;
mathProblem.setText(mathTest[i]);
correctAnswer = mathTest[i+1];
}
}
});
}
}
You can't count the correct answers with a local variable that gets set to 0 each time you click the button. :)
You should move int correctcount = 0; outside of the listener and next to your i and n variables.
You will also want to remove the i = 0; line from inside the button click because that will reset you back to the first question every time you click the button.
Also, since these three lines are duplicated between the if and the else, you can just place them directly after the else.
i = i + 2;
mathProblem.setText(mathTest[i]);
correctAnswer = mathTest[i+1]; // this isn't needed, though
You can try putting your questions in ViewPager if you want to make the questions shown in sliding presentation (http://developer.android.com/training/animation/screen-slide.html).
Or you can put your question inside a ListView if you want to view the question from top to bottom. (http://developer.android.com/guide/topics/ui/layout/listview.html)
EDIT:
Actually you are close to achieve what you want to do.
You should delete i = 0; inside your button onClick() function as it prevents you from going to next questions (3rd, 4th, etc). You might want to consider clearing the mathAnswer EditText when the user submits a question.
Also, it is not necessary to set correctAnswer = mathTest[i+1]; inside your if-else function.
Use arraylist for questions array and answer array.use view pager with two layouts questions and answer layout.if the answer array of position equal to the user answer its correct answer like u can dynamically

Random call name in Android

How to make a 'random call' name in List in database sqlite. How can I call one by one without repeating its value. My layout is one textview, If I click the name it will change. Thank you.
Untested, but should be fine:
Query your database, then use the returned Cursor to populate a LinkedList with whatever options you would like.
LinkedList list = new LinkedList();
if (cursor.getCount() > 0) {
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
list.add(cursor.getString(etc...);
}
}
Create a Random object, and use it to select and remove a random element from list each time:
Random rnd = new Random();
//The below section could be repeated on, for instance, a button click.
int randomValue = rnd.nextInt(list.size());
String result = list.get(randomValue);
list.remove(randomValue);
Each time an element is removed, the LinkedList will adjust in size to accommodate it, so no results will be repeated.
#PPartisan not working.
I add button to test the result from textview. 1 row only detected when I pressed back and back to activity the result is the same value. I clicked the button did not work.
rnd = new Random();
randomValue = rnd.nextInt(list.size());
result =list.get(randomValue).toString();
list.remove(randomValue);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
tv.setText(result);
}
});

I am going to develop a new Quiz application in Android. When I click on the wrong option it has to show red color how can we do that?

I am new to this Quiz Applications.
I am using radio buttons here. When I click on wrong options it will come on red color and it has to display correct answer also. Now here is my code. When i click on the next button it will appear like this. Thanks in advance.
here total, correct and wrong are static variables to display the final score in another class.
RadioButton uans = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
String ansText = uans.getText().toString();
if (ansText.equalsIgnoreCase(answers[flag])) {
correct++;
} else {
wrong++;
}
flag++;
if (flag < question.length) {
tv.setText(question[flag]);
rb1.setText(options[flag * 3]);
rb2.setText(options[flag * 3 + 1]);
rb3.setText(options[flag * 3 + 2]);
marks = correct - wrong;
} else {
marks = correct - wrong;
Intent in = new Intent(getApplicationContext(),
ResultActivity.class);
startActivity(in);
}
if (flag == question.length) {
Intent in = new Intent(getApplicationContext(),
ResultActivity.class);
startActivity(in);
Level1Activity.this.finish();
}
total = question.length;
add these statement where you find a wrong ans, that is in else part, where you need to set a red color.
if your color.xml is like:
<color name="errorColor">#f00</color>
then
uans.setTextColor(getResources().getColor(R.color.red));
and also set the ans with another color

Properly implementing/initializing lots of new variables, taken from RadioGroups and Spinners

I am developing a simple questionnaire-like app which includes lots of radio buttons joined into groups and spinners. I have multiple activities (6); some of them having RBs and some Spinners to let the user answer the questions.
The following step, which I have trouble with, is how to fetch lots of selections (of all the radio buttons/choices) and possibly do that in a for loop (so I don't have to initialize each new variable 30+ times in a row for just one activity). I've already assigned IDs to all of the views, but am having a hard time how to actually fetch the selection, initialize a new var corresponding to the selection (let's say radio button 1 in radio group 1 gives me a new variable with a value of 1) and then make the variables available to all of the activities (should I use global when initializing?).
My failed attempt on generating 10 variables for the first "page"
public void goTo2(View v) {
checkRB();
Intent intent1 = new Intent(Vprasalnik1.this, Vprasalnik2.class);
startActivity(intent1);
finish();
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
RadioButton "vRB" + i; //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Put variables into array like a
int size = 9;
RadioButton[] views = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
views[i] = (RadioButton)findViewByID(...);//For example
}
}
Or make a structure :
public class Choise
{
int mRadioButtonChoise;
int mSpinnerChoise;
}
And use something like this:
...
Choise c = new Choise();
c.mRadioButtonChoise = yourRadioButtonID;
c.mSpinnerChoise = youtSpinnerChoiseID;
...
Using a variable to identify a resource:
RadioButton[] rb = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
int id = context.getResources().getIdentifier("vRB" + i, "id", context.getPackageName())
rb[i] = (RadioButton)findViewByID(id);
}
}
If you have an array of RadioButtons then you can get all the values at the same time, however initializing them will have to be manual.
RadioButton rb[];
boolean rbc[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbc=new boolean[200];
rb=new RadioButton[200]();
rb[0]=(RadioButton)findViewById(R.id.rb1);
rb[1]=(RadioButton)findViewById(R.id.rb2);
rb[2]=(RadioButton)findViewById(R.id.rb3);
rb[3]=(RadioButton)findViewById(R.id.rb4);
// many more.
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
rbc[i]=rb.isChecked(); //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Then before starting your intent add all relevant data to it.
So I've managed to cramp up the radio buttons activity, so that it finally works. If anyone is interested - I've used tags in xml code to properly assign values (1, 2 and 3 for each group of buttons) and managed to get an output in my testToast. At least I didn't have to initialize all of the variables manually - I've been saving the values into an ArrayList and then appended to them via StringBuilder.
Thanks to everyone who tried to help - it turned out I've needed a bit more research, testing and teasing my half-awake brain.
btn = (Button) findViewById(R.id.v3_btn1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 1; i <= 36; i++)
{
tmpRGid = "radioGroup_v3q" + i;
tmp2RGid = getResources().getIdentifier(tmpRGid, "id", getPackageName());
RGid = (RadioGroup) findViewById(tmp2RGid);
selectedOption = RGid.getCheckedRadioButtonId();
RBid = (RadioButton) findViewById(selectedOption);
addToIDList.add((String)RBid.getTag());
}
String testToast = "";
StringBuilder builder = new StringBuilder();
builder.append("Vaša izbira (");
for (int z=0; z < addToIDList.size(); z++) {
testToast = addToIDList.get(z);
builder.append(testToast + ", ");
}
builder.setLength(builder.length() - 2);
builder.append(") je bila shranjena.");
Toast.makeText(Vprasalnik3.this, builder, Toast.LENGTH_LONG).show();

randomGenerator avoid duplicates in a row

I have a question regarding the following code
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(4);
String wordList[] = new String[4];
{
wordList[0] = "Red";
wordList[1] = "Blue";
wordList[2] = "Green";
wordList[3] = "Orange";
}
String wordToDisplay = wordList[randomInt];
This code works fine however I would like to know if it was possible to get it to not pick the same word two times in a row. For example, if it just selected "Red" then it would not pick "Red" again the next consecutive time. I read something about DISTINCT but I'm not sure if that's along the right path.
Here is the code for the button which uses this
final Button button1 = (Button) findViewById(R.id.button1);
final TextView textView = (TextView) findViewById(R.id.text_random_text);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(9);
String wordToDisplay = wordList[randomInt];
textView.setText(wordToDisplay);
Thankyou for your help
go for list and remove color once used:
private static ArrayList<String> arrayList = new ArrayList<String>();
private static Random random = new Random();
public static void fillList(){
arrayList.add("Red");
arrayList.add("Blue");
arrayList.add("Green");
arrayList.add("Orange");
}
public static String getNextRandomColor(){
if(arrayList.isEmpty()){
fillList();
}
return arrayList.remove(random.nextInt(arrayList.size()));
}
You can do this in two way (probably more but two that I can think of right now):
1) Create a function that uses a global variable to store the last generated random number.
It will look something like this:
int myRand(int i) {
int aux;
Random randomGenerator = new Random();
do {
aux = randomGenerator.nextInt(i);
} while (aux != lastRandGenerated);
lastRandGenerated = aux;
return aux;
}
, where lastRandGenerated is a global variable that you initialize to 0.
Then you use this function to generate random numbers.
2) You can create a class that has a function very similar to the one above and then instantiate an object of that class and use that to generate your random numbers. In the class create a static variable that will remember the last generated random number. Use that instead of the global variable.
The specifics are a bit out of my league but as a math problem there are 24 combinations (4 * 3 * 2 * 1). As heavy handed as this might sound, worst case you could work out all the combos and then pick a one out of 24 random.

Categories

Resources