Check RadioGroup checked or not and get value to static int - android

GOAL 1: When click the button, if there isn't any radiobutton checked, it will warning user by Toast; if a radiobutton checked, it will take user to new activity (or do smt up on you).
First
public class hanh1_2 extends Activity{
public static int ButID;
#Override
Second, set the button action:
final Button ok2 = (Button) findViewById(R.id.ok2);
ok2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Set int of ButID = checkedradiobuttonID
//If ButID = -1 --> there isn't bt checked
int ButID = tieng.getCheckedRadioButtonId();
if (ButID == -1){
Toast.makeText(hanh1_2.this, "Check a butt pls", Toast.LENGTH_SHORT).show();
}
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
startActivity(intent2);
}
}
});
Meaningless to advanced, but may helpful for some newbie like me :)

Have a look at the Form stuff tutorial on the Android dev site. You can supply an OnClickListener to all RadioButtons and keep track of the one selected (if any).
private OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
};
Alternatively, you can potentially use the RadioGroup's getCheckedRadioButtonId() method.
As illustrated in one of the other answers: pass the int value as an extra to the Intent you use to launch your second Activity:
// In first activity
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putInt("selected_index", selectedIndex);
startActivity(i);
// In second activity
int selectedIndex = getIntent().getExtras().getInt("selected_index");

Take all your RadioButton and RadioGroup to class level.
initialize them inside onCreate()
now inside onClick() get id of checked RadioButton and compare like this:
public void onClick(View v) {
int checked = tieng.getCheckedRadioButtonId(); // tieng is your RadioGroup
switch(checked)
{
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "First is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Second is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Third is selected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(hanh1_2.this, "pleas check any button", Toast.LENGTH_SHORT).show();
break;
}
}

put extra along with intent :
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
intent2.putInt(Index1, index1);
startActivity(intent2);
}
now inside second activity onCreate() read this extra :
{
int Index1 = getIntent().getExtras().getInt("Index1");
//do stuff here
}

Related

Custom listview using button OnClickListener

i have created a custom listview with an ImageView, two TextViews and a Button
now i am facing issue when i try to set onClicklistner to that button
i want different method to be done for every button
here is my code for customlistview class
i have used temporary onclicklistner for that button which shows the toast "Bought"
what i want to do is that after clicking the button i have to return the price of the food.
class CustomListView extends ArrayAdapter {
public CustomListView(Context context, String[] resource) {
super(context,R.layout.custom_view , resource);
}
Toast toast= null;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater MyInflater = LayoutInflater.from(getContext());
View CustomView = MyInflater.inflate(R.layout.custom_view, parent, false);
String SingleItem= (String) getItem(position);
final TextView text =(TextView)CustomView.findViewById(R.id.Itemname);
final ImageView Image= (ImageView)CustomView.findViewById(R.id.icon);
final TextView Pricetag= (TextView)CustomView.findViewById(R.id.PriceTextView);
text.setText(SingleItem);
switch (SingleItem)
{
case "Chicken":
Image.setImageResource(R.drawable.desert1);
Pricetag.setText("Rs 300");
break;
case "soap":
Image.setImageResource(R.drawable.desert2);
Pricetag.setText("Rs 300");
break;
case "Fish":
Image.setImageResource(R.drawable.fish);
Pricetag.setText("Rs 100");
break;
default:
Image.setImageResource(R.drawable.myimage);
Pricetag.setText("Rs 0.00");
break;
}
final Button Buybutton= (Button)CustomView.findViewById(R.id.BuyButton);
toast = Toast.makeText(getContext(), "", Toast.LENGTH_LONG);
Buybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toast.setText("Bought");
toast.show();
}
});
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toast.setText(text.getText().toString());
toast.show();
}
});
return CustomView;
}
}
For the record, there should be a better way to do this, using food-id or other approach to prevent this, but based on your request, here we go:
1- in getView() when you get a reference on the button i.e:
final Button Buybutton= (Button)CustomView.findViewById(R.id.BuyButton);
do a one more step:
Buybutton.setTag(10);
10 here could be any other number, and you need to find a way to determine which number to use for each button, also it could be a string , ex value of SingleItem
Buybutton.setTag(SingleItem);
2- at onClick() you need to find out what the value assign to the view (button) and based on this value call the proper method:
#Override
public void onClick(View v) {
if (v.getTag().toString().equals("xxxxx")){
doSomething();
}else if (v.getTag().toString().equals("yyyy")){
doAnotherThing();
}else if (v.getTag().toString().equals("zzzzz")){
doSomething12();
}
//and so on...
}
this approach used String as value in setTag() and getTag()
if you use integers, just replace the condition as belwo:
if (Integer.parseInt(v.getTag().toString()) == 10)
EDIT:
If i understand well, then you need to:
Buybutton.setTag(SingleItem);
and onClick():
#Override
public void onClick(View v) {
showPriceTag(v.getTag().toString());
}
add method showPriceTag():
public void showPriceTag(String type){
switch (type)
{
case "Chicken":
//set the price tag data ...
break;
case "soap":
//set the price tag data ...
break;
case "Fish":
//set the price tag data ...
break;
default:
//set the default price tag data ...
break;
}
}

Android Intent won't pass value from Switch

I have a Switch button, from which I want to pass different values (1 or 2) to next activity for calculations. But I always get 0. Any help?
Switch mySwitch = (Switch) findViewById(R.id.edit_home);
// set the switch to ON
mySwitch.setChecked(true);
// attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
double input5 = 2;
Intent intentx=new Intent(MainActivity.this,Main2Activity.class);
intentx.putExtra("IFValue",input5);
startActivity(intentx);
Toast.makeText(getApplicationContext(), "Home field is important advantage",
Toast.LENGTH_SHORT).show();
} else {
double input5 = 1;
Intent intenty=new Intent(MainActivity.this,Main2Activity.class);
intenty.putExtra("IFValue",input5);
startActivity(intentx);
Toast.makeText(getApplicationContext(),
"Home field is not advantage", Toast.LENGTH_SHORT).show();
}
}
});
In next activity:
Bundle bundle = getIntent().getExtras();
double input5 = bundle.getDouble("IFValue");
EDITED: I want to send values (input5) to the next activity, but if I add startActivity(intentx) inside of switch; then goes there imediately and not when I press next Button (buttonForward) as I want to.
Rest of the code:
Switch mySwitch = (Switch) findViewById(R.id.edit_home);
// set the switch to ON
mySwitch.setChecked(true);
// attach a listener to check for changes in state
mySwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked == true) {
double input5 = 2;
Intent intentx=new Intent(MainActivity.this,Main2Activity.class);
intentx.putExtra("IFValue",input5);
startActivity(intentx);
Toast.makeText(getApplicationContext(), "Home field is important advantage",
Toast.LENGTH_SHORT).show();
} else {
double input5 = 1;
Intent intenty=new Intent(MainActivity.this,Main2Activity.class);
intenty.putExtra("IFValue",input5);
startActivity(intenty);
Toast.makeText(getApplicationContext(),
"Home field is not advantage", Toast.LENGTH_SHORT).show();
}
}
});
Button buttonForward = (Button) findViewById(R.id.buttonToMain2);
buttonForward.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
EditText edit_team = (EditText) findViewById(R.id.edit_team);
EditText edit_form = (EditText) findViewById(R.id.edit_form);
EditText edit_import = (EditText) findViewById(R.id.edit_import);
String ekipa1 = edit_team.getText().toString();
final double input2 = Double.valueOf(qualityControl.getProgress());
final double input3 = Double.valueOf(edit_form.getText().toString());
final double input4 = Double.valueOf(ratingBar.getRating());
final double input6 = Double.valueOf(edit_import.getText().toString());
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("Value",input2);
intent.putExtra("Value1",input3);
intent.putExtra("Value2",input4);
intent.putExtra("Value4",input6);
intent.putExtra("team1", ekipa1);
startActivity(intent);
}
});
You are creating a local instance of the Intent (intentx & intenty) inside the listener (I do not see you calling startActivity() inside the listener). The passed Extras only apply to the local copy not to the one you are using outside the listener with startActivity().
Update 1
Character case matters when using Extra keys:
You are using intentx.putExtra("IFvalue",input5);
while in the next Activity you are using double input5 = bundle.getDouble("IFValue"); which is a different key.
Update 2
I want to send values (input5) to the next activity, but if I add
startActivity(intentx) inside of switch; then goes there imediately
and not when I press next Button (buttonForward) as I want to.
Then, you will need to have only one Intent instance in the whole Activity (define it before onCreate() and then do not start the Activity from the switch listener, but add the Extra for the single Intent instance:
Intent intent = new Intent(MainActivity.this,Main2Activity.class); // Class level variable
then change the following in the switch listener:
// Intent intentx=new Intent(MainActivity.this,Main2Activity.class); remove this
intent.putExtra("IFValue",input5);
and in the buttonForward click listener:
//Intent intent=new Intent(MainActivity.this,Main2Activity.class); remove this
intent.putExtra("Value",input2);
intent.putExtra("Value1",input3);
intent.putExtra("Value2",input4);
intent.putExtra("Value4",input6);
intent.putExtra("team1", ekipa1);
startActivity(intent);

Android Buttons wont activate

I know this has been asked a million times but none have led me to solving my problem. The onclicklistener will not activate the code for any of the buttons. Here are the different sections that apply to the five buttons.
Button btnGuysMax;
Button btnGuysMedium;
Button btnEven;
Button btnGirlsMedium;
Button btnGirlsMax;
....
private void init()
{
datasource = new BarsDataSource(this);
datasource.open();
Intent intent = getIntent();
long id = intent.getLongExtra("bar_id",0);
bar = datasource.getBarById(id);
title = (TextView)findViewById(R.id.title);
btnGuysMax = (Button)findViewById(R.id.btnGuysMax);
btnGuysMedium = (Button)findViewById(R.id.btnGuysMedium);
btnEven = (Button)findViewById(R.id.btnEven);
btnGirlsMedium = (Button)findViewById(R.id.btnGirlsMedium);
btnGirlsMax = (Button)findViewById(R.id.btnGirlsMax);
......
btnGuysMax.setOnClickListener(this);
btnGuysMedium.setOnClickListener(this);
btnEven.setOnClickListener(this);
btnGirlsMedium.setOnClickListener(this);
btnGirlsMax.setOnClickListener(this);
.....
#Override
public void onClick(View view)
{
//resetButtons();
switch (view.getId()) {
case R.id.btnGuysMax:
//bar.setSexRatio(-2);
//btnGuysMax.setBackgroundColor(guysMaxColor);
Toast.makeText(this,"Max clicked!",Toast.LENGTH_LONG);
break;
case R.id.btnGuysMedium:
bar.setSexRatio(-1);
Toast.makeText(this,"Medium clicked!",Toast.LENGTH_LONG);
//btnGuysMedium.setBackgroundColor(guysMediumColor);
break;
case R.id.btnEven:
bar.setSexRatio(0);
//Toast.makeText(this,"Medium clicked!",Toast.LENGTH_LONG);
break;
case R.id.btnGirlsMedium:
bar.setSexRatio(1);
//btnGirlsMedium.setBackgroundColor(girlsMediumColor);
break;
case R.id.btnGirlsMax:
bar.setSexRatio(2);
break;
.....
To display a toast you need to call show method.
Try:
Toast.makeText(this,"message",Toast.LENGTH_LONG).show();
try doing:
#Override
public void onClickListener(View view)
{
instead of:
#Override
public void onClick(View view)
{

OnClickListener in a while loop on custom objects

I'm setting up a CardView layout (with the libary) but I've got a problem.
I can setup a onClickListener (which works) in this way:
mCardView = (CardUI) getView().findViewById(R.id.cardsview);
mCardView.setSwipeable(true);
MyCard b = new MyCard("Hi", "Hi", 15);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(v.toString());
Toast.makeText(getActivity(),"werkt",Toast.LENGTH_LONG).show();
}
});
mCardView.addCard(b);
But when I try to do it in a loop I can't seem to get the ID of the cards.
My cards do have a unique ID (just a int as ID).
I'm adding them like this:
int id = 0;
while(!c.isAfterLast()){
String description = "";
System.out.println("Opmerking: " + c.getString(3));
if(!c.getString(3).equals("")){
description = "Opmerkingen: " + c.getString(3);
}
if(recreate){
MyCard a = new MyCard(c.getString(2)+" "+c.getString(1), description, id);
cards.add(a);
mCardView.addCard(a);
a.setOnClickListener(new OnClickListener());
}
c.moveToNext();
id++;
}
And the onClickListener is this:
private class OnClickListener implements View.OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()){
case 1:
Toast.makeText(getActivity(), "werkt", Toast.LENGTH_LONG).show();
break;
default: Toast.makeText(getActivity(), "werkt niet", Toast.LENGTH_LONG).show(); break;
}
}
}
But everytime when I click one which has a onClickListener of the while loop I get 'werkt niet' which is the default item of the switch.
The card ID is a int in the MyCard object.
If anyone could help me it would be greatly appreciated.
Edit: The MyCard object is a object which needs this libary: http://nadavfima.com/cardsui-view-library/
That is because your view.getId() is never equals 1. Try adding
System.out.println("view.getId() -->> "+view.getId());
inside the default case..
You will get your problem then and there...

Multiple OnClickListeners Android

I have 10 buttons set up which are the answers to ten questions. When a certain button is clicked, I have a switch statement set up in my onClick method shown below. My question is what is the best way to set up the OnClickListeners for all the buttons seeing that I need to pass 2 arrays to the onClick method in order to tell if it is correct or not? Also, I need to return and integer value. Thanks
public void onClick(View v, int[] qaarray, int questionorder) {
int x=0;
switch(v.getId())
{
case R.id.imageButton0:
if(qaarray[0] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton1:
if(qaarray[1] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton2:
if(qaarray[2] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton3:
if(qaarray[3] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton4:
if(qaarray[4] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton5:
if(qaarray[5] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton6:
if(qaarray[6] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton7:
if(qaarray[7] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton8:
if(qaarray[8] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton9:
if(qaarray[9] == questionorder){
//correct
}else{
//incorrect
}
break;
default:
throw new RuntimeException("Unknown button ID");
}
}
The OnClickListener only gives you one parameter, which is the View:
void onClick(View v);
But you don't have to pass the questions and 'order' to the method to have what you want. One of the technique you can use is the setTag() method of View:
int[] button = new int[] { R.id.imageButton1, R.id.imageButton2.... };
private class AnswerPair{
public int questionOrder;
public int answer;
}
public void onCreate(Bundle bundle){
for(int i=0; i<NO_OF_BUTTON; i++){
AnswerPair ans = new AnswerPair();
ans.questionOrder = i;
ans.answer = 0; // SET this
getViewById(button[i]).setTag(ans);
getViewById(button[i]).setOnClickListener(this);
}
}
public void onClick(View v){
if (v.getTag() == null) return;
try{
AnswerPair answer = (ans)v.getTag();
// Check answer == question order? index?
}catch(exception e) return;
}
You can implement as many OnClickListeners as you want and assign different listeners for each button.
public void onCreate(Bundle bundle){
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.myButton)
b.setOnClickListener(new MyListener());
}
private class MyListener implements OnClickListener {
#Override
public void onClick(View v) {
// Your code here
}
}
i think a lot of people know this already, but there's a shortcut you can use instead of having different instances of onClickListeners and assigning them in code using setOnClickListener(x).
In your button XML, give it the android:onClick property, and assign it a string you like, for example,
android:onClick="clickOne"
In the activity the sets this xml as its content view, create a method named clickOne with a View parameter.
public void clickOne(View view)
Whatever you place on this method will be executed when you click the button.

Categories

Resources