java - How to get radio button's id and convert to string? -
i working in android studio , trying id of selected radio button , store id in string. possible?
i have tried replacing .gettext() method below .getid() wont let me store string:
radiogroup radiogroup = (radiogroup) findviewbyid(r.id.radiogroup); radiogroup.setoncheckedchangelistener(new radiogroup.oncheckedchangelistener() { @override public void oncheckedchanged(radiogroup radiogroup, int checkedid) { radiobutton checkedradiobutton = (radiobutton) findviewbyid(checkedid); string text = checkedradiobutton.gettext().tostring(); toast.maketext(getapplicationcontext(), text, toast.length_short).show(); } });
getid() returns int - which, primitive types, not have tostring() (or other) method. because, while objects have tostring() method, primitives not objects - lucky you, java provides wrapper classes are objects primitive type. in case of int, corresponding wrapper class called integer:
string text = (integer)checkedradiobutton.getid().tostring(); here, we're explicitly casting int returned getid() integer object, calling tostring() on object.
alternatively, can take advantage of autoboxing let java handle "wrapping" automatically:
integer id = checkedradiobutton.getid(); string text = id.tostring(); note getid() still returning int, because declared id variable integer, java "boxes" return value wrapper class automatically - hence "autoboxing".
you can use static integer.tostring() method:
string text = integer.tostring(checkedradiobutton.getid()) but note that, under hood, same operations being performed here.
Comments
Post a Comment