Add dynamic Radiobutton into RadioGroup - android

public class MCQSample extends Activity implements OnClickListener{
TextView title;
String gotBread;
RadioGroup AnswerRG;
int value ;
int value1;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mcqsample);
title = (TextView) findViewById(R.id.abc);
nextP = (Button) findViewById(R.id.nextP);
backP = (Button) findViewById(R.id.backP);
AnswerRG = (RadioGroup) findViewById(R.id.AnswerRG);
Bundle b = getIntent().getExtras();
value = b.getInt("key", 0);
}
}
Hi guys, im doing the Android app and stuck on create the dynamic radio-button. Because i don't know how many button i need (which depend on the value - user input). I read some posts which can add on the Layout but i want to add into the radioGroup. Is there any ways? Thank

Step #1: Create a new RadioButton via its constructor and configure it as you see fit.
Step #2: Call addView() on your RadioGroup to add the RadioButton to it.
Step #3: There is no step #3

try this way to add radiobutton in RadioGroup:
private final int WC = RadioGroup.LayoutParams.WRAP_CONTENT;
RadioGroup.LayoutParams rParams;
AnswerRG = (RadioGroup) findViewById(R.id.AnswerRG);
RadioButton radioButton = new RadioButton(this);
radioButton.setText("Yellow");
radioButton.setId(1001);//set radiobutton id and store it somewhere
rParams = new RadioGroup.LayoutParams(WC, WC);
AnswerRG.addView(radioButton, rParams);

Related

Multiple RadioGroup onCheckedChanged

This is my first time doing radio groups. Im trying to save the values from 3 groups to Shared Prefs. It works fine with one group, but once I try to add 2 more, all the pref values are just the last group in the form. Im not sure what to do to use multiple RadioGroups. Any help would be appreciated.
onCreate
RadioGroup radioGroupGender = (RadioGroup) findViewById(R.id.gender_radio);
radioGroupGender.setOnCheckedChangeListener(this);
RadioGroup radioGroupActivity = (RadioGroup) findViewById(R.id.activity_level);
radioGroupActivity.setOnCheckedChangeListener(this);
RadioGroup radioGroupStatus = (RadioGroup) findViewById(R.id.current_status);
radioGroupStatus.setOnCheckedChangeListener(this);
And my onCheckedChanged
public void onCheckedChanged(RadioGroup radioGroup, int i) {
int genderId = radioGroup.getCheckedRadioButtonId();
RadioButton genderBut = (RadioButton)radioGroup.findViewById(genderId);
gender_radio = genderBut.getText().toString();
int activityLvl = radioGroup.getCheckedRadioButtonId();
RadioButton activityLvlBut = (RadioButton)radioGroup.findViewById(activityLvl);
activity_level = activityLvlBut.getText().toString();
int currentStat = radioGroup.getCheckedRadioButtonId();
RadioButton CurrentBut = (RadioButton)radioGroup.findViewById(currentStat);
current_status = CurrentBut.getText().toString();
}
You are using the same gender_radio activity_level current_status , they get overwriten on every onCheckedChanged() call, only the values of the last call of onCheckedChanged() will be saved

How to randomize questions without repetition from SQLite?

I'm developing a simple quiz in my android studio. I'm using a database but I would like to randomize the questions every time the user clicks on the quiz button. I have created 5 sample questions so far.
Use Collections.shuffle on your List<Question>, then use an Iterator<Question> to pick out the questions as you click a button.
Assuming you implemented both equals and hashcode for your Question class, then a LinkedHashSet will remove the duplicates, so repetition won't happen.
Here is an Activity based on your class that should show these concepts.
public class QuizActivityMarketing extends Activity {
private Iterator<Question> questionIterator;
private TextView txtQuestion;
private RadioButton rda, rdb, rdc, rdd;
private Button butNext;
private Question currentQ;
private int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define your views
txtQuestion = (TextView) findViewById(R.id.textView1);
rda = (RadioButton) findViewById(R.id.radio0);
rdb = (RadioButton) findViewById(R.id.radio1);
rdc = (RadioButton) findViewById(R.id.radio2);
rdd = (RadioButton) findViewById(R.id.radio3);
butNext = (Button) findViewById(R.id.button1);
// Get and randomize the questions
DbHelperMarketing db = new DbHelperMarketing(this);
final List<Question> questions = db.getAllQuestions();
Collections.shuffle(questions);
questionIterator = new LinkedHashSet<Question>(questions).iterator();
// Setup the first question
if (questionIterator.hasNext()) {
currentQ = questionIterator.next();
setQuestionView(currentQ);
}
// Hook up the button-clicking
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Check the correct answer
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());
if (currentQ.getANSWER().equals(answer.getText())) {
score++;
Log.d("score", "Your score" + score);
}
// Load the next question, if there are any
if (questionIterator.hasNext()) {
currentQ = questionIterator.next();
setQuestionView(currentQ);
} else { // Done asking questions
setQuestionView(null);
Intent intent = new Intent(QuizActivityMarketing.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
private void setQuestionView(Question currentQuestion) {
if (currentQuestion != null) {
txtQuestion.setText(currentQuestion.getQUESTION());
rda.setText(currentQuestion.getOPTA());
rdb.setText(currentQuestion.getOPTB());
rdc.setText(currentQuestion.getOPTC());
rdd.setText(currentQuestion.getOPTD());
} else {
txtQuestion.setText("");
rda.setText("");
rdb.setText("");
rdc.setText("");
rdd.setText("");
}
}
}
I suggest doing:
Option1: If you don't want duplicate Questions
Use collections, since Sets doesn't allow duplicates and lists can be shuffled
Adapt (if not already) your class Question, so you can used in the Set and so not allowing duplicates...(by this override equals AND hashcode)
populate the Collection, shuffle it, get a random element of it
Option2: If you only want one of the questions at random
this is quite the same,
instead of using a set use a list...
omit step 2 since duplicated questions are no a big deal...
but still populate the Collection, shuffle it, get a random element of it
and there you are :)

How to save RadioGroup State using SharedPreferences

i have created a radio group which represents a question and has 4 answer choices (a , b , c , and d ) , hence i created 4 radio buttons for the radiogroup , and it worked fine , but what i want is to keep the answer checked when i leave the activity and return back to it , here is the code :
public class P2 extends Page1 {
RadioGroup rg2 ;
RadioButton r2a , r2b , r2c , r2d ;
Button b2n , b2b ;
TextView tv ;
int count ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p2);
rg2 = (RadioGroup) findViewById(R.id.RG2);
r2a = (RadioButton) rg2.getChildAt(0);
r2b = (RadioButton) rg2.getChildAt(1);
r2c = (RadioButton) rg2.getChildAt(2);
r2d = (RadioButton) rg2.getChildAt(3);
b2n = (Button) findViewById(R.id.B2n); // next button
b2b = (Button) findViewById(R.id.B2b); // back button to page1
tv = (TextView) findViewById(R.id.res);
rg2.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
if (r2c.isChecked()){
count ++ ; // since c is the correct answer add 1 to count (mark)
}
}
});
}
public void move21(View view) { // called when b2b is clicked to go back to page1
Intent intent = new Intent(this , Page1.class) ;
startActivity (intent) ;
} }
BTW, i did not define id's for the radiobuttons , just the id (rg2) for the radiogroup .
how can i save the state of the radiogroup using shared preferences ?
thanks
What you can do before you leave the current activity is save the state with something like:
SharedPreferences settings = getSharedPreferences("answers", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("r2a",r2a.isChecked());
editor.putBoolean("r2b",r2b.isChecked());
editor.putBoolean("r2c",r2c.isChecked());
editor.putBoolean("r2d",r2d.isChecked());
editor.apply();
Then, when you come back to the activity, you can do:
SharedPreferences settings = getSharedPreferences("answers", MODE_PRIVATE);
boolean r2achecked = settings.getBoolean("r2a",false);
boolean r2bchecked = settings.getBoolean("r2b",false);
boolean r2cchecked = settings.getBoolean("r2c",false);
boolean r2dchecked = settings.getBoolean("r2d",false);
Then check each of those newly created bools and if one of them is true, set that button to checked.

save the info of activity android

i have a serious problem in my application, it's about the status of activity, in every activity he has radio buttons check buttons and Edit text, i want the user when he returns to
finds all information that he selected are the same, i read a lot about the cycle of an application in android but i can't make it work, i would be very glad if someone help me.
public class ActivityDeux extends Activity {
final String PREFS_NAME = "MyPrefsFile";
final String ID = "id";
DBAdapter db = new DBAdapter(this);
public void ajouter(View v) {
db.open();
SharedPreferences prefs2 = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
long id = prefs2.getLong(ID, 0);
db.insertMENAGE2(id,a16,b17,rm_18_1ts,rm_18_2ts,c19,d20,e21);
db.close();
}
int a16;
int b17;
int c19;
int d20;
int e21;
private RadioGroup rm_16;
private RadioButton rm_16_1 ;
private RadioButton rm_16_2 ;
private RadioButton rm_16_3 ;
private RadioButton rm_16_4 ;
private RadioButton rm_16_5 ;
private RadioButton rm_16_6 ;
private RadioButton rm_16_7 ;
EditText rm_16_autre;
String rm_16_autrets = "";
private RadioGroup rm_17;
private RadioButton rm_17_1 ;
private RadioButton rm_17_2 ;
private RadioButton rm_17_3;
private RadioButton rm_17_4 ;
private RadioButton rm_17_5 ;
EditText rm_17_autre;
String rm_17_autrets = "";
EditText rm_18_1 ;
EditText rm_18_2 ;
String rm_18_1ts = "";
String rm_18_2ts = "";
private RadioGroup rm_19;
private RadioButton rm_19_1 ;
private RadioButton rm_19_2 ;
private RadioButton rm_19_3;
private RadioButton rm_19_4 ;
private RadioButton rm_19_5 ;
EditText rm_19_5_autre;
String rm_19_5_autrets = "";
private RadioGroup rm_20;
private RadioButton rm_20_1 ;
private RadioButton rm_20_2 ;
private RadioButton rm_20_3;
private RadioButton rm_20_4 ;
private RadioButton rm_20_5 ;
EditText rm_20_5_autre ;
String rm_20_5_autrets = "";
private RadioGroup rm_21;
private RadioButton rm_21_1 ;
private RadioButton rm_21_2 ;
private RadioButton rm_21_3;
private RadioButton rm_21_4 ;
private RadioButton rm_21_5 ;
EditText rm_21_5_autre ;
String rm_21_5_autrets = "";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deux);
rm_16_autre = (EditText)findViewById(R.id.rm_16_autre);
rm_17_autre = (EditText)findViewById(R.id.rm_17_autre);
rm_18_1 = (EditText)findViewById(R.id.rm_18_1);
rm_18_2 = (EditText)findViewById(R.id.rm_18_2);
rm_19_5_autre = (EditText)findViewById(R.id.rm_19_5_autre);
rm_20_5_autre = (EditText)findViewById(R.id.rm_20_5_autre);
rm_21_5_autre = (EditText)findViewById(R.id.rm_21_5_autre);
You can use the onSaveBundleInstance(Bundle outBundle) event, to save the state of your activity. And in onCreate of your activity, you'll get the same bundle..
It depends upon your requirement, suppose if you want to persisit user selection even when user closes app, and display next time when he returns then the fastest possible way will be
-- SharedPreferences, Write all the values user enters in radio boxes and edit boxes into shared preferences using a preferred key(I would suggest widget ids), and in on create initialize them by reading preference again using same keys. you have your solution this way.
Else, if you just want to preserve value for current session, the you can use either of following
-- Use global data holders to preserve values e.g Maps
-- Use onSaveInstanceState & onRestoreInstanceState callbacks from lifecycle, sample code below
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
outState.putBoolean("WIDGET ID as KEY", value); // Save you values from radio boxes here, whether they are checked or not
outState.putString("WIDGET ID as KEY", value); // Write values from Editboxes here
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
// Read the values from bundle, through keys you used to store, and set them to corresponding widgets
}
Look at the image above. The method onCreate is just called once and the onResume method is called when user returns to the activity (through the back button, for example). For this, you could have a variable that stores the box checked and stored when the user selects it. Then, in onResume method, you can "populate" the boxes.

Methods for UI elements created dynamically on Android

I have a doubt... In my Android app, I have an Activity that its GUI is created dynamically from certain data inside my SQLite database... I didn't had any kind of trouble with this and is working fine...
In this activity, there are a bunch of TextView's and RadioGroup's and RadioButton's that are created inside a for loop and the amount of RadioButton's varies due to a condition inside this loop... like this:
for(int i=0;i<numFilasFormulario;i++){
TextView pregunta = new TextView(this);
pregunta.setText(c.getString(c.getColumnIndex("texto")));
pregunta.setGravity(Gravity.LEFT);
pregunta.setTextColor(Color.rgb(0, 0, 0));
pregunta.setTextSize(15);
pregunta.setLayoutParams(params);
ll.addView(pregunta);
if(c.getString(c.getColumnIndex("tipopregunta")).equals("Si o No")){
RadioGroup rg = new RadioGroup(this);
ll.addView(rg);
RadioButton b1 = new RadioButton(this);
b1.setText("SI");
rg.addView(b1);
RadioButton b2 = new RadioButton(this);
b2.setText("NO");
rg.addView(b2);
}else{
if(c.getString(c.getColumnIndex("tipopregunta")).equals("Seleccion Simple")){
RadioGroup rg = new RadioGroup(this);
ll.addView(rg);
RadioButton b1 = new RadioButton(this);
b1.setText("SI");
rg.addView(b1);
RadioButton b2 = new RadioButton(this);
b2.setText("NO");
rg.addView(b2);
RadioButton b3 = new RadioButton(this);
b3.setText("N/A");
rg.addView(b3);
}
}
c.moveToNext();
}
So my question is how to obtain the value of the RadioButton selected by the user... I mean, do I have to invoke the method setOnClickListener() for each RadioButton? Or I have to do it for each RadioGroup? And where do I declare this statements: inside the for loop or outside? Or there is another way?
I'm very very lost here! Any kind of help would be apreciated! Thanks!
There are only one way to get it by using OnCheckedChangeListener
You can create each listener and assign it to your RadioGroup in the loop but I am not recomment to do that. You can create multiple ID in your resource and the create just a single listener before loop and in the loop assign it to your RadioGroup ( Your Radiogroup need set the ID that create in the resource ). Here is example:
OnCheckedChangeListener listener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (group.getId()) {
case R.id.myradio_group1:
// DO your work here
break;
default:
break;
}
}
};
// your loop is here
for(int i=0;i<numFilasFormulario;i++){
....
RadioGroup rg = new RadioGroup(this);
rg.setId(R.id.myradio_group1); // or simply just using rg.setId(i+1000);
// make sure 1000, 1001, 1002, ... is already create at Resource
....
}

Categories

Resources