Pythagoras in android application - java

Hey guys I would really like to calculate not only the c=hypotenuse but also a or b out from what was given in the 3 EditText-Views. But it crashes and won't output a result. Any suggestions? I'm pretty new to this stuff. :)
package net.starostka.somefunctions;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Pythagoras extends AppCompatActivity implements View.OnClickListener {
EditText aNumPyt;
EditText bNumPyt;
EditText cNumPyt;
Button pythagorasCalcu;
TextView pythagorasResultFinal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pythagoras);
aNumPyt = (EditText) findViewById(R.id.aNumPyt);
bNumPyt = (EditText) findViewById(R.id.bNumPyt);
pythagorasCalcu = (Button) findViewById(R.id.pythagorasCalcu);
pythagorasResultFinal = (TextView) findViewById(R.id.pythagorasResultFinal);
// set a listener
pythagorasCalcu.setOnClickListener(this);
}
#Override
public void onClick(View v) {
double a=0,b=0,c=0;
double hypot = 0.0;
/*
// check if the fields are empty
if (TextUtils.isEmpty(aNumPyt.getText().toString()) || TextUtils.isEmpty(bNumPyt.getText().toString()) || TextUtils.isEmpty(cNumPyt.getText().toString())) {
return;
}
*/
// read EditText and fill variables with numbers
a = Double.parseDouble(aNumPyt.getText().toString());
b = Double.parseDouble(bNumPyt.getText().toString());
c = Double.parseDouble(cNumPyt.getText().toString());
if (a>b && a>c){
hypot=a;
if(hypot*hypot==(b*b+c*c)){
//result = Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
pythagorasResultFinal.setText(String.valueOf(hypot));
}
} else if (b>a && b>c){
hypot=b;
if(hypot*hypot==(a*a+c*c)){
//result = Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
pythagorasResultFinal.setText(String.valueOf(hypot));
}
} else if (c>a && c>b){
hypot=c;
if(hypot*hypot==(a*a+b*b)){
//result = Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
pythagorasResultFinal.setText(String.valueOf(hypot));
}
}
}
}
The XML file
</LinearLayout>
<TextView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginLeft="5pt"
android:layout_marginRight="5pt"
android:textSize="12pt"
android:layout_marginTop="3pt"
android:id="#+id/pythagorasResultFinal"
android:gravity="center_horizontal">
</TextView>
Before crash:
After crash:

EDIT
Interesting that no one pointed this out earlier, but I just realized you never initialize cNumPyt. You initialize the other EditTexts but never C. So when you try to get the text, you get NullPointerException because you try to get information from nothing.
Initialize the correct text box in your onCreate method.
In your image, you show that you are leaving input blank for one of the text boxes (in the "after crash" image, we see that you entered 3, 4, and then nothing). This means that there is no Double to be parsed, because "" is not a number.
From the Double documentation:
public static double parseDouble(String s) throws NumberFormatException
[...]
Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable double.
If your input is blank, you'll get an exception. Since it's not in a try-catch block, your application will crash.
To be more specific:
//cNumPyt is empty, and "" is not a parseable number, so NumberFormatException
c = Double.parseDouble(cNumPyt.getText().toString());
Sample block (you will need to do this for every variable separately so you can tell which variable was empty):
try{
a = Double.parseDouble(aNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
a = 0; //default to 0 (or whatever you choose)
}

#Override
public void onClick(View v) {
double a=0,b=0,c=0;
if (!TextUtils.isEmpty(aNumPyt.getText().toString()) &&
!TextUtils.isEmpty(bNumPyt.getText().toString()) &&
!TextUtils.isEmpty(cNumPyt.getText().toString()))
{
a = Double.parseDouble(aNumPyt.getText().toString());
b = Double.parseDouble(bNumPyt.getText().toString());
c = Double.parseDouble(cNumPyt.getText().toString());
if((a*a)==((b*b)+(c*c))){
pythagorasResultFinal.setText(String.valueOf(a));
}
else if ((b*b)==((a*a)+(c*c))){
pythagorasResultFinal.setText(String.valueOf(b));
}
else if ((c*c)==((a*a)+(b*b))){
pythagorasResultFinal.setText(String.valueOf(c));
}
}
}

I found the problem.. Arc676's solution worked as seen in the code below:
#Override
public void onClick(View v) {
double a=0.0,b=0.0,c=0.0;
double hypot = 0.0;
try{
a = Double.parseDouble(aNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
a = 0.0; //default to 0 (or whatever you choose)
}
try{
b = Double.parseDouble(bNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
b = 0.0; //default to 0 (or whatever you choose)
}
try{
c = Double.parseDouble(cNumPyt.getText().toString());
}catch (NumberFormatException e){
//oops, no number available
c = 0.0; //default to 0 (or whatever you choose)
}
if (c == 0.0){
hypot = Math.sqrt((Math.pow(a,2))+(Math.pow(b,2)));
pythagorasResultFinal.setText("Finding C\n" + String.valueOf(hypot));
}else if (a == 0.0){
hypot = Math.sqrt((Math.pow(c,2))-(Math.pow(b,2)));
pythagorasResultFinal.setText("Finding A\n" + String.valueOf(hypot));
}else if (b == 0.0) {
hypot = Math.sqrt((Math.pow(c,2))-(Math.pow(a,2)));
pythagorasResultFinal.setText("Finding B\n" + String.valueOf(hypot));
}
}
Another essential problem i found was i did not define the id for the c View.. Really small problem causing it all to crash..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pythagoras);
aNumPyt = (EditText) findViewById(R.id.aNumPyt);
bNumPyt = (EditText) findViewById(R.id.bNumPyt);
cNumPyt = (EditText) findViewById(R.id.cNumPyt); //Forgot to add this line of code
pythagorasCalcu = (Button) findViewById(R.id.pythagorasCalcu);
pythagorasResultFinal = (TextView) findViewById(R.id.pythagorasResultFinal);
// set a listener
pythagorasCalcu.setOnClickListener(this);
}
Thanks for the fast response and help! (y)

Related

How to display many variables in one textView

I'm working on my first project in Android Studio and I got stuck in "how to display different variables in one textView". to be more clear I'm working on an app that requires the user to enter the gender. each gender has its own calculation method. so I want to display the result calculation the user do in the main interface and In one TextView. I've tried many times to do it but the result is "0.0"
I added another textView and assigned each calculation method to one textview I was able to display the two results.
public class Main_Interface extends AppCompatActivity implements View.OnClickListener{
private TextView results;
//private TextView fResults;//this is the second textview that I created.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
//fResults = (TextView)findViewById(R.id.fResults);
// if(fResults.getText().toString().equals("0.0")){
// fResults.setVisibility(View.INVISIBLE );
// }
calculateMale();
calculateFemale();
}
public void calculateMale(){
SharedPreferences s = getSharedPreferences("data", Context.MODE_PRIVATE);
double weight = s.getFloat("weight",0.0f);
double height = s.getFloat("height",0.0f);
int age = s.getInt("theDate", 0);
double results2 = 66+(13.7*weight)+(5*height)-(6.8*age);
results.setText(""+results2);
public void calculateFemale(){
SharedPreferences s1 = getSharedPreferences("data", Context.MODE_PRIVATE);
double fWeight = s1.getFloat("fWeight",0.0f);
double fHeight = s1.getFloat("fHeight",0.0f);
int Fage = s1.getInt("theDate", 0);
double results3 = 655 + (9.6 * fWeight) + (1.8 * fHeight) - (4.7 *Fage)
;
fResults.setText(""+results3);
SharedPreferences.Editor editor = s1.edit();
editor.putFloat("results", (float) results3);
editor.commit();
}
}
displaying the calculation in one textview.
You Are calling these two methods before checking these two methods
calculateMale();
calculateFemale();
in onCreate() {
//do this
calculateMale();
calculateFemale();
//Then check the result to make results visible or invisible.
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
You just need to make it clear when the function is being called. What actually happening here is you are checking textView's value even before calculating your required values. So it is throwing 0.0.
Simply call calculateMale(); calculateFemale(); before checking textView's value.
You are printing results before calling the two function. Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
calculateMale();
calculateFemale();
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
Return the result from calculateMale() and calculateFemale() methods:
String calculateMale = calculateMale();
String calculateFemale = calculateFemale();
results = (TextView)findViewById(R.id.results);
String result = calculateMale.concat(calculateFemale);
if (result.length() >= 0) {
results.setText(result);
} else {
results.setVisibility(View.INVISIBLE);
}

Android app crashes after a variable is loaded from component

I have quite a simple application. However, after I clik on the button, app crashes. Tried to debug it and the problem seems to be in first 3 row of the onClick method. Once I tried to get there values manually, not via those edit boxes, everything went smoothly. Any ideas please?
public class MainActivity extends AppCompatActivity {
EditText editText_pocetKM;
EditText editText_spotreba;
EditText editText_cenaPHM;
TextView textView_spotrebaO;
TextView textView_cenaO;
DecimalFormat df = new DecimalFormat("0.00##");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_pocetKM = (EditText) findViewById(R.id.editText1_pocetKM);
editText_spotreba = (EditText) findViewById(R.id.editText_Spotreba);
editText_cenaPHM = (EditText) findViewById(R.id.editText1_cenaPHM);
textView_spotrebaO = (TextView) findViewById(R.id.textView_spotrebaO);
textView_cenaO = (TextView) findViewById(R.id.textView_cenaO);
}
public void onClick(View v) {
Double pocetKm = Double.parseDouble(editText_pocetKM.getText().toString());
Double spotreba = Double.parseDouble(editText_spotreba.getText().toString());
Double cenaPHM = Double.parseDouble(editText_cenaPHM.getText().toString());
Double spotrebaO = spotreba * pocetKm / 100;
Double cenaO = spotrebaO * cenaPHM;
textView_cenaO.setText("Cena za spotřebované palivo bude "+ df.format(cenaO) + " Kč");
textView_spotrebaO.setText("Celkem bude spotřebováno "+ df.format(spotrebaO) + " litrů paliva");
}
}
You didn't provide the logcat of your crash report. If the logcat was provided we could be certain of your exact problem. But anyway, as you've got rid of your crash by removing the first three lines of your onClick function, I suppose you're setting invalid inputs in your EditText.
You're parsing the text entered in the EditText to double which will fail if the input is not a valid double string. For example, it'll parse 11.01 fine when it'll throw an exception while parsing Hello.
So to check if the application is crashing for a parsing error, you might consider surrounding them with a try/catch block like this.
try {
Double pocetKm = Double.parseDouble(editText_pocetKM.getText().toString());
Double spotreba = Double.parseDouble(editText_spotreba.getText().toString());
Double cenaPHM = Double.parseDouble(editText_cenaPHM.getText().toString());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Parsing error", Toast.LENGTH_LONG).show();
}

java.lang.NumberFormatException: Invalid int: “” error android

I am making an app where user must enter basic info about self.First name,second name, city and quantity that he or she wish to order.If he or she skip one field toast will pop up with message what field is skipped. And that is ok.That works, but if he skips quantity field I got error on my phone and it send user back on previously activity.When I inspect my LogCat I see error message
java.lang.NumberFormatException: Invalid int: “” error
Now I know why that message appears.Because it expected to find Integer,in if statment. but actually finds String. But do not know how to fix it.The last if/else statemen is an Issue:
Now what i tried so far:
1) Tried to set primitive int as object Integer
2)Tried to use kolicina==0;
3)Tried to use kolicina.equals(null) / kolicina.equals(0);
4)Tried to use .isEmty();
my code:
package com.dsk.android.decijisvetknjiga;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Narudzbina extends AppCompatActivity {
String porukaGreska="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.narudzbina);
}
public boolean praznoPolje(EditText et){
return (et != null && (et.equals("") || et.equals(" ")));
}
public void kreiranjeNarudzbine(View v) {
EditText editTextIme = (EditText) findViewById(R.id.ime);
String imeNarucioca = editTextIme.getText().toString();
praznoPolje(editTextIme);
EditText editTextPrezime = (EditText) findViewById(R.id.prezime);
String prezimeNarucioca = editTextPrezime.getText().toString();
praznoPolje(editTextIme);
EditText editTelefonNarucioca = (EditText) findViewById(R.id.telefon);
String telefonNarucioca = editTelefonNarucioca.getText().toString();
praznoPolje(editTelefonNarucioca);
EditText editAdresaNarucioca = (EditText) findViewById(R.id.adresa);
String adresaNarucioca = editAdresaNarucioca.getText().toString();
praznoPolje(editAdresaNarucioca);
EditText editGradNarucioca = (EditText) findViewById(R.id.grad);
String gradNarucioca = editGradNarucioca.getText().toString();
praznoPolje(editGradNarucioca);
EditText editKolicina = (EditText) findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
int kolicina = Integer.parseInt(narucenaKolicina);
praznoPolje(editKolicina);
int cenaNarudzbine = cena(kolicina);
String poruka = sumiranjeNarudzbine(imeNarucioca, prezimeNarucioca, telefonNarucioca, adresaNarucioca, gradNarucioca, cenaNarudzbine);
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
smsIntent.putExtra("address", "+1111111");
smsIntent.putExtra("sms_body", poruka);
if(imeNarucioca!=null && imeNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Unesite ime", Toast.LENGTH_LONG).show();
}
else if(prezimeNarucioca!=null && prezimeNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite Prezime", Toast.LENGTH_LONG).show();
}
else if(telefonNarucioca!=null && telefonNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite kontakt telefon", Toast.LENGTH_LONG).show();
}
else if(adresaNarucioca!=null && adresaNarucioca.equals("")){
Toast.makeText(Narudzbina.this,"Unesite adresu",Toast.LENGTH_LONG).show();
}
else if(gradNarucioca!=null && gradNarucioca.equals("")){
Toast.makeText(Narudzbina.this, "Navedite grad", Toast.LENGTH_LONG).show();
}
else if(narucenaKolicina!=null && narucenaKolicina.equals("")){
Toast.makeText(Narudzbina.this, "Navedite zeljenu kolicinu", Toast.LENGTH_LONG).show();
}
else{
startActivity(smsIntent);
}
}
English is not my native language so do apologize for spelling mistakes or some lack of clarity in the matter, I'd be happy to explain it if necessary.
Your problem is on this line
int kolicina = Integer.parseInt(narucenaKolicina);
If the input is empty, it will try to parse an empty string "". You need to wrap this in an if statement to check if narucenaKolicina is empty or a valid int before you try to parse it.
Tip for you to ignore this exeception:
EditText editKolicina = (EditText) findViewById(R.id.kolicina);
String narucenaKolicina = editKolicina.getText().toString();
if(!narucenaKolicina.isEmpty())
int kolicina = Integer.parseInt(narucenaKolicina);
else
Toast.makeText(Narudzbina.this, "Don't leave this field empty", Toast.LENGTH_LONG).show();
You need to check if your string have empty text, not only null value or 0.
You have to do something like this
kolicina.equals("");
The exception is caused by the parseInt() method so change kolicina to integer is not useful
You should try something like this :
if (narucenaKolicina != null && !narucenaKolicina.toString().trim().equals(""))
As condition to avoid "" string.

IntelliJ - Class is recognized when creating object, but methods are won't autocomplete or compile

I've got a class defined in a .java file outside of the main activity as follows.
package com.example.someGuy.numbershapes;
class Number {
public int input;
public boolean isSquare(){
int sqrtOfInput = (int) Math.sqrt(input);
if (input == sqrtOfInput * sqrtOfInput) return true;
else return false;
}
public boolean isTriangle(){
int sqrtOfInput = (int) Math.sqrt(input * 2);
if (input == sqrtOfInput * (sqrtOfInput + 1)/2) return true;
else return false;
}
}
I then try to access it from the main activity like this.
package com.example.someGuy.numbershapes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Number myNumber = new Number();
myNumber.input = 22;
if (myNumber.isTriangular()){
//do something
}
else if (myNumber.isSquare()){
//do something else
}
}
When I try to run/build the project in IntelliJ, I get an error saying that there is an identifier expected, and illegal start of type error. What am I doing wrong? I was able to get this class to behave as an object in browxy. What am I doing wrong in this case? I'm trying to set the input to a text field in the layout and get it to run through the functions I have defined so that I can determine if the number input by the user is triangular, a perfect square, both or neither.
You need to put this code
myNumber.input = 22;
if (myNumber.isTriangular()){
//do something
}
else if (myNumber.isSquare()){
//do something else
}
inside the onCreate method, as statements have to appear in a block of code. (The block would be a method for the example)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Number myNumber = new Number();
myNumber.input = 22;
if (myNumber.isTriangular()){
//do something
}
else if (myNumber.isSquare()){
//do something else
}
}

Comparing strings in Java

Im trying to compare the values of two edittext boxes. What i would like is to just compare passw1 = passw2. As my code is now comparing two strings i have entered as i could not get to compare them.
final EditText passw1= (EditText) findViewById(R.id.passw1);
final EditText passw2= (EditText) findViewById(R.id.passw2);
Button buttoks = (Button) findViewById(R.id.Ok);
buttoks.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (passw1.toString().equalsIgnoreCase("1234") && passw2.toString().equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplication(),"Username and password doesn't match", Toast.LENGTH_SHORT).show();
}
} });
Using the == operator will compare the references to the strings not the string themselves.
Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.
String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();
if (passwd1Text.equals(passwd2Text))
{
}
[EDIT]
I made a mistake earlier, because, to get the text, you need to use .getText().toString().
Here is a full working example:
package com.psegina.passwordTest01;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class Main extends Activity implements OnClickListener {
LinearLayout l;
EditText user;
EditText pwd;
Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
l = new LinearLayout(this);
user = new EditText(this);
pwd = new EditText(this);
btn = new Button(this);
l.addView(user);
l.addView(pwd);
l.addView(btn);
btn.setOnClickListener(this);
setContentView(l);
}
public void onClick(View v){
String u = user.getText().toString();
String p = pwd.getText().toString();
if( u.equals( p ) )
Toast.makeText(getApplicationContext(), "Matches", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), user.getText()+" != "+pwd.getText(), Toast.LENGTH_SHORT).show();
}
}
Original answer (Will not work because of the lack of toString())
Try using .getText() instead of .toString().
if( passw1.getText() == passw2.getText() )
#do something
.toString() returns a String representation of the whole object, meaning it won't return the text you entered in the field (see for yourself by adding a Toast which will show the output of .toString())
In onclik function replace first line with this line u will definitely get right result.
if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){
You can compare the values using equals() of Java :
public void onClick(View v) {
// TODO Auto-generated method stub
s1=text1.getText().toString();
s2=text2.getText().toString();
if(s1.equals(s2))
Show.setText("Are Equal");
else
Show.setText("Not Equal");
}
You need both getText() - which returns an Editable and toString() - to convert that to a String for matching.
So instead of: passw1.toString().equalsIgnoreCase("1234")
you need passw1.getText().toString().equalsIgnoreCase("1234").
ou can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
You can use String.compareTo(String) that returns an integer that's negative (<), zero(=) or positive(>).
Use it so:
String a="myWord";
if(a.compareTo(another_string) <0){
//a is strictly < to another_string
}
else if (a.compareTo(another_string) == 0){
//a equals to another_string
}
else{
// a is strictly > than another_string
}
Try to use .trim() first, before .equals(), or create a new String var that has these things.
did the same here needed to show "success" twice
response is data from PHP
String res=response.toString().trim;
Toast.makeText(sign_in.this,res,Toast.LENGTH_SHORT).show();
if ( res.compareTo("success")==0){
Toast.makeText(this,res,Toast.LENGTH_SHORT).show();
}
String password=passw1.trim();
if (password.equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
You need to use the trim method in the String

Categories