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;
}
}
Related
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
}
}
});
}
}
});
I'm using two buttons with the same id in two different layouts in my app where when the first one is clicked, the app loads the 2nd layout and when the button with the same id in the 2nd layout gets clicked, it loads the first layout file. However, my issue is that this toggling happens only once and after that the button doesn't do anything. Do you have any idea on how i can call these onClickListeners whenever each button is clicked until the user leaves that activity?
CardViewActivity.java:
public class CardViewActivity extends AppCompatActivity {
private ImageView cardArtImageView;
private TextView leaderSkillDescText;
private TextView superAttackTitleText;
private TextView superAttackDescText;
private TextView passiveSkillTitleText;
private TextView passiveSkillDescText;
private TextView hpText;
private TextView attText;
private TextView defText;
private TextView costText;
private Button arrowButton;
private int selectedItemPosition;
private boolean isBtnClicked = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cardview_refined);
// Retrieving the data sent over from MainActivity
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle != null) {
selectedItemPosition = bundle.getInt("Card Index");
}
//Toast.makeText(this, "WIDTH: " + SCREEN_WIDTH, Toast.LENGTH_SHORT).show();
// Initializing our views
cardArtImageView = findViewById(R.id.cardArtImageView);
viewDefinitions(false);
setSelectedViewsInit();
initCardViewData(selectedItemPosition);
arrowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isBtnClicked = !isBtnClicked;
if (isBtnClicked) {
setContentView(R.layout.cardview_expand_details);
viewDefinitions(true);
initCardViewData(selectedItemPosition);
setSelectedViewsInit();
Log.d("BTN", "Btn Clicked 1st time");
arrowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.cardview_refined);
cardArtImageView = findViewById(R.id.cardArtImageView);
viewDefinitions(false);
initCardViewData(selectedItemPosition);
setSelectedViewsInit();
isBtnClicked = !isBtnClicked;
Log.d("BTN", "Btn Clicked 2nd time");
}
});
}
}
});
}
/**
* Sets the required textViews as selected to allow automatic scrolling
*/
private void setSelectedViewsInit() {
leaderSkillDescText.setSelected(true);
superAttackTitleText.setSelected(true);
superAttackDescText.setSelected(true);
if (passiveSkillTitleText != null && passiveSkillDescText != null) {
passiveSkillTitleText.setSelected(true);
passiveSkillDescText.setSelected(true);
}
}
/**
* Adds the views's definitions
*
* #param initPassiveInfo used to decide whether or not the passiveSkillDesc & ..Title != null
* so that they can be defined
*/
private void viewDefinitions(boolean initPassiveInfo) {
leaderSkillDescText = findViewById(R.id.leaderSkillDesc);
superAttackTitleText = findViewById(R.id.superAttackTitle);
superAttackDescText = findViewById(R.id.superAttackDesc);
if (initPassiveInfo) {
passiveSkillTitleText = findViewById(R.id.passiveSkillTitle);
passiveSkillDescText = findViewById(R.id.passiveSkillDesc);
} else {
Log.d("Definitions", "Passive info == null");
}
hpText = findViewById(R.id.HP);
attText = findViewById(R.id.ATT);
defText = findViewById(R.id.DEF);
costText = findViewById(R.id.COST);
arrowButton = findViewById(R.id.arrowButton);
}
/**
* Initialize the cardViewActivity's views with the data from the CardInfoDatabase.java class
*
* #param selectedItemPosition Used to initialize this activity's views if the intent was called from the MainScreen Fragment
*/
private void initCardViewData(int selectedItemPosition) {
if (cardArtImageView != null) {
cardArtImageView.setImageResource(CardInfoDatabase.cardArts[selectedItemPosition]);
}
leaderSkillDescText.setText(CardInfoDatabase.leaderSkills[selectedItemPosition]);
superAttackTitleText.setText(CardInfoDatabase.superAttacksName[selectedItemPosition]);
superAttackDescText.setText(CardInfoDatabase.superAttacksDesc[selectedItemPosition]);
if (passiveSkillTitleText != null && passiveSkillDescText != null) {
passiveSkillTitleText.setText(CardInfoDatabase.passiveSkillsName[selectedItemPosition]);
passiveSkillDescText.setText(CardInfoDatabase.passiveSkillsDesc[selectedItemPosition]);
}
hpText.setText(CardInfoDatabase.hp[selectedItemPosition].toString());
attText.setText(CardInfoDatabase.att[selectedItemPosition].toString());
defText.setText(CardInfoDatabase.def[selectedItemPosition].toString());
costText.setText(CardInfoDatabase.cost[selectedItemPosition].toString());
}
}
To avoid this issue, you need to make sure that the OnClickListener you assign to the button always sets the OnClickListener for the button in the "new" layout.
I haven't tested this, but it seems like it should work in theory. Try defining the listener as a private member of your class, then setting it in your onCreate, like arrowButton.setOnClickListener(arrowClickListener);:
private void arrowClickListener = new View.OnClickListener(){
#Override
public void onClick(View view) {
// clicked buttton -- pick layout based on button "state"
int resId = isBtnClicked ? R.layout.cardview_expand_details : R.layout.cardview_refined;
// set the contentview with the layout we determined earlier
setContentView(resId);
// If we're in the "normal" view, find the card art view and set our field to it
if (!isBtnClicked){
cardArtImageView = findViewById(R.id.cardArtImageView);
}
// do other initialization stuff
viewDefinitions(isBtnClicked);
initCardViewData(selectedItemPosition);
setSelectedViewsInit();
// set our new arrow button click listener to this listener
arrowButton.setOnClickListener(arrowClickListener);
// toggle button flag
isBtnClicked = !isBtnClicked;
}
}
Sorry if I got some of the logic wrong -- the key in this case is to set the click listener "recursively", in a manner of speaking, which ensures that a listener gets set after every click.
Here is my code:
public class TipCalculator extends Activity implements RadioGroup.OnCheckedChangeListener {
EditText ba= null;
TextView ta= null;
TextView td= null;
RadioButton t10= null;
RadioButton t15= null;
RadioButton t20= null;
RadioGroup rg= null;
DecimalFormat df=new DecimalFormat("$####.00");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tip_calculator);
ba=(EditText)findViewById(R.id.bill_amount);
ta=(TextView)findViewById(R.id.tip_amount);
td=(EditText)findViewById(R.id.Total_Dollars);
t10=(RadioButton)findViewById(R.id.ten);
t15=(RadioButton)findViewById(R.id.fifteen);
t20=(RadioButton)findViewById(R.id.twenty);
rg=(RadioGroup)findViewById(R.id.tip_choices);
rg.setOnCheckedChangeListener(this);
}
public void onCheckedChanged(RadioGroup rg, int i) {
if(i==t10.getId())
ta.setText(df.format(Double.parseDouble(ba.getText().toString())*.10));
if(i==t15.getId())
ta.setText(df.format(Double.parseDouble(ba.getText().toString())*.15));
if(i==t20.getId())
ta.setText(df.format(Double.parseDouble(ba.getText().toString())*.20));
if(i==t10.getId())
td.setText(( ba.getText().toString()+(ta.getText().toString())));
if(i==t15.getId())
td.setText("$");
if(i==t20.getId())
td.setText ( df.format(Double.parseDouble(ta.getText().toString()) + Double.parseDouble(ba.getText().toString())));
}
}
The part of the code that I'm getting my errors from is in the very last part. I am trying to set variable "td" to equal the two variables "ta" and "ba" but I either get an error or it concatenates the values of the variables instead please help!
thanks in advance!
td.setText(Double.toString(Double.valueOf(ba.getText().toString()) + Double.valueOf(ta.getText().toString())));
I am using an Adapter to generate buttons in a GridView.
Using an OnClickListener, whenever I click a button from the GridView, it is possible to get the String of the button in a variable. However, I want to click a button, store its text in a variable, then click a different button, store its text in another variable so later I can compare the two texts. How could I do that?
gI'm using OnClickListener, therefore my previous implementation for one button was the following:
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText.toString();
With this approach, I can only get and store text from first button clicked, unless I store all the values in an array.
Ok so from what I can understand, you want to compare the strings of the two items in a grid view. If this is what you want, heres how I would do it(just a psuedocode):
String mValue1, mValue2;
boolean isOneClicked = false;
onItemClickedListener(item, position){
if(!isOneClicked){
mValue1 = item.stringValue;
isOneClicked = true;
}
else{
mValue2 = item.stringValue;
//do whatever you want here
//Reset when done
mValue1 = "";
mValue2 = "";
isOneClicked = false;
}
}
Please you can share your code to turn the things more comprehensible? Edit your question please... Anyways:
MainActivity.java
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private String butString, butString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString = (String) button1.getText();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString2 = (String) button1.getText();
}
});
}
}
After that you can compare the two strings.
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...