Updating the value of radio buttons - java

I've been struggling for couple of days with updating the value of a radio button. I've created the radio button group inside a fragment with two buttons and I need to change the value of the radio button according to which one the user has chosen. This seems simple and straight forward. The problem is I have to make the radioButton variable final inside the onClick method and as result I can't change its value and if I establish it outside the class I will not be able to access it form inside the class!
Here is my code
enter code here
// Adding a new consultaion ---------------------
final TextView titleEditText = rootView.findViewById(R.id.titleEditText);
final TextView bodyEditText = rootView.findViewById(R.id.bodyEditText);
final RadioGroup radioGroup = getActivity().findViewById(R.id.radioGroup);
final int radioButtId = radioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = getActivity().findViewById(radioButtId);
final Button sendButt = rootView.findViewById(R.id.sendButt);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio_individual:
radioButton = rootView.findViewById(R.id.radio_individual);
//Toast.makeText(getActivity(), "ind", Toast.LENGTH_SHORT).show();
break;
case R.id.radio_company:
radioButton = rootView.findViewById(R.id.radio_company);
//Toast.makeText(getActivity(), "com", Toast.LENGTH_SHORT).show();
break;
}
}
});
And this is the XML code
enter code here
<RadioButton
android:id="#+id/radio_individual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="فرد"
android:checked="true"
/>
<RadioButton
android:id="#+id/radio_company"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="شركة"
/>
</RadioGroup>

Actually I've got the solution. First there is not need to use the function radioGroup.setOnCheckedChangeListener all I had to do is to declare the two variables radioButtId and radioButton inside the onClick function of the sending button not outside it.
// Adding a new consultation ---------------------
final TextView titleEditText = rootView.findViewById(R.id.titleEditText);
final TextView bodyEditText = rootView.findViewById(R.id.bodyEditText);
final RadioGroup radioGroup = rootView.findViewById(R.id.radioGroup);
final Button sendButt = rootView.findViewById(R.id.sendButt);
// Sending button -------------------
sendButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Check if fields are empty
if (titleEditText.getText().toString().matches("") || bodyEditText.getText().toString().matches("")){
} else {
// Add the consultaion
showPD("Sending teh consulation", getActivity());
// We have to declear the variable of the readio button here!
final int radioButtId = radioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = rootView.findViewById(radioButtId);
ParseObject newCon = new ParseObject("Consultations");
newCon.put("title", titleEditText.getText().toString());
newCon.put("body", bodyEditText.getText().toString());
newCon.put("type", radioButton.getText().toString());
newCon.put("userPointer", ParseUser.getCurrentUser());
// Saving the block
newCon.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// seccess
hidePD();
Toast.makeText(getActivity(), "sent", Toast.LENGTH_SHORT).show(); // We use getActivity() instead of HomeFragment.this because we are dealing with a fragment
} else {
//error
hidePD();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show(); // We use getActivity() instead of HomeFragment.this because we are dealing with a fragment
}
}
});
}
}
});

Related

"onRadioButtonClicked" method not working for radio button implemented by "onCreate" method

I tried to populate RadioGroup's RadioButtons on "onCreateMethod" rather than using XML because my purpose is to get it from some sort of database or other business objects model that works with randomicity. RadioButtons are fine, but nothing happens when I click them otherwise when I created in XML activity file, not a log message neither a test toast. By the way, as I said, I need to create the buttons by code, thanks, is my first steps in Android.
My Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
My Code:
public class ListaAlunosActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = view.getId();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
Buttons are okay!
using onClick for finding selected radio button is not the best solution but because you want to use onClick i will show you how to do it with minimum changes to your code. make these three changes to your code:
public class ListaAlunosActivity extends AppCompatActivity
implements View.OnClickListener {// <------ 1. implement OnClickListener
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setOnClickListener(this);// <---------- 2.add this line
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
#Override
public abstract void onClick (View v){ //<-------- 3. override onClick
boolean checked = ((RadioButton) v).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = v.getId();// your radio buttons have no id thus use title instead of id:
String title = ((RadioButton) v).getText();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
If you look keenly, your onRadioButtonClicked is just a method that is never called. Now what you have to do is make the Activity implement RadioGroup.OnCheckedChangeListener. And in onCheckedChanged method, do the Toast and it will work. Here is the code.
public class ListaAlunosActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alnus);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setId(i);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
listaDeQuestoes.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast toast2 = Toast.makeText(this, "toast working for id "+ checkedId, Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
I did this and it works perfectly
Not completely sure what your code is meant to do, but I would use a setOnCheckedChangeListener rather than onClick.
Something like this
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
final String TAG = "MyActivity"; // not used?
Log.v("On clicked working", "clicado");
// Note checkedId is +1 when accessing the arraylist so needs to be decremented to get a list item
Toast toast2 = Toast.makeText(ListaAlunosActivity.this, "toast working clicked (" + checkedId + ") [" + dataList.get(checkedId - 1) + "]", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
});
The Toast is working and I showed how you can determine which button was clicked and how to access your data array with it, if desired.
The main reason for this, as BAHMAN points out, is that you haven't set any listener. HOWEVER. Setting a listener on the buttons themselves is not a very good idea. It is better to set it on the radio group. And it's better to have your layout elements in your layout file. This makes them easier to modify and understand.
Another thing that is personal preference: I prefer implementing the listener as an anonymous class where it is set. The solutions where the class implements the listener make it harder to read for large classes where it can be annoying to go looking for listeners. I might make an exception if the listener is very complex or if it something that might be used more than once.
I also cleaned up the code a bit. Comments added where I did
Anyway, here's how I would write this code:
Main Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio_button_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Main Activity Code:
public class ListaAlunosActivity extends AppCompatActivity {
// I put your tag at the top of the class so it's more useful
public static final String TAG = "ListaAlunosActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
// You didn't really need an arraylist here for this static content.
// I just made it an array
String[] dataList = {"sup1", "sup2", "sup3"};
// Get this from your layout instead of adding it manually.
// It's a cleaner way to set up the layout that makes the
// code more maintainable
RadioGroup listaDeQuestoes = findViewById(R.id.radio_button_list);
// I changed this to a for each loop because it's a little cleaner
for (String name : dataList){
RadioButton botao = new RadioButton(this);
botao.setText(name);
listaDeQuestoes.addView(botao);
}
// This is the code that will react to the new radio button being selected
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Either way we do it, we need to grab the view to get the name
RadioButton buttonView = group.findViewById(checkedId);
// You can use this code to get the index if you need it
int checkedIndex = group.indexOfChild(buttonView);
// And you can use either of these methods to get the name:
String buttonNameFromView = buttonView.getText().toString();
String buttonNameFromDataSource = dataList[checkedIndex];
String output = "Button with Id: " + checkedId + " and Name: " + buttonNameFromView + " was clicked";
Log.v(TAG, output);
Toast toast = Toast.makeText(ListaAlunosActivity.this, output, Toast.LENGTH_LONG);
// I set gravity to just center here. This is the same as center_vertical | center_horizontal. Personally, I wouldn't set it at all.
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
}

Android Studio getting values from radio button, and using it elsewhere

I've got the code below, to use a radio button and get the value and return it as a string for a function. Hoping that I could use it elsewhere in the main program. However, it doesn't. it would allow me to use the variable btn and if, I did the atl-enter suggestion by declaring it to final string [], it'll return null. Most online tutorial and stackoverflow previous question only includes toasting text from whichever button chosen, within onCheckedChanged.
public String listeneronbutton() {
String btn;
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedID) {
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(checkedID);
Toast.makeText(getApplicationContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
btn = String.valueOf(radioButton.getText()); //(error here: variable 'btn' is accessed from within inner class, needs to be declared final)
}
});
return btn;
}
How do I get the function listeneronbutton() properly being able to get and return btn value?
Change your method like this :
public String listeneronbutton() {
String btn;
RadioGroup radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(checkedID);
Toast.makeText(getApplicationContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
btn = String.valueOf(radioButton.getText());
return btn;
}
you cannot have a method which adds the OnCheckedChangeListener and gets the String, at the same time (because separation of duties & the one method only should run once, the other method more often). alike this you can add method instanceRadioGroup() to onCreate() or onCreateView() and then get the current value with method getButtonText().
also, the variable int checkedId is already being passed into the scope, so one can use that.
/** the handle for the {#link RadioGroup} */
private RadioGroup mRadioGroup = null;
/** this field holds the button's text */
private String mButtonText = null;
/** the setter for the field */
protected void setButtonText(#Nullable String value) {
this.mButtonText = value;
}
/** the getter for the field */
protected String getButtonText() {
return this.mButtonText;
}
/** it sets mButtonText by checkedId */
protected void updateButtonText(int checkedId) {
if ((checkedId == -1)) {
this.setButtonText(null);
} else {
RadioButton radioButton = (RadioButton) this.mRadioGroup.findViewById(checkedId);
this.setButtonText(radioButton.getText());
}
}
/** this code should only run once, onCreate() or onCreateView() */
protected void instanceRadioGroup() {
/* setting the handle for the {#link RadioGroup} */
this.mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
/* update the field with the text of the default selection */
int checkedId = this.mRadioGroup.getCheckedRadioButtonId();
this.updateButtonText(checkedId);
/* and also add an onCheckedChange listener */
this.mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
updateButtonText(checkedId);
}
});
}
Declare String btn as field. Thus you can access anywhere inside class.
public class Test{
String btn;
public String listeneronbutton(){
return btn;
}
}

One button for 2 different actions

I have "send" Button inside dialogFragment that onClick event push new data to firebase under key value.
I want this button to be also like an "update" button when the user click on particular button. the data will update in firebase under the same key value as before.
This is the send button onClick method:
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//some code .....//
DatabaseReference newPost = mDatabase.push();
str_key = newPost.getKey();
trempData = new TrempData(str_key, str_uid, str_name, str_phone, str_from, str_to, str_date, str_time, str_extra, str_timestamp);
newPost.setValue(trempData);
Toast.makeText(getActivity(), "Tremp Added", Toast.LENGTH_SHORT).show();
dismiss();
}
});
Any suggestions?
More important than the implementation is the way you think it can be done. So, the basic approach in these cases is to use a boolean variable.
Why? Because it can be used to indicate if the button is in a particular state or not.
So, you can do something like this.
boolean b=false;
//set your button in the initial state you want(submit in your case)
//In onClick() method
if(!b){ //button in submit state
b=true;
//do submit stuff
send_btn.setText("update");
}
else{ //button in update state
b=false;
//do update stuff
send_btn.setText("submit");
}
In this case, true value of b indicates that the button is in "update" state.
This is an Example :
private final int BUTTON_UPDATE = 1;
private final int BUTTON_SEND = 2;
private int buttonStatus = 0;
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(buttonStatus)
{
case BUTTON_UPDATE: { // your update code here}
case BUTTON_SEND : { // your send code here
}
the buttonStatus will control what operation the button will do.
Put a boolean in sharedPrefrences and keep to false initially when
user sends data to firebase update boolean to true.
in onClick check if the value is true or false using if else and
execute code accordingly
You can use the tag of the view for this and update the state as your need
Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (button.getTag().equals("send")) {
// push the value to firebase
// set the tag to update and the text
button.setTag("update");
button.setText("update");
}else if (button.getTag().equals("update")){
// update the value in firebase
}
}
});
xml
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="send"
android:text="send" />

I am not allowed to pass a string from resource file within a switch case [Android]

I have few buttons and I have the following click listener for the same:
private View.OnClickListener onclick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.home:
break;
case R.id.contact:
break;
case R.id.terms:
break;
case R.id.touch:
show(R.string.about_us); //Error here
break;
}
}
};
On each button click I display the same popup, only the text differs. I have text in strings.xml file
below is my dialog function:
public void show(String message){
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.terms);
//dialog.setTitle("Terms & Conditions");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText(message);
text.setTypeface(helv_light);
ImageButton dialogButton = (ImageButton) dialog.findViewById(R.id.button1);
// dialogButton.setTypeface(helv_light);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
in case R.id.touch: My IDE complains with the following message:
show(java.lang.string) cannot be applied to (int).
If I replace show(R.string.about_us); with show(""+R.string.about_us); The error goes away, what do I miss here?
Use getResources().getString for getting string from strings.xml :
show(v.getContext().getResources().getString(R.string.about_us));
R.string.about_us is an int value, is not a string. To keep both you can overload show, providing the integer parameter, and call
public void show(final int messageId) {
sendMessage(getResources().getString(messageId));
}
The R.string.* values are ints. You need to use getResources().getString(R.string.str_id) to get the actual string value.

get/use radio button value android

I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...

Categories