Simple android calculator application crashes - java

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.

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;
}
}
}

Switch case for images

I'm going to create the app which will take random 3 numbers from array String [] powerBalls with 5 numbers and will switch the image with picture to every number and then show the number and picture(e.g. string "1" from array powerballs will have the image with the name "o1"). The problem is that on the display I get the numbers and can see the picture as long as switch case will find the correct image. Then the app shutting down. The images are all the time visible and they should appear only with the random number. What is wrong with this code?
I have really no idea what I'm doing wrong and could not find some example for this program.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zufallsgenerator);
bindViews();
mGenerateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generateRandomNumbers();
}
});
}
public void generateRandomNumbers(){
Collections.shuffle(Arrays.asList(powerBalls));
mFirstNumber.setText(powerBalls[0]);
mSecondNumber.setText(powerBalls[1]);
mThirdNumber.setText(powerBalls[2]);
mFourthNumber.setText(powerBalls[3]);
mFifthNumber.setText(powerBalls[4]);
mSixthNumber.setText(powerBalls[5]);
switch (powerBalls[0]) {
case "1":
imageViewDice1.setImageResource(R.drawable.o1);
imageViewDice1 = (ImageView)findViewById(R.id.image_view_dice1);
break;
case "2":
imageViewDice2.setImageResource(R.drawable.o2);
imageViewDice2 = (ImageView)findViewById(R.id.image_view_dice2);
break;
case "3":
imageViewDice3.setImageResource(R.drawable.o3);
imageViewDice3 = (ImageView)findViewById(R.id.image_view_dice3);
break;
case "4":
imageViewDice4.setImageResource(R.drawable.o4);
imageViewDice4 = (ImageView)findViewById(R.id.image_view_dice4);
break;
case "5":
imageViewDice5.setImageResource(R.drawable.o5);
imageViewDice5 = (ImageView)findViewById(R.id.image_view_dice5);
break;
case "6":
imageViewDice6.setImageResource(R.drawable.o6);
imageViewDice6 = (ImageView)findViewById(R.id.image_view_dice6);
break;
}
switch (powerBalls[1]) {
case "1":
imageViewDice1.setImageResource(R.drawable.o1);
imageViewDice1 = (ImageView)findViewById(R.id.image_view_dice1);
break;
case "2":
imageViewDice2.setImageResource(R.drawable.o2);
imageViewDice2 = (ImageView)findViewById(R.id.image_view_dice2);
break;
case "3":
imageViewDice3.setImageResource(R.drawable.o3);
imageViewDice3 = (ImageView)findViewById(R.id.image_view_dice3);
break;
case "4": // and so on...*****
and on the end of the java class:
public void bindViews(){
mFirstNumber = (TextView)findViewById(R.id.firstNumber);
mSecondNumber = (TextView)findViewById(R.id.secondNumber);
mThirdNumber = (TextView)findViewById(R.id.thirdNumber);
mFourthNumber = (TextView)findViewById(R.id.fourthNumber);
mFifthNumber = (TextView)findViewById(R.id.fifthNumber);
mSixthNumber = (TextView)findViewById(R.id.sixthNumber);
mPowerBall = (TextView)findViewById(R.id.powerBall);
mGenerateButton = (Button)findViewById(R.id.mgenerateButton);
The example of the xml file with views:
<TextView
android:id="#+id/firstNumber"
android:layout_weight="1"
android:fontFamily="serif"
android:textSize="24sp"
android:padding="4dp"
android:layout_margin="8dp"
android:text="01"
android:textColor="#color/startblue"
android:layout_width="0dp"
android:layout_height="wrap_content" />
Thank you in advance for your suggestions and answers. Cheers

Android - Radiobutton click event to go to new activity

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

Floating button setOnClickListener not gets called in Android

I want to integrate movable floating button same like "WhatsApp" Application When open, it displays hike floating button with motion. And also working click event.
I used with default OnTouch event it's working but I can't apply Click event on floating button. How can I apply both Click and touch event ?
Thanks in advance!
home.xml
<RelativeLayout
android:id="#+id/rl_parent_floating"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible">
<RelativeLayout xmlns:fab="http://schemas.android.com/apk/res-auto"
android:id="#+id/rl_floating_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp">
<TextView
android:id="#+id/txtCartCount"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignRight="#+id/fab"
android:layout_alignTop="#+id/fab"
android:background="#drawable/cart_gold_circle"
android:gravity="center"
android:singleLine="true"
android:text="2"
android:textColor="#android:color/white"
android:textSize="8sp" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:src="#drawable/ic_floating_cart"
fab:fab_colorNormal="#color/header_color_red"
fab:fab_colorPressed="#color/colorPrimaryDark"
fab:fab_colorRipple="#color/gold_color" />
</RelativeLayout>
</RelativeLayout>
Home.java
mFloatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
mRrootLayout = (ViewGroup) findViewById(R.id.rl_floating_button);
rl_floating_button = (RelativeLayout) findViewById(R.id.rl_floating_button);
rl_parent_floating = (RelativeLayout) findViewById(R.id.rl_parent_floating);
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mIntent = new Intent(mActivity, Cart.class);
startActivity(mIntent);
}
});
mFloatingActionButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
view.getLayoutParams();
_xDelta = X - lParams.leftMargin;
_yDelta = Y - lParams.topMargin;
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
case MotionEvent.ACTION_MOVE:
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
.getLayoutParams();
layoutParams.leftMargin = X - _xDelta;
layoutParams.topMargin = Y - _yDelta;
layoutParams.rightMargin = 0;
layoutParams.bottomMargin = 0;
view.setLayoutParams(layoutParams);
break;
}
mRrootLayout.invalidate();
return true;
}
});
Use SimpleOnGestureListener & GestureDetector class to get single tap on screen instead of using Interface setOnclickListner as it may not work with ontouchListner
private class SingleTapDetector extends SimpleOnGestureListener{
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
}
and then in onCreate method initialize GestureDetector like this
gestureDetector=new GestureDetector(this,new SingleTapDetector());
Now, check in OnTouchListener of floating bubble , if single tap is detected on floating button
Code
mFloatingActionButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
// code for single tap or onclick
// pass your intent here
} else {
switch(event.getAction()){
// code for move and drag
// handle your MotionEvents here
}
return true;
}
});
Hope this will help you.

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.

Categories

Resources