Dot in calculator android studio - java

I have been trying to build a simple calculator in android studio. Everything is fine but i have a problem, when i run the calculator and i press the dot button, it shows in the textview "." instead "0."
Also, i need to check the existence of two decimal points in a single numeric value.
here is an image:
it shows "."
and i want:
how can i change this??, here is my code:
private int cont=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display=(TextView)findViewById(R.id.display);
text="";
}
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
display.setText(text);
}
public void dot(View view){ /*This is not finished*/
display.setText{"0."}
}
I was thinking in creating another method for the dot button, but the content of the text value disappears when i press another button, how to fix this?

try this
public void numero1(View view){ /*when i press a number, this method executes*/
Button button = (Button) view;
text += button.getText().toString();
if(text.substring(0,1).equals("."))
text="0"+text;
display.setText(text);
}

try this way
public void dot(View view){ /*This is not finished*/
String str=display.getText().toString().trim();
if(str.length()>0){
display.seText(str+".")
}else{
display.setText("0.")
}
}

Use a string builder and append all the text entered to already existing string. Before display, just use the toString() method on the string builder.

Create a class that represents your character sequence to be displayed and process the incoming characters.
For example:
class Display {
boolean hasPoint = false;
StringBuilder mSequence;
public Display() {
mSequence = new StringBuilder();
mSequence.append('0');
}
public void add(char pChar) {
// avoiding multiple floating points
if(pChar == '.'){
if(hasPoint){
return;
}else {
hasPoint = true;
}
}
// avoiding multiple starting zeros
if(!hasPoint && mSequence.charAt(0) == '0' && pChar == '0'){
return;
}
// adding character to the sequence
mSequence.append(pChar);
}
// Return the sequence as a string
// Integer numbers get trailing dot
public String toShow(){
if(!hasPoint)
return mSequence.toString() + ".";
else
return mSequence.toString();
}
}
Set such a click listener to your numeric and "point/dot" buttons:
class ClickListener implements View.OnClickListener{
#Override
public void onClick(View view) {
// getting char by name of a button
char aChar = ((Button) view).getText().charAt(0);
// trying to add the char
mDisplay.add(aChar);
// displaying the result in the TextView
tvDisplay.setText(mDisplay.toShow());
}
}
Initialize the display in onCreate() of your activity:
mDisplay = new Display();
tvDisplay.setText(mDisplay.toShow());

Related

if statement inside a onClickListener trying to get value of androidtextwidget

I am trying to convert a value that has been passed through from another fragment. The convert method is inside an onClickListener which when clicked will make the conversion of the value passed through the fragment.
The values are currently being placed into TextViews on my second fragment. However when I try to make an if statement it won't enter the loop
Text Name is what my textView has been set to.
The code is here
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textName.equals("Miles") && textName2.equals("Kilometers")) {
String str1 = editText1.getText().toString();
double unittoConvert = Double.parseDouble(str1);
double convertedUnit = unittoConvert * 1.6;
String result = Double.toString(convertedUnit);
textName3.setText(result);
}
}
});
This is the code for the methods that are setting the unit selected in scroller and passing it through to the text view which is then displaying the selected unit. When i try to extract these values it wont work
PageViewModel.getName().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName.setText(s);
}
});
PageViewModel2.getName2().observe(requireActivity(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textName2.setText(s);
}
});
Use getText to extract text from TextView and then compare
textName.getText().equals("Miles") && textName2.getText().equals("Kilometers")

How to validate decimal input not allowing alone "." and empty field?

I'm writing a calculator on Android Studio, in Java, and the app crashes if the user call the result with a dot "." alone or let the EditText field in blank.
I'm looking for a solution for not allowing these two conditions happening, together or individualy, in each of the three fields.
I've already tried TextWatcher and if/else but without success.
The .xml file where the editText field are designed is already set for decimalNumber.
I've already tried this:
if(myfieldhere.getText().toString().equals(".")){myfieldhere.setText("0");}
For each "valor line" and else for the "finalresult" line if everything is fine. Both inside the setOnClickListener block. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peso_layout);
result = findViewById(R.id.layresult);
conc = findViewById(R.id.layconc);
dose = findViewById(R.id.laydose);
peso = findViewById(R.id.laypeso);
calc = findViewById(R.id.laycalcpeso);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
});
}
The ideal output should be the app not crashing if these two conditions happen and sending an error message to the user that input is invalid.
What i'm receiving is the app crashing.
Thank you very much. I'm very beginner in Java and I'm few days struggling with this.
Dear Friend, Your directly trying to convert string input into float and then after your check value but do your code like Below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText edt1,edt2;
TextView txtans;
Button btnsum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1=findViewById(R.id.edt1);
edt2=findViewById(R.id.edt2);
txtans=findViewById(R.id.txtans);
btnsum=findViewById(R.id.btnsum);
btnsum.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.btnsum){
float n1,n2;
String value1=edt1.getText().toString();
String value2=edt2.getText().toString();
if(value1.equals("") || value1.equals(".")){
n1=0;
}else {
n1= Float.parseFloat(value1);
}
if(value2.equals("")|| value2.equals(".")){
n2=0;
}else{
n2= Float.parseFloat(value2);
}
float ans=n1+n2;
txtans.setText(ans+"");
}
}
}
See In above code, First get value from edittext and then check wheather it contain null or "." inside it. if it contains then store 0.0 value in some variable. then after make sum and display in textbox.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String myvalor = myfieldhere.getText().toString();
if(myvalor.equals(".") || myvalor.isEmpty())
{
// toast error : incorrect value
return;
}
try
{
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
catch(Exception exp){// toast with exp.toString() as message}
}
});
use TextUtils for check empty String its better
if(TextUtils.isEmpty(peso.getText().toString())||
TextUtils.isEmpty(conc.getText().toString())||
TextUtils.isEmpty(dose.getText().toString())){
return;
}

how to take default value of an edittext as 0?

I am trying to make a simple android app in which 2 text fields are there.input range is 0 to 15. If the number is in range than addition is performed.
i have implemented input varification so now if the edit text is empty it shows empty field warning. but calculation is not done. what i want is if the field is empty is should show the error but also do the addition by take default value as 0.
here is my code
public class MainActivity extends AppCompatActivity {
private EditText check,check2;
private TextView textView;
private TextInputLayout checkLay,checkLay2;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeWidgets();
initializeListeners();
}
private void initializeWidgets(){
check=findViewById(R.id.check);
check2=findViewById(R.id.check2);
checkLay2=findViewById(R.id.checkLay2);
checkLay=findViewById(R.id.checkLay);
button=findViewById(R.id.button);
textView=findViewById(R.id.textView);
}
private void initializeListeners() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signUp();
}
});
}
private void signUp(){
boolean isVailed=true;
int a1,a2;
String one=check.getText().toString();
String two=check2.getText().toString();
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
else {
if (one.length() > 0)
{
a1=Integer.parseInt(one);
if(a1> 15){
checkLay.setError("quiz marks must be less than 15");
isVailed=false;
}
else if(a1 <=15)
{
checkLay.setErrorEnabled(false);
isVailed=true;
}
}
}
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
isVailed=false;
}
else{
if (two.length() > 0)
{
a2=Integer.parseInt(two);
if(a2 > 15)
{ checkLay2.setError("quiz marks must be less than 15");
isVailed=false;
}
else
if(a2 <=15)
{
checkLay2.setErrorEnabled(false);
isVailed=true;
}
}
if(isVailed)
{
int total;
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
total=a1+a2;
textView.setText(String.valueOf(total));
}
}
I would do it differently but for your specific question
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
isVailed=false;
}
Change to
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1=0;
}
Same for the two.isEmpty()
If a field is empty you set isVailed to false and thus say not to add the numbers. Instead you want to set the corresponding number to zero and let isVailed be true:
if(one.isEmpty()){
checkLay.setError("YOu need to enter something");
a1 = 0;
}
and
if(two.isEmpty()){
checkLay2.setError("You need to enter something");
a2 = 0;
}
Also throw off the lines
a1=Integer.parseInt(one);
a2=Integer.parseInt(two);
You already convert inputs to a1 and a2 earlier.
A piece of advice: you have doubled code. It's better to use functions for such pieces of codes.
add this line in your initializeWidgets function
yourEditText.setText(0);
follow link for more help: duplicate
You can create a convenience method to get value from your edittext. The following code will return 0 if edittext is empty else the value from the edittext
private int getIntFromEditText(EditText editText) {
return editText.getText().length()>0 ? Integer.parseInt(editText.getText().toString()):0;
}
Call it by passing EditText as a parameter, e-g
a1=getIntFromEditText(check)

Can't take global variable in android

When user click the button , the age is 50. After that, when sending data using nfc,the value of age is 0.0. Help! How I can solve it ?
public class MainActivity extends Activity{
String mone;
InputStream is =null;
double age;
double app=50.00,water=60.88,ban=35.55;
boolean app_b=true, water_b=true, ban_b=true;
private ViewFlipper viewFlipper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewFlipper = (ViewFlipper) findViewById(R.id.viewflipper);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
String te = new String(msg.getRecords()[0].getPayload());
mone=te;
Log.e("value 2 ","val"+age); //age is 0.0
}
}
public void onNewIntent(Intent intent) {
setIntent(intent);
}
public void onClick(View v) {
if (v.getId() == R.id.apple)
app_b=false;
else if (v.getId() == R.id.watermelon)
water_b=false;
else if (v.getId() == R.id.banana)
ban_b=false;
}
public void aniStart(){
// Next screen comes in from right.
viewFlipper.setInAnimation(this, R.anim.slide_in_from_right);
// Current screen goes out from left.
viewFlipper.setOutAnimation(this, R.anim.slide_out_to_left);
// Display previous screen.
viewFlipper.showPrevious();
}
public void submit(View v){
if(v.getId() == R.id.button && (!app_b || !water_b || !ban_b)){
if (!app_b)
age=app;
else if (!water_b)
age=water;
else if (!ban_b)
age=ban;
aniStart();
Log.e("Value","age:"+age); //age=50;
}
else {
Toast.makeText(getApplicationContext(),"please select your fruit",Toast.LENGTH_LONG).show();
}
}
}
Why age is 0.0 ?
UPDATE :
This app is actually receive data from another phone via NFC. Before tapping the phone , I click on the button and get the value 50. After that , I receive data from another phone and hold the string value in "te".
Currently your variable is getting updated when button is clicked but if you want to assign a value to age when checking intent then you can pass a double in the Intent that started this activity using putExtra(String key, double value) in that intent.
uhm onCreate gets called first and age has no value assigned.
Age is showing up as 0.0 because:
This is the default value given to an unassigned double in java(double age; // age = 0.0)
The onCreate() method runs as soon as your activity 'starts up' (before you can click your button) so the log statement will always print whatever value you initialize the age variable to (in this case that's 0.0).
Put this code in onClick():
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
Log.e("nfc","insidenfc"+age); //age is 0.0
}

Can't get my if statement to work?

I know this has got to be simple. But for the life of me i don't know why i can't get this right.
Ok so I want to go from a listview page (got that) then click a switch to make it go to the next page (also got that.) Then I want a int to tell me which position I am on form the last page (might be working?) now i can't get the If Else statement to work in the page.
public class NightmareParts extends Activity
{
public int current_AN_Number = NightmareList.AN_position_num;
private TextView edit_title;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.part_layout);
// isn't working here. Why?
// test_edit = (TextView)findViewById(R.id.directions_tv);
// test_edit.setText(R.string.directions_text_two);
// works without this being in here.
setDoneButtonListener();
}
//Set up the Done button to initialize intent and finish
private void setDoneButtonListener()
{
Button doneButton = (Button) findViewById(R.id.back_button);
doneButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
finish();
}
});
}
private void editTitle()
{
if (current_AN_Number = 1)
{
edit_title = (TextView)findViewById(R.id.part_title);
edit_title.setText(R.string.AN_title_1);
}
}
}
The current_AN_number is coming from the last page.
Your if statement is incorrect:
if (current_AN_Number = 1)
You've used the assignment operator, when you wanted to compare it with the == operator:
if (current_AN_Number == 1)
if (current_AN_Number = 1)
Should be
if (current_AN_Number == 1)
You're not setting current_AN_Number to be 1, you are comparing if it is equal to 1. So use ==.
test_edit = (TextView)findViewById(R.id.directions_tv);
is not working because test_edit is never declared.

Categories

Resources