i'm trying to create a multiple choice quiz using 4 buttons with array. i couldn't get the variable from the button text
my button text: buttonA: Obama, buttonB: Lincoln, buttonC: Washington, buttonD: Bush
the correct answer is Obama (buttonA)
when i change the code on the answer line into answer = "Obama";
(comment line), it works. But when i change into a gettext()
from the buttonA text
, it didn't works.
i checked the answer variable from gettext()
, it returns ""
Please advise, thank you
here's the code
package com.trivia;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MenuWho extends Activity {
private String keyanswer ,answer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutwho);
Button buttons[] = new Button[4];
buttons[0] = (Button)findViewById(R.id.buttonA);
buttons[1] = (Button)findViewById(R.id.buttonB);
buttons[2] = (Button)findViewById(R.id.buttonC);
buttons[3] = (Button)findViewById(R.id.buttonD);
keyanswer = "Obama";
answer = "";
}
public void cekanswer (View view) {
Button selectedbutton = (Button) view;
switch (selectedbutton.getId())
{
case R.id.buttonA:
//answer = "Obama";
answer = selectedbutton.getText().toString();
break;
case R.id.buttonB:
answer = (String) selectedbutton.getText();
break;
case R.id.buttonC:
answer = (String) selectedbutton.getText();
break;
case R.id.buttonD:
answer = (String) selectedbutton.getText();
break;
}
//cek answer
if (answer == keyanswer)
{
Toast.makeText(this,"Correct !", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(this,"Wrong !", Toast.LENGTH_LONG).show();
}
}
}