Radio Button auto deselect after selection - android

I have four radio buttons in a radio group in my MCQ app. When I select a radio button and go to next question, there is a problem if I select same radio button as previous, the radio button automatically deselect, but after selecting any other button, it is working.
private int getSelectedAnswer(int radioSelected){
int answerSelected = 0;
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
if(radioSelected == R.id.radio3){
answerSelected = 4;
}
return answerSelected;
}
private void selectedRadioButton(int ansSelected){
if(ansSelected == 1){
optionOne.setChecked(true);
}
if(ansSelected == 2){
optionTwo.setChecked(true);
}
if(ansSelected == 3){
optionThree.setChecked(true);
}
if(ansSelected == 4){
optionFour.setChecked(true);
}
}
private void uncheckedRadioButton(){
optionOne.setChecked(false);
optionTwo.setChecked(false);
optionThree.setChecked(false);
optionFour.setChecked(false);
}
private void showQuestions(){
if(currentQuizQuestion >= quizCount){
currentQuizQuestion=currentQuizQuestion-1;
Toast.makeText(ShowSingleQuestionsOnline.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
else {
uncheckedRadioButton();
quizQuestion.setText(1+ currentQuizQuestion + " : " + MyQuestArrList.get(currentQuizQuestion).get("QuestName"));
int dd=Integer.parseInt(MyQuestArrList.get(currentQuizQuestion).get("QueType"),10);
optionOne.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption1"));
optionTwo.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption2"));
optionThree.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption3"));
optionFour.setText(MyQuestArrList.get(currentQuizQuestion).get("QueOption4"));
}
}
Thanks in advance.

This behavior is normal because the radio option state is not reset.
Take a look on your getSelectedAnswer() method :
private int getSelectedAnswer(int radioSelected){
int answerSelected = 0;
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
if(radioSelected == R.id.radio3){
answerSelected = 4;
}
return answerSelected;
}
When you go to the next question, the selected radio option state remain and when you click again on it, it value change (deselect).
To avoid this, you need to reset your radio options before go to the next question.

Related

How to solve this scenario on Android Studio?

Click on red button 2 times and green button 3 times after this click on yellow button 5 times. If this done successfully you go on next screen for next quiz.
Assuming your buttons already connected to corresponding functions in Android Manifest
private int redClicks = 0;
private int greenClicks = 0;
private int yellowClicks = 0;
public void redClickCount(View view) {
if (redClicks < 2){
redClicks++;
}
greenClicks = 0;
yellowClicks = 0;
}
public void greenClickCount(View view) {
if (redClicks == 2 && greenClicks < 3){
greenClicks++;
} else { //start all over again
redClicks = 0;
greenClicks = 0;
yellowClicks = 0;
}
}
public void yellowClickCount(View view) {
if (redClicks == 2 && greenClicks == 3 && yellowClicks <5){
yellowClicks++;
} else {
if (redClicks == 2 && greenClicks == 3 && yellowClicks = 5){
// go to next round
} else {
//start all over again
redClicks = 0;
greenClicks = 0;
yellowClicks = 0;
}
}
}

LUHN credit-card validation fails on a valid card number

In my application i want to check whether the user have entered valid card number for that i have used LUHN algorithm.I have created it as method and called in the mainactivity. But even if i give valid card number it shows invalid.While entering card number i have given spaces in between i didn't know because of that its not validating properly. Please help me in finding the mistake.
CreditcardValidation.java
public class CreditcardValidation {
String creditcard_validation,msg;
//String mobilepattern;
public static boolean isValid(long number) {
int total = sumOfDoubleEvenPlace(number) + sumOfOddPlace(number);
if ((total % 10 == 0) && (prefixMatched(number, 1) == true) && (getSize(number)>=16 ) && (getSize(number)<=19 )) {
return true;
} else {
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number > 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long temp = 0;
while (number > 0) {
temp = number % 100;
result += getDigit((int) (temp / 10) * 2);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
if ((getPrefix(number, d) == 5)
|| (getPrefix(number, d) == 4)
|| (getPrefix(number, d) == 3)) {
if (getPrefix(number, d) == 4) {
System.out.println("\nVisa Card ");
} else if (getPrefix(number, d) == 5) {
System.out.println("\nMaster Card ");
} else if (getPrefix(number, d) == 3) {
System.out.println("\nAmerican Express Card ");
}
return true;
} else {
return false;
}
}
public static int getSize(long d) {
int count = 0;
while (d > 0) {
d = d / 10;
count++;
}
return count;
}
public static long getPrefix(long number, int k) {
if (getSize(number) < k) {
return number;
} else {
int size = (int) getSize(number);
for (int i = 0; i < (size - k); i++) {
number = number / 10;
}
return number;
}
}
public String creditcardvalidation(String creditcard)
{
Scanner sc = new Scanner(System.in);
this.creditcard_validation= creditcard;
long input = 0;
input = sc.nextLong();
//long input = sc.nextLong();
if (isValid(input) == true) {
Log.d("Please fill all the column","valid");
msg="Valid card number";
}
else{
Log.d("Please fill all the column","invalid");
msg="Please enter the valid card number";
}
return msg;
}
}
MainActivity.java
addcard.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.getId()==R.id.btn_add)
{
creditcard= card_number.getText().toString();
cv = new CreditcardValidation();
String mob = cv.creditcardvalidation(creditcard);
Toast.makeText(getActivity(), mob, 1000).show();``
refer code below
EditText cardNumber=(EditText)findViewById(R.id.cardNumber);
String CreditCardType = "Unknown";
/// Remove all spaces and dashes from the passed string
String CardNo ="9292304336";///////cardNumber.getText().toString();
CardNo = CardNo.replace(" ", "");//removing empty space
CardNo = CardNo.replace("-", "");//removing '-'
twoDigit=Integer.parseInt(CardNo.substring(0, 2));
System.out.println("----------twoDigit--"+twoDigit);
fourDigit=Integer.parseInt(CardNo.substring(0, 4));
System.out.println("----------fourDigit--"+fourDigit);
oneDigit=Integer.parseInt(Character.toString(CardNo.charAt(0)));
System.out.println("----------oneDigit--"+oneDigit);
boolean cardValidation=false;
// 'Check that the minimum length of the string isn't <14 characters and -is- numeric
if(CardNo.length()>=14)
{
cardValidation=cardValidationMethod(CardNo);
}
boolean cardValidationMethod(String CardNo)
{
//'Check the first two digits first,for AmericanExpress
if(CardNo.length()==15 && (twoDigit==34 || twoDigit==37))
return true;
else
//'Check the first two digits first,for MasterCard
if(CardNo.length()==16 && twoDigit>=51 && twoDigit<=55)
return true;
else
//'None of the above - so check the 'first four digits collectively
if(CardNo.length()==16 && fourDigit==6011)//for DiscoverCard
return true;
else
if(CardNo.length()==16 || CardNo.length()==13 && oneDigit==4)//for VISA
return true;
else
return false;
}
also u can refer this demo project
Scanner.nextLong() will stop reading as spaces (or other non-digit characters) are encountered.
For instance, if the input is 1234 567 .. then nextLong() will only read 1234.
However, while spaces in the credit-card will [likely] cause it to fail LUHN validation with the above code, I make no guarantee that removing the spaces would make it pass - I'd use a more robust (and well-tested) implementation from the start. There is no need to rewrite such code.

Get Resource Id from ImageView

I am trying to develop a little game.
I have a ViewFlipper which has 50 pictures (random frequence of 4 pictures) in ImageViews. Then I have 4 Buttons with the same 4 pictures which can appear in the ViewFlipper.
The task is to click the right button when the right picture appears.
(When Picture 1 appears Button 1 has to be pressed and so on)
My Problem is I don't know how to get the displayed ImageView id.
flipper.getCurrentView().getId()
gives me "-1" as Id. But I want to have the Id of "R.drawable.pic1"
My code so far:
my Loader-Method:
protected void loadPicturesIntoFlipper() {
Random generator = new Random();
pictures = new ArrayList();
for(int i = 0; i < 50;i++){
int number = generator.nextInt(4) + 1;
if(number == 1){
pic = R.drawable.pic1;
}
if(number == 2){
pic = R.drawable.pic2;
}
if(number == 3){
pic = R.drawable.pic3;
}
if(number == 4){
pic = R.drawable.pic4;
}
pictures.add(pic);
}
for(int i=0;i<pictures.size();i++)
{
setFlipperImage((Integer) pictures.get(i));
}
}
My Insert-Method:
private void setFlipperImage(int res) {
image = new ImageView(getApplicationContext());
image.setBackgroundResource(res);
flipper.addView(image);
}
My Check-Method :
protected void check(int number, int id) {
int code = 0;;
if(number == 1){
code = R.drawable.button_tip_finder;
}
if(number == 2){
code = R.drawable.button_about_us;
}
if(number == 3){
code = R.drawable.button_power_calculator;
}
if(number == 4){
code = R.drawable.button_powerpedia;
}
if(code == id){
test.setText(""+id);
}
else{
test.setText(""+id);
}
}
I call it like:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
check(1,flipper.getCurrentView().getId());
flipper.showNext();
}
});
Do it like this:
private void setFlipperImage(int res) {
image = new ImageView(getContext());
image.setBackgroundResource(res);
image.setTag(res); //<------
flipper.addView(image);
}
and then:
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
check(1,(Integer)flipper.getCurrentView().getTag());//<----
flipper.showNext();
}
});
BTW use else in all of your code please, E.g:
if(number == 1){
pic = R.drawable.pic1;
} else if(number == 2){
pic = R.drawable.pic2;
} else if(number == 3){
pic = R.drawable.pic3;
}
may this one helps you,
int icon = getResources().getIdentifier([YOUR IMAGE NAME], "drawable",
getPackageName());

Radio button is not displaying right value

In my coding m having three buttons. i am getting the selected button is id and used it for comparison. But it first automatically displays the default selected button's id before clicking the button.
rdgp.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
counter++;
if (counter > 5 || counter >= anarray.size()) {
Toast.makeText(testActivity.this, "" + score, 2000).show();
Intent intent = new Intent(testActivity.this, Badge.class);
intent.putExtra("Score", score);
startActivity(intent);
return;
}
rb1.setText(anarray.get(counter));
rb2.setText(an1array.get(counter));
rb3.setText(an2array.get(counter));
rb4.setText(an3array.get(counter));
rb5.setText(an4array.get(counter));
int ans = 0;
if (checkedId == R.id.radio0) {
ans = 1;
} else if (checkedId == R.id.radio1) {
ans = 2;
} else if (checkedId == R.id.radio2) {
ans = 3;
} else if (checkedId == R.id.radio3) {
ans = 4;
}
Toast.makeText(testActivity.this, "" + ans, 2000).show();
if (ans == anarray.get(counter))
;
{
score = score + 1;
}
}
});
to get the id of checked radiobutton use group.getCheckedRadioButtonId().Returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
Add the following line, in your XML for all radio buttons.
android:checked="false"
If you are getting default value from radio buttons then check in our layout file weather you used android:checked = "true".If this is the state then change it to false.

How to I finish the "continue;" That i putted after the if statement?

I made a statement and if it is true it continues, I want to stop this "continue" and make another statement for example touchdown and touchup.
here is my code
private void updateRunning(float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
if (event.type != TouchEvent.TOUCH_UP)
continue;
world.doodle.DOODLE_Y = 3;
touchPoint.set(event.x, event.y);
guiCam.touchToWorld(touchPoint);
if (OverlapTester.pointInRectangle(pauseBounds, touchPoint)) {
Assets.clicks();
state = GAME_PAUSED;
return;
}
}
world.update(deltaTime, game.getInput().getAccelX());
if (world.score != lastScore) {
lastScore = world.score;
scoreString = "" + lastScore;
}
if (world.state == World.WORLD_STATE_NEXT_LEVEL) {
state = GAME_LEVEL_END;
}
if (world.state == World.WORLD_STATE_GAME_OVER) {
state = GAME_OVER;
if (lastScore >= Settings.highscores[4])
scoreString = "new highscore: " + lastScore;
else
scoreString = "score: " + lastScore;
Settings.addScore(lastScore);
Settings.save(game.getFileIO());
}
}
Little confused by what you are asking, but perhaps an else if?
if (event.type == TouchEvent.TOUCH_UP) {
/* do something for TOUCH_UP event */
} else if (event.type == TouchEvent.TOUCH_DOWN) {
/* do something for TOUCH_DOWN event */
} else {
/* do something else */
}
You can't stop a continue after you execute it.
Try adding break; where you want it to stop.

Categories

Resources