Android - Radiobutton click event to go to new activity - java

I would like to do something like a small selection form.
I would like to do a click event where if I select one of the first radiogroup and another one of the second it takes me to a new activity.
I got two radiogroups with two radiobuttons inside each.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/physic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="physic"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/math"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="math"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/theories"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="theories"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/problems_solving"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="problem solving"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
I declared my buttons and tried to use onRadioButtonClicked like below:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.math:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showFirstWord("math problem resolution");
break;
case R.id.theories:
if (checked)
showSecondWord("math theories");
break;
}
break;
case R.id.physic:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showThirdWord("physic problem solving");
break;
case R.id.theories:
if (checked)
showFourthWord("physic theories");
break;
}
break;
}
}
I want the strings in the functions to appear in a text view in the other activities like below:
private void showFirstWord (String text) {
Intent first_word = new Intent(this, FirstActivity.class);
first_word.putExtra("key", text);
startActivity(first_word);
}
private void showSecondWord (String text) {
Intent second_word = new Intent(this, SecondActivity.class);
second_word.putExtra("key", text);
startActivity(second_word);
}
private void showThirdWord (String text) {
Intent third_word = new Intent(this, ThirdActivity.class);
third_word.putExtra("key", text);
startActivity(third_word);
}
private void showFourthWord (String text) {
Intent fourth_word = new Intent(this, FourthActivity.class);
fourth_word.putExtra("key", text);
startActivity(fourth_word);
}
I tried to follow this page from Android developers but I'm still not sure what to do with it: https://stuff.mit.edu/afs/sipb/project/android/docs/guide/topics/ui/controls/radiobutton.html
My method doesn't seem to be correct ass I can't get the strings to appear in the other activities. Is my reasonning ok for now or should I study another method?
Thanks :)

You can simplified your code onRadioButtonClicked just create first a String variable called subjectSelected.
then:
private String subjectSelected = "";
public void onRadioButtonClicked(View view) {
RadioButton radioButton = (RadioButton) view;
switch(view.getId()) {
case R.id.math:
subjectSelected = radioButton.getText().toString();
break;
case R.id.physic:
subjectSelected = radioButton.getText().toString();
break;
case R.id.problems_solving:
if (subjectSelected.equals("math")) {
showFirstWord ("math problem resolution");
} else if (subjectSelected.equals("physic")) {
showThirdWord("physic problem solving");
}
break;
case R.id.theories:
if (subjectSelected.equals("math")) {
showSecondWord("math theories");
} else if (subjectSelected.equals("physic")) {
showFourthWord("physic theories");
}
break;
}
}
and to display the text you pass to another activity. Use a Bundle to get the value of your key.
e.g.:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Bundle bundle = getIntent().getExtras();
String key = bundle.getString("key");
TextView textView = (TextView) findViewById(R.id.textView1); // Replace the textView1 with the id you set to your textview.
textView.setText(key);
}
}
You can copy the codes of your FirstActivity and paste to your SecondActivity, ThirdActivity and FourthActivity to get the key.

String str; // store the text corresponding to the RadioButton which is clicked
switch(view.getId()) {
case R.id.radioButton1:
if (checked)
str = "button1Text";
break;
case R.id.radioButton2:
if (checked)
str = "button2Text";
break;
case R.id.radioButton3:
if (checked)
str = "button3Text";
break;
}
Intent intent = new Intent(this, WinderDTActivity.class);
intent.putExtra("radioChosen", str); // pass "str" to the next Activity

Related

A variable holds an unexpected value

I'm building a module for checking an answer in my Android java app and it doesn't work. While debugging it shows that the variable holds a value that is completely unexpected for it to hold. Could please someone explain what the problem might be? Here is the module:
private void QuizOperations() {
Toast.makeText(QuizActivity.this,"quizOperation", Toast.LENGTH_SHORT).show();
answered = true; // when the question is already answered Set bool to true
RadioButton rbSelected = findViewById(rbGroup.getCheckedRadioButtonId());
int indexofchild =rbGroup.indexOfChild(rbSelected) +1;
int answerNr = indexofchild +1;
checkSolution(answerNr,rbSelected);// method checks if the answer that is selected by the user corresponds to the answer in the database
}
The intended way was rbselected getting the index of the RadioButton pressed by the user, and than answerNr gets the index of this button as int. Than it passes in to the checksolution() function which checks if the AnswerNr corresponds to the right answer in the database. However, while debugging answerNr holds the value of 5 whichever button I press.
Debug screenshot
Let me know if any additional code needed. Thanks a lot
Here is a very minimalistic example on how to detect the view is being pressed, set/get id from tag.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#333333">
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton1"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton2"/>
<RadioButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/radioButton3"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private String[] answers = {
"January",
"February",
"March",
};
private RadioButton rb1, rb2, rb3;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rb1 = findViewById(R.id.radioButton1);
rb2 = findViewById(R.id.radioButton2);
rb3 = findViewById(R.id.radioButton3);
rb1.setTag("0");
rb2.setTag("1");
rb3.setTag("2");
rb1.setOnClickListener(this);
rb2.setOnClickListener(this);
rb3.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
final int index = Integer.parseInt((String)view.getTag());
switch(view.getId()) {
case R.id.radioButton1:
rb2.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton2:
rb1.setChecked(false);
rb3.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
case R.id.radioButton3:
rb1.setChecked(false);
rb2.setChecked(false);
Toast.makeText(MainActivity.this, answers[index], Toast.LENGTH_SHORT).show();
break;
}
}
}

Store checkbox value to Firebase Database

I'm making an app and I need to register user. I also have two checkboxes where the user selects gender (male or female). I know that checkbox understand boolean values true or false, but I'm wondering how to do that with firebase.
This is exactly what I need to do:
image
Here what I've done:
private void SignUp(final String firstName, final String lastName, final String email, final String password, final String checkMale, final String checkFemale) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
assert user != null;
String userId =user.getUid();
reference = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("id", userId);
hashMap.put("firstName", firstName);
hashMap.put("lastName", lastName);
hashMap.put("email", email.toLowerCase());
if(male.isChecked() && female.isChecked()) {
hashMap.put("male", checkMale);
hashMap.put("female", checkFemale);
}
reference.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
pd.dismiss();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Toast.makeText(RegisterActivity.this, "User Registered successfully", Toast.LENGTH_SHORT).show();
}
}
});
} else {
pd.dismiss();
Toast.makeText(RegisterActivity.this, "You can't register with this email or password", Toast.LENGTH_SHORT).show();
}
}
});
}
Any help is appreciated.
You can use Radio Buttons instead of checkbox.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/malleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/femaleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
And in code you can check which is selected.
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.maleButton:
if (checked)
hashMap.put("male", true);
break;
case R.id.femaleButton:
if (checked)
hashMap.put("male", false);
break;
}
}
Also you do not need to store 2 variables in firebase male and female if users can choose only one. In other case(if users can choose both) store 2 variables and remove radiogroup so users can choose both.
I think in gender both can't checked at once and you kept && condition, so I would't work here:
if(male.isChecked() && female.isChecked()) {
hashMap.put("male", checkMale);
hashMap.put("female", checkFemale);
}
First of all do not need to save both value male & female. Just keep once key "gender" and specify one string or number e.g. 1 or "m" for male & 2 or "f" for female and save it along with all value.
Here you can use RadioButton inside RadioGroup 'gender' instead of only RadioButtons.
For your reference:
if(male.isChecked())
hashMap.put("gender", "m");
else
hashMap.put("gender", "f");
Use Radio Buttons in place of the checkbox.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rdgGender"
android:orientation="vertical">
<RadioButton android:id="#+id/rbMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/rbFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
get RadioGroup id
RadioGroup rdgGender = findViewbyId(R.id.rdgGender);
on submit button click
public void onSubmitClick() {
boolean checkedId = rdgGender.getCheckedRadioButtonId();
switch(checkedId) {
case R.id.rbMale:
hashMap.put("gender", "Male");
break;
case R.id.rbFemale:
hashMap.put("gender", "Female");
break;
}
}

Why can't I set text to an Android?

``Hi, i have a calculator application and on the screen there are buttons for number and add, multiplication, clean, substruction and division buttons. But when I open and click buttons they couldnt make change on editText. When i write number on keybord, it edited. How can i fix it?
Here is full of my java code
private EditText screen; //textbox screen
private float numberBf; // save screen before pressing button operation
private String operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (EditText) findViewById(editText);
int idList[] = {R.id.button0,R.id.button,R.id.button2,R.id.button3,R.id.button4,
R.id.button5,R.id.button6,R.id.button7,R.id.button8,R.id.button9, R.id.buttonAdd,R.id.buttonMul,
R.id.buttonC, R.id.buttonDiv,R.id.buttonDot,R.id.buttonEq,R.id.buttonSub};
for(int id:idList){
View v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//new class
private class ButtonClickListener implements View.OnClickListener {
public void onClick(View view){
switch (view.getId()){
case R.id.buttonC: //clear button
screen.setText("0");
numberBf = 0;
operation = "";
break;
//adding function
case R.id.buttonAdd:
mMath("+");
break;
case R.id.buttonSub:
mMath("-");
break;
case R.id.buttonMul:
mMath("*");
break;
case R.id.buttonDiv:
mMath("/");
break;
case R.id.buttonEq:
mResult();
break;
default:
String num = ((Button) view).getText().toString();
getKeyboard(num);
break;
}
}
}
public void mMath(String s){
numberBf = Float.parseFloat(screen.getText().toString()); //save the screen
operation = s; //save operation
screen.setText("0"); //clear screen
}
public void mResult(){
float numberFl = Float.parseFloat(screen.getText().toString());
float result = 0;
if(operation.equals("+"))
result = numberFl + numberBf;
if (operation.equals("-"))
result = numberBf - numberFl;
if(operation.equals("*"))
result = numberFl * numberBf;
if (operation.equals("/"))
result = numberBf / numberFl;
screen.setText(String.valueOf(result));
}
public void getKeyboard(String str){
String scrCurrent = screen.getText().toString();
if (scrCurrent.equals("0"))
scrCurrent = "";
scrCurrent = str;
screen.setText(str);
}
}
and some part of my activity_main xml code, number 9 button and text place is
activity_main :
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:text="0"
android:layout_below="#+id/button0"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="57dp"
android:gravity="right"
android:editable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:id="#+id/button9"
android:layout_below="#+id/button5"
android:layout_toRightOf="#+id/button5"
android:textStyle="bold" />
please help me thank you
screen = (EditText) findViewById(editText);
The parameter editText is not a valid Resource Identifier. In XML you should have
<EditText ...
android:id="#+id/thetextid">
And then in your code you should have
screen = (EditText) findViewById(R.id.thetextid);
This should make it work:
screen = (EditText) findViewById(R.id.editText);
You haven't instantiated the button click listener. Add
btnClick = new ButtonClickListener();
before any of the setOnClickListener(btnClick) calls.

Simple android calculator application crashes

I am building a simple calculator, but for some reason, it crashes as soon as I press a button. Please help me out with it.
This is my Calculator.java class.
package com.dexter.seemab;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Calculator extends Activity{
String display="";
Character op = 'q';
int i,num,numtemp;
int check=0;
EditText rd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
rd=(EditText)findViewById(R.id.etResult);
}
public void btnClicked(View v){
switch(v.getId()){
case R.id.one:{
insert(1);
}
case R.id.two:{
insert(2);
}
case R.id.three:{
insert(3);
}
case R.id.four:{
insert(4);
}
case R.id.five:{
insert(5);
}
case R.id.six:{
insert(6);
}
case R.id.seven:{
insert(7);
}
case R.id.eight:{
insert(8);
}
case R.id.nine:{
insert(9);
}
case R.id.zero:{
insert(0);
}
case R.id.add:{
perform();
op='+';
}
case R.id.sub:{
perform();
op='-';
}
case R.id.product:{
perform();
op='*';
}
case R.id.difference:{
perform();
op='/';
}
case R.id.equals:{
calculate();
}
case R.id.clear:{
clear();
}
}
}
public void insert(int digit){
if (check==1){
clear();}
display=display+Integer.toString(digit);
num=Integer.valueOf(display).intValue();
rd.setText(display);
check=0;
}
public void perform(){
numtemp=num;
display=display+op.toString();
}
public void calculate(){
switch(op){
case '+':
i=num+numtemp;
case '-':
i=num-numtemp;
case '*':
i=num*numtemp;
case '/':
i=num/numtemp;
}
display=Integer.toString(i);
rd.setText("="+display);
check=1;
}
public void clear(){
op='q';
num=0;
numtemp=0;
i=0;
display="";
rd.setText(display);
}
}
my buttons contain an onClick listener which points to the method btnClicked(). Now whenever I press a button, the program of mine crashes. PLease help me out with it. Thanks.
There are some things that should cause your App to crash:
As you do not use break-statements at the end of your cases, every case from the one matching your button-id to the last statement (R.id.clear) will be executed. This certainly is unexpected behaviour that you should fix.
Further num / numtemp is wrong as numtemp represents the firstly entered number and num the last number.
This is your fixed code. Read below what caused the Exception:
package com.dexter.seemab;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Calculator extends Activity {
String display = "";
Character op = 'q';
int i, num, numtemp;
int check = 0;
EditText rd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
rd = (EditText) findViewById(R.id.etResult);
}
public void btnClicked(View v) {
switch (v.getId()) {
case R.id.one:
insert(1);
break;
case R.id.two:
insert(2);
break;
case R.id.three:
insert(3);
break;
case R.id.four:
insert(4);
break;
case R.id.five:
insert(5);
break;
case R.id.six:
insert(6);
break;
case R.id.seven:
insert(7);
break;
case R.id.eight:
insert(8);
break;
case R.id.nine:
insert(9);
break;
case R.id.zero:
insert(0);
break;
case R.id.add:
op = '+';
perform();
break;
case R.id.sub:
op = '-';
perform();
break;
case R.id.product:
op = '*';
perform();
break;
case R.id.difference:
op = '/';
perform();
break;
case R.id.equals:
calculate();
break;
case R.id.clear:
clear();
break;
}
}
public void insert(int digit) {
if (check == 1) {
clear();
}
display = display + Integer.toString(digit);
if(op == 'q') {
num = Integer.valueOf(display).intValue();
} else {
String[] digits = display.split("\\"+op.toString());
num = Integer.valueOf(digits[digits.length-1]);
}
rd.setText(display);
check = 0;
}
public void perform() {
numtemp = num;
display = display + op.toString();
}
public void calculate() {
switch (op) {
case '+':
i = numtemp + num;
break;
case '-':
i = numtemp - num;
break;
case '*':
i = numtemp * num;
break;
case '/':
i = numtemp / num;
break;
}
display = Integer.toString(i);
rd.setText("=" + display);
check = 1;
}
public void clear() {
op = 'q';
num = 0;
numtemp = 0;
i = 0;
display = "";
rd.setText(display);
}
}
Another hint: You're calculator is not able to perform simple tasks like 3+4-5. If you want those terms to be calculated you have to change at least the perform()-method.
EDIT:
I found the cause of the crash: It is an NumberFormatException thrown in this line: num = Integer.valueOf(display).intValue();. It occurs (with my corrected code) when you click the first digit after the operator. It occurs because something like 12+8 cannot be parsed to int. So you have two choices to fix this:
1) In method perform: Change display = display + op.toString(); to display = "";. This will fix the Exception, but it is not very user-friendly.
2) In method insert: Change num = Integer.valueOf(display).intValue(); to
if(op == 'q') {
num = Integer.valueOf(display).intValue();
} else {
String[] digits = display.split("\\"+op.toString());
num = Integer.valueOf(digits[digits.length-1]);
}
This way your EditText will display text like "12+52" which is more user-friendly.
first change num=Integer.valueOf(display).intValue();
TO
num=Integer.parse(display);
and change display=Integer.toString(i);
TO
display=String.valueOf(i);
This code is when i was learning Android Application Development, and I am sharing it with you. May be you can get some idea from here, hope it helps:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*" >
<TableRow>
<EditText
android:id="#+id/editText"
android:layout_span="4"
android:editable="false"
android:gravity="right"
android:hint="Your text here..." />
</TableRow>
<View
android:layout_height="2px"
android:background="#00ff00" />
<TableRow>
<Button
android:id="#+id/button1"
android:text="1" />
<Button
android:id="#+id/button2"
android:text="2" />
<Button
android:id="#+id/button3"
android:text="3" />
<Button
android:id="#+id/buttonAdd"
android:text="+" />
</TableRow>
<TableRow>
<Button
android:id="#+id/button4"
android:text="4" />
<Button
android:id="#+id/button5"
android:text="5" />
<Button
android:id="#+id/button6"
android:text="6" />
<Button
android:id="#+id/buttonSub"
android:text="-" />
</TableRow>
<TableRow>
<Button
android:id="#+id/button7"
android:text="7" />
<Button
android:id="#+id/button8"
android:text="8" />
<Button
android:id="#+id/button9"
android:text="9" />
<Button
android:id="#+id/buttonMul"
android:text="*" />
</TableRow>
<TableRow>
<Button
android:id="#+id/button0"
android:layout_span="2"
android:text="0" />
<Button
android:id="#+id/buttonClear"
android:text="Clr" />
<Button
android:id="#+id/buttonDiv"
android:text="/" />
</TableRow>
<TableRow>
<Button
android:id="#+id/buttonEqu"
android:layout_span="2"
android:text="=" />
<Button
android:id="#+id/buttonCan"
android:text="C" />
<Button
android:id="#+id/buttonPow"
android:text="^" />
</TableRow>
</TableLayout>
Activity:
public class MyFirstCalculator extends Activity implements OnClickListener
{
/** Called when the activity is first created. */
Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9;
Button btnAdd,btnSub,btnMul,btnDiv,btnPow,btnEqu,btnCan,btnClr;
EditText editText;
Double oldValue;
char chOp=' ';
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText=(EditText) findViewById(R.id.editText);
btn0 = (Button)findViewById(R.id.button0);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
btn4 = (Button)findViewById(R.id.button4);
btn5 = (Button)findViewById(R.id.button5);
btn6 = (Button)findViewById(R.id.button6);
btn7 = (Button)findViewById(R.id.button7);
btn8 = (Button)findViewById(R.id.button8);
btn9 = (Button)findViewById(R.id.button9);
btnAdd = (Button)findViewById(R.id.buttonAdd);
btnSub = (Button)findViewById(R.id.buttonSub);
btnMul = (Button)findViewById(R.id.buttonMul);
btnDiv = (Button)findViewById(R.id.buttonDiv);
btnPow = (Button)findViewById(R.id.buttonPow);
btnEqu = (Button)findViewById(R.id.buttonEqu);
btnCan = (Button)findViewById(R.id.buttonCan);
btnClr = (Button)findViewById(R.id.buttonClear);
btn0.setOnClickListener(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btnAdd.setOnClickListener(this);
btnSub.setOnClickListener(this);
btnDiv.setOnClickListener(this);
btnMul.setOnClickListener(this);
btnPow.setOnClickListener(this);
btnEqu.setOnClickListener(this);
btnCan.setOnClickListener(this);
btnClr.setOnClickListener(this);
}
public void onClick(View v)
{
try
{
Button btn = (Button)v;
Double answer, curValue;
switch(v.getId())
{
case R.id.button0:
case R.id.button1:
case R.id.button2:
case R.id.button3:
case R.id.button4:
case R.id.button5:
case R.id.button6:
case R.id.button7:
case R.id.button8:
case R.id.button9:
editText.setText(editText.getText()+""+btn.getText()+"");
break;
case R.id.buttonAdd:
case R.id.buttonSub:
case R.id.buttonMul:
case R.id.buttonDiv:
case R.id.buttonPow:
if(editText.getText()+"" == "")
{
return;
}
chOp=(btn.getText()+"").charAt(0);
oldValue=Double.parseDouble(editText.getText()+"");
editText.setText("");
break;
case R.id.buttonCan:
oldValue=0.0;
editText.setText("");
break;
case R.id.buttonClear:
int len = (editText.getText()+"").length();
if(len==0)
{
Toast.makeText(getApplicationContext(), "Nothing to erase...", Toast.LENGTH_LONG).show();
}
else
{
editText.setText((editText.getText()+"").substring(0, len-1));
break;
}
case R.id.buttonEqu:
if(editText.getText()+"" == "")
{
return;
}
curValue = Double.parseDouble(editText.getText()+"");
switch (chOp)
{
case '+':
answer = oldValue+curValue;
editText.setText(answer+"");
break;
case '-':
answer=oldValue-curValue;
editText.setText(answer+"");
break;
case '*':
answer=oldValue*curValue;
editText.setText(answer+"");
break;
case '/':
answer=oldValue/curValue;
editText.setText(answer+"");
break;
case '^':
answer=Math.pow(oldValue, curValue);
editText.setText(answer+"");
break;
}
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Note: I dont remember if the code is complete or not, or whether it runs properly or not, as it was written one year ago.

How to handle onClick() in 100 buttons?

I have 100 buttons in layout and OnClick() method for all of it.
If I use switch I need to do case R.id.button1, ..., case R.id.button100 for all 100 buttons. How to shorten this code?
public void webClick(View v)
{
switch(v.getId())
{
case R.id.button1:
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink","file:///android_asset/chapter/chapter1.html");
startActivity(intent);
break;
case R.id.button2:
Intent intent2 = new Intent(this, Webview.class);
intent2.putExtra("weblink","file:///android_asset/chapter/chapter2.html");
startActivity(intent2);
break;
// ...
case R.id.button100:
Intent intent100 = new Intent(this, Webview.class);
intent100.putExtra("weblink","file:///android_asset/chapter/chapter100.html");
startActivity(intent100);
break;
}
}
If the URL depends directly on the ID, then try this:
public void webClick(View v)
{
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink","file:///android_asset/chapter/chapter" + v.getId() + ".html");
startActivity(intent);
}
EDITED
In the case you URL doesn't depend directly on the ID, then try mapping button IDs with URLS, like this:
Map<Integer, String> urls = new HashMap();
urls.put(R.id.button1, "file:///android_asset/chapter/chapter100.html");
// ... 1 to 100 ...
and modify the above code like this:
public void webClick(View v)
{
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink", urls.get(v.getId()));
startActivity(intent);
}
EDITED #2
If in the label of your buttons you already have the URL, a sugestion (not mine but made by #pad) would be to use it to calculate the URL this way:
public void webClick(View v)
{
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink", "file:///android_asset/chapter/chapter" + v.getText().replaceAll("Chapter ","") + ".html"); // Assuming your text is like "Chapter 50"
startActivity(intent);
}
For more number of buttons in your case, Dynamically create button in a loop and assign onclick event like..
Create one LinearLayout in your xml file.
Now add this all buttons in that LinearLayout like..
String[] urls={url1,url2.....url100}; // here write your all URLs
Button button[]= new Button[100];
LinearLayout mainlinear=(LinearLayout) findViewById(R.id.main_layer);
for (int i = 0; i < 100; i++) {
button[i] = new Button(this);
button[i].setText(i);
button[i].setTag(i+":"+URL); // URL = What you need to pass when button is click
button[i].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView selected = (TextView) v;
String tag = selected.getTag().toString();
//Here you need to write your code when button is pressed.
Intent intent = new Intent(this, Webview.class);
intent2.putExtra("weblink",urls[i]);
startActivity(intent2);
}
}
mainlinear.addView(button[i]);
You might want to use a ListView. If you want to have buttons, then use a ListView, which has one button in each item's layout.
Then, you setup a onItemClickListener. You get the position of that button (the first one has position 0, the second has position 1, etc.). Then compose a link:
String link= "file:///android_asset/chapter/chapter" + (position +1) + ".html";
The rest of your code, would be the same (intent.putExtra("weblink", link);)
My suggestion is to use a ListView or GridView for this case and save the file names in an ArrayList. Then you do something like this:
List<String> urlList = new ArrayList<String>();
urlList.add("file:///android_asset/chapter/chapter1.html");
urlList.add("file:///android_asset/chapter/chapter2.html");
// and so on
ListView listView = (ListView)findViewById(R.id.listView);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.id.simple_list_item_1, urlList);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink", urlList.get(position));
startActivity(intent);
}
});
This would be a nice implementation because you would avoid using 100 Buttons and OnClickListeners to save some ressources.
Edit: This code should be running, just put it in onCreate() for some testing. All you have to do is to define a ListView in your layout.xml insteed of the 100 buttons like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView">
</ListView>
</LinearLayout>
If you really wanna use this with Buttons than follow morgano's suggestion.
I think that this should be working:
public void webClick(View v)
{
String stringID = String.valueOf(v.getId());
String[] temp = stringID.split("utton");
stringID = "file:///android_asset/chapter/chapter" +temp[1]+ ".html"
Intent intent = new Intent(this, Webview.class);
intent.putExtra("weblink",stringID);
startActivity(intent);
}
public void webClick(View v)
{
Intent intent = new Intent(this, Webview.class);
switch(v.getId())
{
case R.id.button1:
intent.putExtra("weblink","file:///android_asset/chapter/chapter1.html");
startActivity(intent);
break;
case R.id.button2:
intent.putExtra("weblink","file:///android_asset/chapter/chapter2.html");
startActivity(intent);
break;
case R.id.button3:
intent.putExtra("weblink","file:///android_asset/chapter/chapter3.html");
startActivity(intent);
break;
.
.
.
.
case R.id.button100:
intent.putExtra("weblink","file:///android_asset/chapter/chapter100.html");
startActivity(intent);
break;
default:
break;
}
}

Categories

Resources