This is a class file that generates random string.
public class RandomGen {
static String keys() {
String str[] = new String[25];
str[0] = "Press A1";
str[1] = "Press A2";
str[2] = "Press A3";
str[3] = "Press A4";
str[4] = "Press A5";
str[5] = "Press B1";
str[6] = "Press B2";
str[7] = "Press B3";
str[8] = "Press B4";
str[9] = "Press B5";
str[10] = "Press C1";
str[11] = "Press C2";
str[12] = "Press C3";
str[13] = "Press C4";
str[14] = "Press C5";
str[15] = "Press D1";
str[16] = "Press D2";
str[17] = "Press D3";
str[18] = "Press D4";
str[19] = "Press D5";
str[20] = "Press E1";
str[21] = "Press E2";
str[22] = "Press E3";
str[23] = "Press E4";
str[24] = "Press E5";
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(25);
return str[randomInt];
}
}
This is android activity file. I’m returning a random text from a class and displaying in a text view. If the returned string is “Press A1” the user should press only the Al button. If he press other buttons an error message has to be shown in an other textview. And next time if “Press C1” displayed in that textview, the user should press only the C1 button. If he press someother button “wrong button” message has to be shown. I don’t know how to check the condition. Please help me.
RandomGen rg = new RandomGen();
String s;
b[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = rg.keys();
tv.setText(s);
tv2.setText("A1 is pressed");
}
});
b[1].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = rg.keys();
tv.setText(s);
tv2.setText("A2 is pressed");
}
});
b[2].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = rg.keys();
tv.setText(s);
tv2.setText("A3 is pressed");
}
});
b[3].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
s = rg.keys();
tv.setText(s);
tv2.setText("A4 is pressed");
}
});
You have a whole lot of code duplication here. Here’s what you should do, IMHO.
Create a static final array of texts, containing the text of all your buttons.
Create a
Map<View, String>containing the text associated with each button (unless Android allows associateing some text to a button, in which case you don’t even need this map).For each button add the same listener: