radio button activity source code - android

This method is called at button click because of assigned name to the
"OnClick property" of the button,what should be the correct code of case in below coding.it giving error that it should be constant expression in case.
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton AButton = (RadioButton) findViewById(R.id.radio0);
RadioButton BButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}

You must be using this code in a project that will be marked as library. Is It?
If yes, then you must need to understand that in this case view.getId() value can not be used as constant.
In such projects, you can use if else statements.
The reason behind this is, in the main project if you would have defined a resource with the same id, there would be wrong result returned or initialized.
So, this is to avoid that situation as it would be more difficult to debug.
Use, if - else statement.
Also, I dont remember the ADT version, but after that view ids are not considered as the constants.

Just convert your switch case statement to if statement and it should suffice. For explanation read switch case statement error: case expressions must be constant expression

Related

How do I change the function that the button has to a different one?

So we are working on a quiz game/app and we have a problem with just one thing.
We got 4 buttons for the possible answers and only one of them is the correct one (obviusly). They are regular buttons with text on them, not the radio ones. The thing is that in order to avoid creating an activity for each question we wanna keep the buttons in one activity, and when pressed on the "correct answer" to change the buttons functions to be different. For example buttons 1,2,3 all send the player to gave over screen, while button 4 is the correct one. Then it should change the text that is displayed on the buttons and change all the buttons' functions so that 1,3,4 are now the "game over buttons" and 2 is the correct one. We tried if statements and integers, and booleans, to no avail. Any hints or solutions that could help us?
Thanks
Given your current setup I'd have each button's onClick call a method like validateCorrectAnswer(int buttonNumber) and then from there you'd do your validations. So for button1 you'd call validateCorrectAnswer(1).
From validateCorrectAnswer(...) you'd have an array of correct answers, so it could be something like int[] correctAnswers = {4, 2, 3, 4, 1, 3, 2, 1, ...}; and depending on which question they are on you'd check. So let's say you are on question 3 you'd check correctAnswers[2] == buttonNumber.
So to simplify that further within your activity store what question they are currently on in a global variable, something like private int currentQuestion = 0 and then after each question you increment that number.
So the final method would be something like:
void validateCorrectAnswer(int buttonNumber) {
if (correctAnswer[currentQuestion] == buttonNumber) {
currentQuestion++;
// correct answer, cool move on
} else {
// wrong answer, game over
}
}
In your question class, you can set the answer to a text / button id and check on a button click if the button text / id is the same as your answer.
Also, see this example from butterknife:
//Specify multiple IDs in a single binding for common event handling.
#OnClick({ R.id.door1, R.id.door2, R.id.door3 })
public void pickDoor(DoorView door) {
if (door.hasPrizeBehind()) {
Toast.makeText(this, "You win!", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Try again", LENGTH_SHORT).show();
}
}
source: Butterknife docs
You could use the setTag(tagValue) and getTag(tagValue) methods for the 4 buttons.
1 - correct
0 - wrong
And then just switch the tagValues according to the answer given.
#Override
public void onClick(View view) {
int answer = 0;
if(view instanceof Button) {
answer = (int) ((Button)view).getTag();
}
if(answer == 1) {
//true answer
refreshButtons();
} else {
//game over
}
Log.d("TAG", "a: "+answer);
}
public void refreshButtons () {
questionNr ++;
Log.d("TAG", "q: "+questionNr);
setAnswers(questionNr);
}
public void setAnswers (int question) {
switch (question){
case 1: // Second question
v1.setTag(0);//wrong
v2.setTag(1);//correct
v3.setTag(0);//wrong
v4.setTag(0);//wrong
break;
case 2:// Third question
v1.setTag(0);//wrong
v2.setTag(0);//wrong
v3.setTag(1);//correct
v4.setTag(0);//wrong
break;
case 3:// Forth question
v1.setTag(0);//wrong
v2.setTag(0);//wrong
v3.setTag(0);//wrong
v4.setTag(1);//correct
break;
}
}
You could also setup the texts for the other views in the same setAnswer() Method
The onCreate() method could be something like this :
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//here you setup the answers for the first question
v1 = (Button) findViewById(R.id.button1);
v1.setOnClickListener(this);
v1.setTag(1);
v2 = (Button) findViewById(R.id.button2);
v2.setOnClickListener(this);
v2.setTag(0);
v3 = (Button) findViewById(R.id.button3);
v3.setOnClickListener(this);
v3.setTag(0);
v4 = (Button) findViewById(R.id.button4);
v4.setOnClickListener(this);
v4.setTag(0);

Switch case, getText of the case android

I have a simple switch case:
switch (view.getId()){
case R.id.one:
break;
case R.id.two:
break;
}
What I would like to do is write something smart and self sufficient to obtain the text value of the mentioned textviews. For example r.id.one holds text of 1, while r.id.two holds text of 2.
Whenever I press 1 I want to get it's text value.
I know it can be done by the following way:
TextView one = (TextView)findviewbyid(r.id.one);
one.getText();
But with the increase of textviews it will be hard to maintain, as I want to use the obtained value later on.
Thanks advance to all the downvotes, really helpful.
Solution:
switch (view.getId()){
case R.id.one:
String number = (String) ((TextView)view).getText();
break;
case R.id.two:
String number = (String) ((TextView)view).getText();
break;
}
Now number receives the value from the textview. Thanks all.
Instead of a switch, you can try to get the text if the view is any TextView. For instance:
if (view instanceof TextView) {
((TextView) view).getText();
}
Try Butterknife library.
Use something like :
#OnClick({R.id.textviewID1, R.id.textviewID1)
protected void onTextViewClick(TextView textView) {
textView.getText();
}
This allows you to use the same callback function for each textview using just a simple annotation.
And makes the code more readable as well.

Spinner selected string dependent on language used in switch case

I have a Spinner on my Activity with items "hello" and "goodbye" for user to choose. These items, when device is in Spanish, would be "hola" and "adios", as strings are chosen from string-es/ instead from string.
The problem is that I've got many switch cases on my code like this:
switch(spinnerSelectedItem){
case "hello":
case "hola":
//do something
break;
case "goodbye":
case "adios":
//do something else
break;
}
I've tried to create a final String initialized with string resource, but it complains saying "Constant Expression Required"
final String resHello = getResources().getString(R.string.helloText);
final String resGoodbye = getResources().getString(R.string.goodbyeText);
switch(spinnerSelectedItem){
case resHello :
//do something
break;
case resGoodbye :
//do something else
break;
}
This is a simplified version, I have many more items and more than two languages
One solution would be to use strings id instead of value, or use if clauses instead of switch, but I would like to find a "smart" or "clean" way to do this, do you have any idea?
You can use the getIdentifier method of Resources to get the id of the string. eg:
getResources().getIdentifier(resValue, "string", getPackageName())
This will return the id which you can then use in your switch statements and compare.

NullPointerException at Radio Group on dialogbox

I have two radiogroup on FormVisitMapping.java, i put one of them on dialogbox which is trigger by button onClick(). but i get an error nullpointerexception only on my radiogroup where in dialog. even i have a similiar code on both of them. i have no idea why this happenned. i've read a question with similiar issue, but nothing solve my problem. here is my code :
btninvoice= (Button) findViewById(R.id.btninvoice);
btninvoice.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
final Dialog dialog3 = new Dialog(FormVisitMapping.this);
dialog3.setContentView(R.layout.penagihan);
dialog3.setTitle("Isi Data Penagihan:");
dialog3.show();
//other stuff
RadioGroup tes=(RadioGroup) findViewById(R.id.penagihan);
switch (tes.getCheckedRadioButtonId()) {
case R.id.rbtandaterima:
systemofpayment = "Tanda Terima";
break;
case R.id.rbtagihlangsung:
systemofpayment="Tagih Langsung";
break;
default:
break;
}
}
});
i've got NullPointerException on this line :
switch (tes.getCheckedRadioButtonId()) {
every help will be apriciated.thank you
Your using findViewById() on a wrong view. You haven't included your XML but I'm guessing that you want to find it in dialog's layout.
Change
RadioGroup tes=(RadioGroup) findViewById(R.id.penagihan);
to
RadioGroup tes=(RadioGroup) dialog3.findViewById(R.id.penagihan);

Retrieving view name property in android?

Is there anyway to retrieve the name of a view in android? Have been walking through the api and haven't seen any method to do this.
View only contains id not name, I think it's not able to retrieve it.
From your comment, I think you can put the index to the android:tag attribute
such as
<RadioButton android:tag="1" />
Then you can invoke button.getTag to fetch the tag value. Hope this helps you get rid of the switch case statements..
use view.getId();, which is usually used in onClick(View v) method
// from View.OnClickListener
#Override
public void onClick(View v){
switch( v.getId() ) { // <= this is it
case R.id.first_id:
// do something
break;
}
}

Categories

Resources