radiobutton nullpointerexecption in fragment - android

I want to get the text from RadioButton which is Male or Female but however I got the result nullPointerExeception. Below is my code:
sex = (RadioGroup)v.findViewById(R.id.radioGroup);
int selectSex = sex.getCheckedRadioButtonId();
radioButton = (RadioButton)v.findViewById(selectSex);
String empSex = radioButton.getText().toString();
Toast.makeText(getContext(),empSex + "",Toast.LENGTH_LONG).show();
XML:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/radioGroup"
android:layout_margin="5dp"
android:orientation="horizontal"
android:weightSum="1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/male"
android:id="#+id/maleRadio"
android:textColor="#color/colorAccent"
android:layout_weight="0.3"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/female"
android:id="#+id/femaleRadio"
android:textColor="#color/colorAccent"
android:layout_weight="0.3"/>
</RadioGroup>
PS: This is in Fragment page.

Can try if-else statement
in your case, male and female
so
if(male.isChecked()){
//do somethings
}
else if(female.isChecked()){
//do somethings
}
this is the simplest and easier.

Its an issue with your usage.
You don't want to show a toast directly when your fragment is created.
It should be when the user selects any radio button or user left it selected by default.
You should use sex.setOnCheckedChangeListener, Answer you are looking for
is here:- https://stackoverflow.com/a/8323973/3594268
and here:- https://stackoverflow.com/a/9175703/3594268
And for context here:-https://stackoverflow.com/a/8215398/3594268 //this is your null pointer exception in Toast

Related

how to count correct and wrong answer in radio button android

i am a beginner Android developer
I use radio button group for Quiz App i need to count correct and wrong answer
but it count each i checked radio button . i do not know how ?.
public class MainActivity extends AppCompatActivity {
/**
* Global Variable for count Correct answer
*/
int count_correct_answer =0;
/**
* Global Variable for count worng answer
*/
int count_wrong_answer=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void rdaio_click_group1(View view) {
RadioGroup radio=(RadioGroup) findViewById(R.id.radio_group1);
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_button1:
if (checked)
break;
case R.id.radio_button2:
if (checked)
count_correct_answer++;
radio.clearCheck();
break;
case R.id.radio_button3 :
if(checked)
break;
}
}
public void rdaio_click_group2(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_button12:
if (checked)
count_correct_answer++;
break;
case R.id.radio_button22:
if (checked)
break;
case R.id.radio_button32 :
if(checked)
break;
}
}
Create a Button to valide(wrong or correct answer) your answer and control next question.
This button need call onClickListener.
There is more than one problem in the code that you provided.
First of all, start by checking the spellings that you have used for the onClick method in xml. You have defined public void *rdaio_click_group<number>*, it's radio, just ensure that you have it spelled the same way in both xml and java.
Secondly, you should always initialize view and stuff within the onCreate method or the onCreateView method for fragments. So, declare RadioGroup radioGroup; outside onCreate to make it a global variable and then within the onCreate, type
radioGroup = (RadioGroup) findViewById(R.id.radio_group1);
In your switch part, you are confusing yourself and the app as to what you want to do. In
switch(view.getId()) {
case R.id.radio_button1:
if (checked)
break;
......
}
At this point, the app knows that if the view.getId() evaluates to true, then, it is supposed try the if condition, then, only when the boolean checked evaluates to true, the switch statement is supposed to break.
When you do not have a parentheses (the {} brackets) after if, switch conditions and loops, then the compiler will assume that all the code upto the next ';' (semi-colon) is what you want to include in the parentheses and nothing else. Now, you have left a blank line after the if condition probably to say that you want nothing to happen when this condition is true, the compiler doesn't know this. Thus, by default, it includes the break statement in the if condition, this happens because the next semi-colon after the if condition is includes the break statement.
Android studio doesn't allow this, if you want to do nothing with the if condition, then don't use it or place empty parentheses after it so that Android Studio knows that you want to do nothing when the condition is true, you must always have a break statement for every case, whereas you have the break statement only for those instances when the condition evaluates to true, what is the app supposed to do when the condition is false?
It will simply keep trying the next case, until it reaches the default one, now if any one of the previously tried cases evaluates to true and has a reachable break statement, then the app will perform all the tasks that were required to be performed for both the cases (the original one and the new one). Otherwise the app will simply implement the default case and produce a wrong output.
/**
* declare object variable for each groupe button
*/
RadioGroup radio_groub1_button,radio_groub2_button, radio_groub3_button , radio_groub4_button;
RadioGroup radio_groub5_button , radio_groub6_button ,radio_groub7_button , radio_groub8_button ;
/**
* Global Variable for count Correct answer
*/
int count_correct_answer =0;
/**
* Global Variable for count worng answer
*/
int count_wrong_answer=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* find ID for group button 1 to group button 8
*/
radio_groub1_button = (RadioGroup)findViewById(R.id.radio_group1) ;
radio_groub2_button = (RadioGroup)findViewById(R.id.radio_group2) ;
radio_groub3_button = (RadioGroup)findViewById(R.id.radio_group3) ;
radio_groub4_button = (RadioGroup)findViewById(R.id.radio_group4) ;
radio_groub5_button = (RadioGroup)findViewById(R.id.radio_group5) ;
radio_groub6_button = (RadioGroup)findViewById(R.id.radio_group6) ;
radio_groub7_button = (RadioGroup)findViewById(R.id.radio_group7) ;
radio_groub8_button = (RadioGroup)findViewById(R.id.radio_group8) ;
}
public void submit_answer(View view){
int selectteed1 = radio_groub1_button.getCheckedRadioButtonId();
RadioButton radio_button1 = (RadioButton)findViewById(selectteed1);
String button1= radio_button1.getText().toString();
/**
* get id of correct answer and store in variable.
*/
int button_g1= R.id.radio_button2;
if(selectteed1 == button_g1) {
// Toast.makeText(getBaseContext(),"Yes", Toast.LENGTH_LONG).show();
count_correct_answer++;
} else {count_wrong_answer++;}
/**
* cheked radio button that selectted in group1 and get id .
* */
int selectteed2 = radio_groub2_button.getCheckedRadioButtonId();
RadioButton radio_button2 = (RadioButton)findViewById(selectteed2);
String button2 =radio_button2.getText().toString();
/**
* get id of correct answer and store in variable.
*/
int button_g2= R.id.radio_button12;
/**
* check for correct answer , wrong and count it .
*/
if(selectteed2== button_g2) {
count_correct_answer++;
}
else {count_wrong_answer++;}
int selectteed3 = radio_groub3_button.getCheckedRadioButtonId();
RadioButton radio_button3 = (RadioButton)findViewById(selectteed3);
String button3 = radio_button3.getText().toString();
/**
* get id of correct answer and store in variable.
*/
int button_g3= R.id.radio_button33;
/**
* check for correct answer , wrong and count it .
*/
if(selectteed3== button_g3) {
count_correct_answer++;
} else {count_wrong_answer++;}
/**
* cheked radio button that selectted in group1 and get id .
*/
int selectteed4 = radio_groub4_button.getCheckedRadioButtonId();
RadioButton radio_button4 = (RadioButton)findViewById(selectteed4);
/**
* get id of correct answer and store in variable.
*/
int button_g4= R.id.radio_button14;
/**
* check for correct answer , wrong and count it .
*/
if(selectteed4== button_g4) {
count_correct_answer++;
}
else {count_wrong_answer++;}
/**
* cheked radio button that selectted in group1 and get id .
*/
int selectteed5 = radio_groub5_button.getCheckedRadioButtonId();
RadioButton radio_button5 = (RadioButton)findViewById(selectteed5);
/**
* get id of correct answer and store in variable.
*/
int button_g5= R.id.radio_button25;
/**
* check for correct answer , wrong and count it .
*/
if(selectteed5== button_g5) {
count_correct_answer++;
}
else {count_wrong_answer++;}
/**
* cheked radio button that selectted in group1 and get id .
*/
int selectteed6 = radio_groub6_button.getCheckedRadioButtonId();
RadioButton radio_button6 = (RadioButton)findViewById(selectteed6);
/**
* get id of correct answer and store in variable.
*/
int button_g6= R.id.radio_button26;
/**
* check for correct answer , wrong and count it .
*/
if(selectteed6== button_g6) {
count_correct_answer++;
}
else {count_wrong_answer++;}
/**
* cheked radio button that selectted in group1 and get id .
*/
int selectteed7 = radio_groub7_button.getCheckedRadioButtonId();
RadioButton radio_button7 = (RadioButton)findViewById(selectteed7);
/**
* get id of correct answer and store in variable.
*/
int button_g7= R.id.radio_button27;
/**
* check for correct answer , wrong and count it .
*/
if(selectteed7== button_g7) {
count_correct_answer++;
}
else {count_wrong_answer++;}
/**
* cheked radio button that selectted in group1 and get id .
*/
int selectteed8 = radio_groub8_button.getCheckedRadioButtonId();
RadioButton radio_button8 = (RadioButton)findViewById(selectteed8);
/**
* get id of correct answer and store in variable.
*/
int button_g8= R.id.radio_button28;
/**
* check for correct answer , wrong and count it .
*/
if(selectteed8== button_g8) {
count_correct_answer++;
}
else {count_wrong_answer++;}
String succeed = "Number of correct answer is \t "+ count_correct_answer + "\n you are done";
String faild = "Number of wrong answer is \t "+ count_wrong_answer + "\n you are faild";
if(count_correct_answer >= count_wrong_answer){
Toast.makeText(getBaseContext(),succeed, Toast.LENGTH_LONG).show();
}
else{Toast.makeText(getBaseContext(),faild, Toast.LENGTH_LONG).show();}
}
XML
<LinearLayout
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/Q_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q1" />
<RadioGroup
android:id="#+id/radio_group1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button1" />
<RadioButton
android:id="#+id/radio_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button2" />
<RadioButton
android:id="#+id/radio_button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button3" />
</RadioGroup>
<TextView
android:id="#+id/Q_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q2" />
<RadioGroup
android:id="#+id/radio_group2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button12" />
<RadioButton
android:id="#+id/radio_button22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button22" />
<RadioButton
android:id="#+id/radio_button32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button32" />
</RadioGroup>
<TextView
android:id="#+id/Q_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q3" />
<RadioGroup
android:id="#+id/radio_group3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button13" />
<RadioButton
android:id="#+id/radio_button23"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button23" />
<RadioButton
android:id="#+id/radio_button33"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button33" />
</RadioGroup>
<TextView
android:id="#+id/Q_4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q4" />
<RadioGroup
android:id="#+id/radio_group4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button14" />
<RadioButton
android:id="#+id/radio_button24"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button24" />
<RadioButton
android:id="#+id/radio_button34"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button34" />
</RadioGroup>
<TextView
android:id="#+id/Q_5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q5" />
<RadioGroup
android:id="#+id/radio_group5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button15" />
<RadioButton
android:id="#+id/radio_button25"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button25" />
<RadioButton
android:id="#+id/radio_button35"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button35" />
</RadioGroup>
<TextView
android:id="#+id/Q_6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q6" />
<RadioGroup
android:id="#+id/radio_group6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button16" />
<RadioButton
android:id="#+id/radio_button26"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button26" />
<RadioButton
android:id="#+id/radio_button36"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button36" />
</RadioGroup>
<TextView
android:id="#+id/Q_7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q7" />
<RadioGroup
android:id="#+id/radio_group7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button17"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button17" />
<RadioButton
android:id="#+id/radio_button27"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button27" />
<RadioButton
android:id="#+id/radio_button37"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button37" />
</RadioGroup>
<TextView
android:id="#+id/Q_8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:text="#string/Q8" />
<RadioGroup
android:id="#+id/radio_group8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/radio_button18"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button18" />
<RadioButton
android:id="#+id/radio_button28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button28" />
<RadioButton
android:id="#+id/radio_button38"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button38" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_gravity="center_horizontal"
android:onClick="submit_answer"
android:text="#string/submit"/>
<TextView
android:id="#+id/show_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textSize="18sp"
android:layout_marginTop="12dp"
android:padding="23dp"
android:text="" />`enter code here`
Declare globally:
RadioGroup radio;
In onCreate:
radio = (RadioGroup) findViewById(R.id.radio_group1);
In onClick or any Action Event:
radioButtonID = radio.getCheckedRadioButtonId();
View radioButton = radio.findViewById(radioButtonID);
if(radioButton.getId() == R.id.radio_button12){
count_correct_answer++;
}
else{
count_wrong_answer++;
}
As far as I understood, You want to reset radioButton selection. So, I added these codes to reset radioGroups and count_correct_answer, count_wrong_answer:
Add below codes after showing Success/Failed toast in submit_answer(View view):
radio_groub1_button.clearCheck();
radio_groub2_button.clearCheck();
.
.
.
radio_groub8_button.clearCheck();
count_correct_answer = 0;
count_wrong_answer = 0;
Hope this helps.

EditText, when setting to maxLines = 1 and enter is pressed it erases and crashes

I have an issue regarding the EditText. Doing a simple math game where the player will get an example such as this: 9 x 9 = __ . The empty space (= EditText, limited to only numbers) is where the player has to fill in correct answer from the equation and press an [ CORRECT ]-button to correct the equation.
Problem:
I have currently set android.maxLines = "1". Now each time the player presses the Enter-key any written text will be erased. If you re-type back and press the Correct-button the app stopps working. However, for as long as you don't press enter the app works just fine using the Correct-button. How do I prevent it from crashing/stop working? But also stop it from erasing any numbers when pressing the Enter-key.
XML-file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_play"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.android.laboration2.EasyActivity">
<TextView
android:id="#+id/textEasyMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textEasyNumber1"
android:layout_centerHorizontal="true"
android:layout_gravity="start"
android:text="#string/multiply"
android:textAlignment="textStart"
android:textColor="#android:color/black"
android:textSize="40sp" />
<TextView
android:id="#+id/textEasyNumber1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginEnd="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="49dp"
android:layout_toLeftOf="#+id/answerButton"
android:layout_toStartOf="#+id/answerButton"
android:text="#string/number_1"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textEasyEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textEasyNumber1"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/equal"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<EditText
android:id="#+id/editTextEasyResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textEasyEqual"
android:layout_centerHorizontal="true"
android:hint=" "
android:maxLines="1"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textEasyScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="start"
android:layout_marginBottom="31dp"
android:layout_toLeftOf="#+id/answerButton"
android:layout_toStartOf="#+id/answerButton"
android:text="#string/score_0"
android:textAlignment="textStart"
android:textColor="#android:color/black"
android:textSize="24sp" />
<Button
android:id="#+id/answerButton"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextEasyResult"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:background="#android:color/holo_orange_dark"
android:text="#string/button_result"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textEasyNumber2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textEasyEqual"
android:layout_alignEnd="#+id/textEasyLevel"
android:layout_alignRight="#+id/textEasyLevel"
android:layout_marginEnd="12dp"
android:layout_marginRight="12dp"
android:inputType="number"
android:text="#string/number_2"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="50sp" />
<TextView
android:id="#+id/textEasyLevel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textEasyScore"
android:layout_alignBottom="#+id/textEasyScore"
android:layout_toEndOf="#+id/answerButton"
android:layout_toRightOf="#+id/answerButton"
android:text="#string/level_0"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="24sp" />
</RelativeLayout>
JAVA-file:
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.answerButton:
int easyNum1 = Integer.parseInt(textEasyNumber1.getText().toString());
int easyNum2 = Integer.parseInt(textEasyNumber2.getText().toString());
int easyResult = Integer.parseInt(editTextEasyResult.getText().toString());
if(easyNum1 * easyNum2 == easyResult){
currentScore++;
currentLevel++;
textEasyScore.setText("Score: " + currentScore);
textEasyLevel.setText("Level: " + currentLevel);
Toast.makeText(getApplicationContext(), "Good job!", Toast.LENGTH_LONG).show();
editTextEasyResult.setText("");
}else{
currentScore = 0;
currentLevel = 0;
Toast.makeText(getApplicationContext(),"Wrong! :(", Toast.LENGTH_LONG).show();
}
//Updates Scores & Level
textEasyScore.setText("Score: " + currentScore);
textEasyLevel.setText("Level: " + currentLevel);
break;
}//switch ends here
//stores the Score into the High Score page, when new High Score is reached it will auto-update
SharedPreferences sharedPrefsHighScore = getSharedPreferences("Prefs_HighScore",MODE_PRIVATE);
SharedPreferences.Editor editorScore = sharedPrefsHighScore.edit();
int storedHighScore = sharedPrefsHighScore.getInt("highScore",0);
if (currentScore>storedHighScore) {
editorScore.putInt("highScore", currentScore);
editorScore.commit();
//if a new High Score is achieved, the toastmessage "NEW HIGH SCORE!" will be shown (with modifications)
Toast highScoreToast = Toast.makeText(getApplicationContext(), "NEW HIGH SCORE!", Toast.LENGTH_LONG);
TextView toastMessage = (TextView) highScoreToast.getView().findViewById(android.R.id.message);
toastMessage.setTextColor(Color.WHITE);
toastMessage.setTextSize(25);
highScoreToast.show();
}//if-statement ends here
randomNumbersForEquation();
}//onClick ends here
//adds a random number for our Equation (for textEasyNumber1 and textEasyNumber2)
void randomNumbersForEquation(){
int addingOneTocurrentLevel = currentLevel + 1;
int numberRange = addingOneTocurrentLevel * 3;
Random randInt = new Random();
int Number1 = randInt.nextInt(numberRange);
Number1++;//don't want a zero value
int Number2 = randInt.nextInt(numberRange);
Number2++;//don't want a zero value
textEasyNumber1.setText("" + Number1);
textEasyNumber2.setText("" + Number2);
}//setQuestion ends here
Try these together
android:imeOptions="actionDone"
android:inputType="number"
android:maxLines="1"
Well, when you press "enter" key, the text doesn't get erased, rather it shifts up. After hitting enter key, press the up arrow key and you will find your text. The problem might be with the logic you have written for "Correct" button. Please share the code which is executed upon pressing "Correct" button
UPDATED --- Try using trim() method to remove trailing spaces. Since you are parsing the value into an int, the extra space might be causing the issue Something like this:
Integer.parseInt(editTextEasyResult.getText().toString().trim());
Another suggestion is, since you are developing a maths related app, you can restrict your EditText to accept numbers only. Do so by mentioning the following attribute for your edit text file:
android:inputType="number"
Doing so will present a numerical keyboard to the user without the enter key.

Characters appear in the order as i click

For example. There is picture on the top of the screen below that there are some empty boxes and below the boxes there are some buttons. Every button has a character for text("a","c","t"). You click on a button and the button's text appear in the box. You can click them in the order you want to but the answer is "cat" so when you put the characters in the correct order then you got a toast.
I tried to do it with TextViews and Buttons. I can make the button disappear when i click on it and a textview appear in the same time. But every textview has a fix place on the screen, so i need to put every character in every box invisible and when i click on the "c" character it appear in the first box and the other "c" characters stay invisible. But if i click on the "a" first, then it appears in the second box because there is too much variation to do all. I'm not good at explaining but if anyone has an idea how to do that easier please response!
Here is my code:
public class MainActivity extends ActionBarActivity implements OnClickListener{
Button b1;
Button b2;
Button b3;
TextView tg1;
TextView tg2;
TextView tg3;
TextView to1;
TextView to2;
TextView to3;
TextView tl1;
TextView tl2;
TextView tl3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.bg);
b1.setOnClickListener(this);
b2 = (Button)findViewById(R.id.bo);
b2.setOnClickListener(this);
b3 = (Button)findViewById(R.id.bl);
b3.setOnClickListener(this);
tg1 = (TextView)findViewById(R.id.tg1);
tg2 = (TextView)findViewById(R.id.tg2);
tg3 = (TextView)findViewById(R.id.tg3);
to1 = (TextView)findViewById(R.id.to1);
to2 = (TextView)findViewById(R.id.to2);
to3 = (TextView)findViewById(R.id.to3);
tl1 = (TextView)findViewById(R.id.tl1);
tl2 = (TextView)findViewById(R.id.tl2);
tl3 = (TextView)findViewById(R.id.tl3);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.bg:
b1.setVisibility(View.INVISIBLE);
tg1.setVisibility(View.VISIBLE);
tg2.setVisibility(View.INVISIBLE);
tg3.setVisibility(View.INVISIBLE);
break;
case R.id.bo:
b2.setVisibility(View.INVISIBLE);
to2.setVisibility(View.VISIBLE);
to1.setVisibility(View.INVISIBLE);
to3.setVisibility(View.INVISIBLE);
break;
case R.id.bl:
b3.setVisibility(View.INVISIBLE);
tl3.setVisibility(View.VISIBLE);
tl2.setVisibility(View.INVISIBLE);
tl1.setVisibility(View.INVISIBLE);
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="hu.szada.gombokelso.MainActivity"
android:orientation="horizontal">
<TextView
android:id="#+id/tl1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:visibility="invisible"
android:text="l"/>
<Button
android:id="#+id/bo"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="86dp"
android:onClick="onClick"
android:text="o" />
<Button
android:id="#+id/bl"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignBaseline="#+id/bg"
android:layout_alignBottom="#+id/bg"
android:layout_alignParentLeft="true"
android:layout_marginLeft="36dp"
android:onClick="onClick"
android:text="l" />
<Button
android:id="#+id/bg"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerVertical="true"
android:layout_marginRight="14dp"
android:layout_toLeftOf="#+id/bo"
android:onClick="onClick"
android:text="g" />
<TextView
android:id="#+id/tg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tl"
android:layout_alignBottom="#+id/tl"
android:layout_alignLeft="#+id/tl"
android:layout_weight="1"
android:visibility="invisible"
android:text="g" />
<TextView
android:id="#+id/to1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tl"
android:layout_alignBottom="#+id/tl"
android:layout_alignLeft="#+id/tl"
android:layout_weight="1"
android:visibility="invisible"
android:text="o" />
/// Second
<TextView
android:id="#+id/to2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tl1"
android:layout_alignBottom="#+id/tl1"
android:layout_marginLeft="19dp"
android:layout_toRightOf="#+id/tl1"
android:layout_weight="1"
android:visibility="invisible"
android:text="o" />
<TextView
android:id="#+id/tg2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/to2"
android:layout_alignBottom="#+id/to2"
android:layout_alignLeft="#+id/to2"
android:layout_weight="1"
android:visibility="invisible"
android:text="g" />
<TextView
android:id="#+id/tl2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/to2"
android:layout_alignBottom="#+id/to2"
android:layout_alignRight="#+id/to2"
android:layout_weight="1"
android:visibility="invisible"
android:text="l" />
/// Third
<TextView
android:id="#+id/tg3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/to2"
android:layout_alignBottom="#+id/to2"
android:layout_alignRight="#+id/bl"
android:layout_weight="1"
android:visibility="invisible"
android:text="g" />
<TextView
android:id="#+id/tl3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tg3"
android:layout_alignBottom="#+id/tg3"
android:layout_alignLeft="#+id/tg3"
android:layout_weight="1"
android:visibility="invisible"
android:text="l" />
<TextView
android:id="#+id/to3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tg3"
android:layout_alignBottom="#+id/tg3"
android:layout_toRightOf="#+id/tl3"
android:layout_weight="1"
android:visibility="invisible"
android:text="o" />
You might want to try a slightly different approach.
If I understand you correctly, you want to "type" a word out using given lettered buttons. Like one of those hangman style games.
Why not append the text views on the fly.
Something like
#Override
public void onClick(View v) {
//Grab the surrounding layout for the textviews
GridView answerGrid = (GridView)getViewById(R.id.answerGrid);
//Get the text that was on the button
Button b = (Button)v;
String btnText = b.getText().toString();
//Make a text view with text
TextView txt = new TextView();
text.setText(btnText);
//Append to text view container
answerGrid.addView(txt);
//Invisible button
b.setVisibility(View.INVISIBLE);
}
Haven't tested to see if this is perfect, but its a start.
=====
I've looked at your xml
Why not use GridViews?
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
....>
<GridView android:id="#+id/answerGrid"
....>
<!-- Put nothing here. This is for answers -->
</GridView>
<GridView android:id="#+id/lettersGrid"
android:layout_below="answerGrid"
....>
<!-- Buttons in here -->
</GridView>
</RelativeLayout>
This way you can customise the number of rows/columns based on the length of the word you're playing with. And GridView will automatically give you a neat layout and spacing.
Have a look at the GridView doc and get it customised the way you want it.
See my edits above for the Java code.

how to dynamically change the value of the find view by id in android?

i am a basic learner in android. What i am trying to achieve from my code is that : i want to dynamically change the value of radio buttons of a radio group inside a for loop. Then, grab the text value so that i can compare, lets say if the value is "Take Out", i want the rb1 to be checked.
Here is the radio group
<RadioGroup
android:layout_marginTop="20dp"
android:layout_width="fill_parent"
android:layout_height="120dp"
android:layout_alignBottom="#+id/add"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="20dp"
android:id="#+id/rg1">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take Out"
android:id="#+id/rb1"
android:checked="true"
android:onClick="selectSomething"
/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sit down"
android:id="#+id/rb2"
android:checked="false" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delivery"
android:id="#+id/rb3"
android:checked="false" />
</RadioGroup>
What i have tried so far:
int count = rg1.getChildCount();
//Make checked if the value is equal
for(int i = 0; i < count;i++){
String myshit = "rb"+i;
int id = getResources().getIdentifier(myshit, "id", getPackageName());
RadioButton RadioValue = (RadioButton) findViewById(id);
String _RadioValue = RadioValue.getText().toString();
Log.d("abc",_RadioValue);
}
For testing, i wanted to print out the values in Log but it does not compile and throws error. I am just half way thorugh in my code. Is there a better way to solve this problem ? Need your expertise. Thank You !
You are doing it the wrong way.
All of your RadioButtons should point to a common function.
That is, all of them should have this property assigned:
android:onClick="selectSomething"
Inside that method, do something like:
public final void selectSomething(final View v)
{
switch(v.getId())
{
case R.id.rb1:
{
String str = "Take out";
System.out.println(str);
break;
}
// all other cases
// ...
}
}

Populate radiobuttons from database android

i'm developing a driving school test app and I need some help.
I have xml file like this:
<!-- language: lang-xml -->
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget28"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#AAC1E2" >
<LinearLayout
android:id="#+id/widget29"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/i1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/e1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enun"
android:textAppearance="?android:attr/textAppearanceMedium" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<ImageView
android:id="#+id/i2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/e2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enun"
android:textAppearance="?android:attr/textAppearanceMedium" />
<RadioGroup
android:id="#+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
... x 30 times and a button that will correct the test and show if you passed or not. You pass the test when you fail 3 questions or less.
Questions are stored this way:
Id_question Id_topic Id_test Question AnswerA AnswerB AnswerC AnswerOK Image
Id_question Id_topic and id_test are integer fields
Question and AnswerA-C are text fields
AnswerOK is an integer field. If AnswerA is OK = 1, AnswerB = 2, AnswerC = 3
Image is the name of the related image, extracted from resources folder.
I use a database to populate every field in the xml. Images and questions are extracted from database this way:
<!-- language: lang-java -->
Cursor c = adbh.query(bundle.getString("test"));
//"test"-->"SELECT question, image FROM table WHERE id_test = 1"
Integer i = 1;
if (c.moveToFirst()) {
do {
String path = c.getString(index);
String nimage = "i"+i;
int idImage = getResources().getIdentifier(nimage, "id", this.getPackageName());
ImageView image = (ImageView) findViewById(idImage);
int idDrawable = getResources().getIdentifier(ruta, "drawable", this.getPackageName());
image.setImageResource(idDrawable);
String nenun = "e"+i;
String enun = c.getString(anotherIndex);
int idEnun = getResources().getIdentifier(nenun, "id", this.getPackageName());
TextView txtenun = (TextView) findViewById(idEnun);
txtenun.setText(enun);
i++;
} while (c.moveToNext());
How can I populate radiobuttons? The query would be "SELECT AnswerA, AnswerB, AnswerC from table WHERE id_test = 1"
And my last question is how can I correct the test. I think on storing radiobutton pressed (I don't know exactly how) in an array and then compare with correct answers. The query would be "SELECT AnswerOK from table WHERE id_test = 1".
Example:
Array of answered questions:
1 1 1 2 2 3 2 3 1 3 2...
Array of correct answers:
3 2 1 2 2 3 2 3 2 2 2...
<!-- language: lang-java -->
for (int i=0; i<30; i++)
if (a[i] == b[i])
numberOfRightAnswers++;
Thank you :)
How can I populate radiobuttons? The query would be "SELECT AnswerA,
AnswerB, AnswerC from table WHERE id_test = 1"
Will probably want to select those values directly in the first query, so instead of :
Cursor c = adbh.query(bundle.getString("test"));
//"test"-->"SELECT question, image FROM table WHERE id_test = 1"
will have:
Cursor c = adbh.query(bundle.getString("test"));
//"test"-->"SELECT question, AnswerA, AnswerB, AnswerC, image FROM table WHERE id_test = 1"
Then in that while loop assign the text to the RadioButtons like you did for TextView txtenun.
And my last question is how can I correct the test. I think on storing
radiobutton pressed (I don't know exactly how) in an array and then
compare with correct answers.
Add a OnCheckedChangeListener() to all of your RadioGroups. In that listener you'll get the RadioGroup where the user checked something and the id of the checked RadioButton. Use that to construct the array of correct answers.
Some advices:
Maybe you should modify your layout and your current approach. Making the user scroll your 30 question layout might not be such a good idea, also you're loading many resources although the user will not actually see them until it gets to that particular question(I don't know the size of your image, if they are small this probably isn't an issue). You're other alternatives are a ListView layout or a simple layout of one question that you populate on demand depending on which questions is the user at. My advice would be the second option. That option will also help you avoid the getIdentifier method calls, this method is slower then the findViewById and should be avoided. Bellow is a layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#AAC1E2" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/questionImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/questionText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enun"
android:textAppearance="?android:attr/textAppearanceMedium" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="3" >
<Button
android:id="#+id/previousQuestion"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="previous" />
<Button
android:id="#+id/validateTest"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="validate" />
<Button
android:id="#+id/nextQuestion"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1"
android:text="next" />
</LinearLayout>
</LinearLayout>
</ScrollView>
You'll make a query for all the question in that test(including all the data) and start with a static field int counter = 0. When the app is started you'll move the cursor to the counter value(which is 0 at the start):
c.moveToPosition(counter);
and use the values from that row to populate the above question layout:
ImageView questionImage = (ImageView) findViewById(R.id.questionImage);
int idDrawable = getResources().getIdentifier(ruta, "drawable", this.getPackageName());
questionImage.setImageResource(idDrawable);
String enun = c.getString(anotherIndex);
TextView txtenun = (TextView) findViewById(R.id.questionText);
txtenun.setText(enun);
// will do the same to populate the other parts of the question from the cursor
When the user presses the nextQuestion Button you'll increment the counter value(you should do some checks so you don't go overboard the 30 questions), move the cursor to the counter position again and then populate the layout like above. When the user presses previousQuestion you decrement counter, move the cursor and again populate the layout with data.
Also you'll add only one OnCheckedChangeListener to your RadioGroup. When that listener fires you should store the question id(from the counter value you should be able to tell on which question you are) and the selected RadioButton in a data structure(probably a HashMap), retrieve the correct answers for the test from the database and see if the user it's a good driver.
Also you could(probably) optimize your database.
Edit:
private ArrayList<Integer> responses = new ArrayList<Integer>(); // this will hold the number of the correct answer. Note that this will work if the user answers question one after the other
// if the user skips question you'll get in trouble, this is one of the reasons why your design is not so good.
String rg = "radioGroup" + i;
int idRg = getResources().getIdentifier(rg, "id", this.getPackageName());
RadioGroup radioGroup = (TextView) findViewById(idRg);
radioGroup.setOnChekedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged (RadioGroup group, int checkedId) {
if (group.getChildAt(0).getId() == checkedId) {
responses.add(0); // the first answer was checked
} else if (group.getChildAt(1).getId() == checkedId) {
responses.add(1); // the first answer was checked
} else if (group.getChildAt(2).getId() == checkedId) {
responses.add(2); // the first answer was checked
}
}
});
According to #Luksprog answer this is my finally working loop:
Cursor c = adbh.query(bundle.getString("test"));
Integer i = 1;
if (c.moveToFirst()) {
do {
String ruta = c.getString(4);
String nimage = "i" + i;
int idImage = getResources().getIdentifier(nimage, "id",
this.getPackageName());
ImageView image = (ImageView) findViewById(idImage);
int idDrawable = getResources().getIdentifier(ruta, "drawable",
this.getPackageName());
image.setImageResource(idDrawable);
String rgname = "radioGroup"+i;
int idRg = getResources().getIdentifier(rgname, "id",
this.getPackageName());
RadioGroup rg = (RadioGroup) findViewById(idRg);
rg.removeAllViews();
RadioButton rb1 = new RadioButton(this);
rb1.setId(i);
rb1.setText(c.getString(1));
rg.addView(rb1);
RadioButton rb2 = new RadioButton(this);
rb2.setId(i+1);
rb2.setText(c.getString(2));
rg.addView(rb2);
RadioButton rb3 = new RadioButton(this);
rb3.setId(i+2);
rb3.setText(c.getString(3));
rg.addView(rb3);
String nenun = "e" + i;
String enun = c.getString(0);
int idEnun = getResources().getIdentifier(nenun, "id",
this.getPackageName());
TextView txtenun = (TextView) findViewById(idEnun);
txtenun.setText(enun);
i++;
} while (c.moveToNext());

Categories

Resources