How to save RadioGroup State using SharedPreferences - android

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.

Related

Kotlin how to save Radio Button and display values?

So I'm trying to learn Kotlin and have been using Android Studios to practice and learn. Currently I'm trying to make a simple activity with RadioGroup (with Radio Buttons), save the selected value, and then display how much of each value (radiobutton) was selected.
My question is, how do I print which button was selected, and how many of this type of button was selected?
I tried the following:
//in MainActivity.kt in my MainActivity class
s1RadioGroup.setOnCheckedChangeListener { _, checkedId ->
//if catButton was selected add 1 to variable cat
if(checkedId == R.id.catRadio) {
catSum += 1
print(catSum)
}
//if dogButton was selected add 1 to variable dog
if(checkedID == R.id.dogRadio) {
dogSum += 1
print(dogSum)
}
Not sure if I'm going about it the right way, but the desired output is:
I have layout, ID's, clear button, and everything else working. But I'm not sure how to use onClickListener event on 'SaveButton' to save selected radio button and then displaying results (Ex: Cat = 1, Dog =2). I would appreciate any suggestions, or if you can point me in the right direction.
You can maybe try something like this:
RadioButton rb = (RadioButton) findViewById(R.id.radio_button);
// restore previous state
rb.setChecked(lastButtonState);
// set a listener
rb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call this to enable editing of the shared preferences file
// in the event of a change
SharedPreferences.Editor editor = sharedpreferences.edit();
Boolean isChecked = rb.isChecked();
// use this to add the new state
editor.putBoolean(BUTTON_STATE, isChecked);
// save
editor.apply();
}
});
I realize that this is in Java, and you're asking for kotlin, but a SharedPreference, is what you would need to save the radio button's state.
if you want to save all datam you can use database or sharedprefrence.
and if you only want just display value is clicked, you can make like this in button save.
String result1 = ""
String result2 = ""
String result3 = ""
RadioGroup radioGroup = findViewById('yourRGidFromXml')
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
int selectedId = radioGroup.getCheckedRadioButtonId();
RadioButton rb = findViewById(selecetedId)
result1= rb.getText.toString()
Log.i("ID", String.valueOf(selectedId));
}
});
//this just for see result
btnSave.OnclikListener(view -> {
Log.i("Result1",result1)
})
you can copy code and android will convert that code to kotlin.

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 :)

Shared preferences doesn't store int data

I have an activity with two TextViews which show int values. These values change incrementally (1, 2, 3, and so...) when the user clicks a button. I use SharedPreferences to store that values via button click. When I close the app and open it again, the values are correctly displayed in the TextViews, but if they change, they should be added from the previous stored value. Problem is that they start to count from zero.
Here is my code:
public class Roulette1 extends ActionBarActivity {
Button button0, button1;
int click_button0, click_button1;
public static final String button0Str = "button0Key";
public static final String button1Str = "button1Key";
public static final String MyPREFERENCES = "MyPrefsRoulette1";
SharedPreferences sharedpreferences;
TextView times_0_tv;
TextView times_1_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
times_0_tv = (TextView) findViewById(R.id.times_0);
times_1_tv = (TextView) findViewById(R.id.times_1);
button0 = (Button) findViewById(R.id.button0);
button1 = (Button) findViewById(R.id.button1);
final TextView total_clicks_tv = (TextView) findViewById(R.id.total_clicks);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button1 = click_button1 + 1;
int total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
times_0_tv.setText(click_button0);
times_1_tv.setText(click_button1);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click_button0 = click_button0 + 1;
int total_clicks = click_button0 + click_button1;
total_clicks_tv.setText(String.valueOf(total_clicks));
times_0_tv.setText(click_button0);
times_1_tv.setText(click_button1);
}
});
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if (sharedpreferences.contains(button0Str))
{
times_0_tv.setText(sharedpreferences.getString(button0Str, ""));
}
if (sharedpreferences.contains(button1Str))
{
times_1_tv.setText(sharedpreferences.getString(button1Str, ""));
}
}
public void run1(View view) {
SharedPreferences.Editor editor = sharedpreferences.edit();
String times0string = times_0_tv.getText().toString();
String times1string = times_1_tv.getText().toString();
editor.putString(button0Str, times0string);
editor.putString(button1Str, times1string);
editor.commit();
}
Hope you have any idea. Thanks!
When you read from sharedPrefs, remember to update the field counters and not just the value of the textViews.
As suggested in the comments, a possible solution would be to use the textView value as the state, updating that directly. Otherwise you have to keep the counters updated manually, for example by updating the fields value at the same time you update the textView value. Personally, I prefer to keep the state separated from the presentation, so that it is easier to compute something with that value later (the downside is that you have to keep the view synchronized. This might change with the new data binding library).
PS I purposely did not put any code, because the solution is trivial and there are other answers with code, but more importantly because I think that the data binding library is a much cleaner way to deal with this kind of problems, even though it's still in beta stage.
Sharedpreferences stored int data also. Check this link:
http://androidexample.com/Android_SharedPreferences_Basics/index.php?view=article_discription&aid=126&aaid=146
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
/**************** Storing data as KEY/VALUE pair *******************/
editor.putBoolean("key_name1", true); // Saving boolean - true/false
editor.putInt("key_name2", "int value"); // Saving integer
editor.putFloat("key_name3", "float value"); // Saving float
editor.putLong("key_name4", "long value"); // Saving long
editor.putString("key_name5", "string value"); // Saving string
// Save the changes in SharedPreferences
editor.commit(); // commit changes
I think there is some logical mistake in your code. Please check.
Add this code to the very beginning of your oncreate:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
times0string = String.valueOf(sharedPreferences.getString(button0Str, 0));
times1string = String.valueOf(sharedPreferences.getString(button1Str, 0));
To solve your problem, Try below code:
Replace first two line inside button1 onClick()
click_button1 = Integer.parseInt(sharedpreferences.getString(button1Str, "")) + 1;
int total_clicks = Integer.parseInt(sharedpreferences.getString(button0Str, "")) + click_button1;
Replace first two line inside button0 onClick()
click_button0 = Integer.parseInt(sharedpreferences.getString(button0Str, "")) + 1;
int total_clicks = click_button0 + Integer.parseInt(sharedpreferences.getString(button1Str, ""));

saving the state of radiobuttons

Hi I'm trying to create an app for Android and in order to develop it i need to navigate through different pages where each page has only one question and 4 answers(a,b,c,d). For this task I have defined 4 radiobuttons for each question. What I want to obtain is that if any radiobutton is checked , the other radiobuttons are unchecked (radiobuttons checked false) . And i want that when the user goes thorugh differentes pages the value can be retrieved. I have tried this code , however it worked fine with selecting one answer and uncheck the others , but it didnt work for saving the state of the radiobuttons even though i used shared preferences .
public class Page1 extends Activity {
RadioButton r1a , r1b , r1c , r1d ;
Button b1n ; // this is a next-button that will navigate to page2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
SharedPreferences pref ;
r1a = (RadioButton) findViewById(R.id.Q1a);
r1b = (RadioButton) findViewById(R.id.Q1b);
r1c = (RadioButton) findViewById(R.id.Q1c);
r1d = (RadioButton) findViewById(R.id.Q1d);
b1n = (Button) findViewById(R.id.B1n);
pref = getSharedPreferences("Answers", 0);
final Editor editor = pref.edit();
r1a.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1a.isChecked()){
r1b.setChecked(false);
r1c.setChecked(false);
r1d.setChecked(false);
}
}
});
r1b.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1b.isChecked()){
r1a.setChecked(false);
r1c.setChecked(false);
r1d.setChecked(false);
}
}
});
r1c.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1c.isChecked()){
r1a.setChecked(false);
r1b.setChecked(false);
r1d.setChecked(false);
}
}
});
r1d.setOnCheckedChangeListener (new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
if (r1d.isChecked()){
r1c.setChecked(false);
r1a.setChecked(false);
r1b.setChecked(false);
}
}
});
// i use this to save the state , but it fails :(
editor.putBoolean("questionA", r1a.isChecked());
editor.putBoolean("questionB", r1b.isChecked());
editor.putBoolean("questionC", r1c.isChecked());
editor.putBoolean("questionD", r1d.isChecked());
editor.commit();
}
public void move12(View view) { // instantiated when b1n is clicked
Intent intent = new Intent(this , P2.class) ;
startActivity (intent) ;
}
}
i have two questions here :
is this code ok ? or is there a better idea for handling the checked buttons ?
the shared preference does not work , anytime i return to page1 all the radiobuttons are unchecked and the state fail to be saved. what is the cause of the problem ?and how can it be resolved ? any ibeads please .
Your code for saving state is ok. Your radioButtons are unchecked because nowhere in Page1 you actually read from SharedPreferences and set their state. You could add this in onCreate():
r1a.setChecked(pref.getBoolean("questionA", false));
r1b.setChecked(pref.getBoolean("questionB", false));
r1c.setChecked(pref.getBoolean("questionC", false));
r1d.setChecked(pref.getBoolean("questionD", false));
First though, check if preference file is present and if states of each buttons have been saved.
You can sort of truncate your onCheckChangedListeners to just one and then have a switch that checks to see which RadioButton was clicked, but the way you did it is fine.
As per saving the data, it doesn't look like you're attempting to read the data that you saved. First of all, you should put all of your data saving inside the move12 method. Secondly, try adding something like this to your onCreate:
bool aChecked = prefs.getBoolean("questionA",false);
if(aChecked)
r1a.setChecked(true);
Do that for all four.

Android: Save State of Radio Buttons

Hi I'm trying to create an app for Android and in order to develop it i need to navigate through different pages and questions. For this task I have defined a radiogroup with some radiobuttons. What I want to obtain is each question answered radiobutton and when the user goes thorugh differentes pages the value can be retrieved. I have tried this code that consists of that if there is one selected radiobutton, there arent created new radiobuttons (radiobuttons checked false). However with this code, there is always a selected answer so there is always the same radiobutton selected. I will appreciate some help.
radBotA.setOnCheckedChangeListener(radioCheckChangeListener);
radBotB.setOnCheckedChangeListener(radioCheckChangeListener);
radBotC.setOnCheckedChangeListener(radioCheckChangeListener);
radBotD.setOnCheckedChangeListener(radioCheckChangeListener);
radBotA.setOnClickListener(radioClickListener);
radBotB.setOnClickListener(radioClickListener);
radBotC.setOnClickListener(radioClickListener);
radBotD.setOnClickListener(radioClickListener);
if (radBotA.isChecked()){
Answers[position]="A";
}
else if(radBotB.isChecked()){
Answers[position]="B"; }
else if(radBotB.isChecked()){
Answers[position]="C"; }
else if(radBotC.isChecked()){
Answers[position]="D"; }
else if(radBotD.isChecked()){
Answers[position]="D"; }
else {
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
}
bPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position = position -1;
questions.Previous();
currentQuestion();
}
});
bNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
position = position +1;
questions.Next();
currentQuestion();
}
});
private void currentQuestion() {
if (position==0){
bPrevious.setVisibility(View.GONE);
}else{
bPrevious.setVisibility(View.VISIBLE);
}
if (position==nPreguntas-1){
bNext.setVisibility(View.GONE);
}else{
bNext.setVisibility(View.VISIBLE);
}
questions.currentQuestion(this, category);
enunciado.setImageResource(Enunciado[position]);
pregunta.setText(questions.getPregunta());
final RadioButton radBotA = new RadioButton(this);
final RadioButton radBotB = new RadioButton(this);
final RadioButton radBotC = new RadioButton(this);
final RadioButton radBotD = new RadioButton(this);
radBotA.setText("A. " + questions.getRespuestaA());
radBotB.setText("B. " + questions.getRespuestaB());
radBotC.setText("C. " + questions.getRespuestaC());
radBotD.setText("D. " + questions.getRespuestaD());
String nprueba = "Item " + questions.getId() + " de "+ nPreguntas;
NombrePrueba.setText(nprueba);
if (radBotA.isChecked()){
Answers[position]="A";
}
else if(radBotB.isChecked()){
Answers[position]="B"; }
else if(radBotB.isChecked()){
Answers[position]="C"; }
else if(radBotC.isChecked()){
Answers[position]="D"; }
else if(radBotD.isChecked()){
Answers[position]="D"; }
else {
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
radBotA.setChecked(false);
}
}
thank you all for your time
Edit:
public void save(){
SharedPreferences settings = getSharedPreferences("Answers", 0);
SharedPreferences.Editor e = settings.edit();
e.putBoolean("A0",radBotA.isChecked());
e.putBoolean("B0",radBotB.isChecked());
e.putBoolean("C0",radBotC.isChecked());
e.putBoolean("D0",radBotD.isChecked());
e.putBoolean("A1",radBotA.isChecked());
e.putBoolean("B1",radBotB.isChecked());
e.putBoolean("C1",radBotC.isChecked());
e.putBoolean("D1",radBotD.isChecked());
e.putBoolean("A2",radBotA.isChecked());
e.putBoolean("B2",radBotB.isChecked());
e.putBoolean("C2",radBotC.isChecked());
e.putBoolean("D2",radBotD.isChecked());
e.putBoolean("A3",radBotA.isChecked());
e.putBoolean("B3",radBotB.isChecked());
e.putBoolean("C3",radBotC.isChecked());
e.putBoolean("D3",radBotD.isChecked());
public void load(){
SharedPreferences settings = getSharedPreferences("Answers", 0);
boolean answerA0 = settings.getBoolean("A0", false);
boolean answerB0 = settings.getBoolean("B0", false);
boolean answerC0 = settings.getBoolean("C0", false);
boolean answerD0 = settings.getBoolean("D0", false);
boolean answerA1 = settings.getBoolean("A1", false);
boolean answerB1 = settings.getBoolean("B1", false);
boolean answerC1 = settings.getBoolean("C1", false);
boolean answerD1 = settings.getBoolean("D1", false);
boolean answerA2 = settings.getBoolean("A2", false);
boolean answerB2 = settings.getBoolean("B2", false);
boolean answerC2 = settings.getBoolean("C2", false);
boolean answerD2 = settings.getBoolean("D2", false);
boolean answerA3 = settings.getBoolean("A3", false);
boolean answerB3 = settings.getBoolean("B3", false);
boolean answerC3 = settings.getBoolean("C3", false);
boolean answerD3 = settings.getBoolean("D3", false);
However I don't know how to continue. I v' thinking about the following code but it gives me error and where posicion is the "Page Number":
public void Test(){
switch(posicion){
case(0):
if(answerA0==true){
e.putBoolean("A0",radBotA.isChecked());
}
}
}
}
If I understand you correctly, you want to retrieve some data in other activities. In that case the easiest way would be to use SharedPreferences.
After user answers the question (CheckBox's check state is being changed) you should store your information in SharedPreferences like this:
SharedPreferences settings = getSharedPreferences("Answers", 0); // first argument is just a name of your SharedPreferences which you want to use. It's up to you how you will name it, but you have to use the same name later when you want to retrieve data.
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("questionA", radBotA.isChecked()); // first argument is a name of a data that you will later use to retrieve it and the second argument is a value that will be stored
editor.putBoolean("questionB", radBotB.isChecked());
editor.putBoolean("questionC", radBotC.isChecked());
editor.putBoolean("questionD", radBotD.isChecked());
editor.commit(); // Commit the changes
So now you have those information stored in your internal storage. In other activity, you can retrieve this information:
SharedPreferences settings = getSharedPreferences("Answers", 0);
boolean answerA = settings.getBoolean("questionA", false); // The second argument is a default value, if value with name "questionA" will not be found
boolean answerB = settings.getBoolean("questionB", false);
boolean answerC = settings.getBoolean("questionC", false);
boolean answerD = settings.getBoolean("questionD", false);
I'm working on same application and the solution is that you have to store state of Radio button according to your question Number and for each question there is different key, like this:
final RadioButton rdSelection=(RadioButton)findViewById(mradioOptGroup.getCheckedRadioButtonId());
int child_index=mradioOptGroup.indexOfChild(rdSelection);
switch(mid)
{
case 1:
sharedpreferences.putint("",child_index);
break;
case 2:
sharedpreferences.putint("",child_index);
break;
}
and do like this for all your questions on every next question
and on every previous question you have to store state of radio button of mid+1
where mid is your question number
i just solved this problem , now i am able to save the current state of radio button on every next click and on every previous click i get back the radio state,even at the if the user changed the state by going to previous question or any of the question.

Categories

Resources