onclick i get null - android

ok i want my script to give me an answer on the first click but it takes me multiple clicks.
`package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class EquationsActivity extends Activity {
EditText field1;
EditText field2;
EditText field3;
EditText field4;
TextView text1;
TextView text2;
TextView text3;
String fnum;
String snum;
String tnum;
String ftnum;
String RAnswer;
String Answer;
String answer;
double num7;
double num8;
double num9;
double num10;
double num5;
double num4;
double num3;
double num6;
double num1;
double num2;
double num11;
double num12;
double num13;
double num14;
double num15;
String num16;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
field1 = (EditText) findViewById(R.id.tf1);
field2 = (EditText) findViewById(R.id.tf2);
field3 = (EditText) findViewById(R.id.tf3);
field4 = (EditText) findViewById(R.id.tf4);
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
text3 = (TextView) findViewById(R.id.text3);
button1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
text1.setText(RAnswer);
text2.setText(Answer);
text3.setText(answer + "," + num16);
fnum = field1.getText().toString();
snum = field2.getText().toString();
tnum = field3.getText().toString();
ftnum = field4.getText().toString();
RAnswer = Double.toString(num7);
Answer = Double.toString(num11);
answer = Double.toString(num14);
num16 = Double.toString(num15);
num1 = Double.parseDouble(fnum);
num2 = Double.parseDouble(snum);
num3 = Double.parseDouble(tnum);
num4 = Double.parseDouble(ftnum);
num5 = num2 - num1;
num6 = num4 - num3;
num7 = num6 / num5;
num8 = Math.pow(num2-num1,2);
num9 = Math.pow(num4-num3, 2);
num10 = num8+num9;
num11 = Math.sqrt(num10);
num12 = num1+num2;
num13 = num3+num4;
num14 = num12/2;
num15 = num13/2;
}
});
}
}`

Are you sure it takes you several clicks? There is some math in there that could potentially take some time. To debug, add this line at the beginning of the onClick method:
Log.i("button", "onClick called");
Now when you select the button, if this log message shows up in your LogCat, then the button is responding to the first click.
Edit:
Have you tried moving some of the method components around?
#Override
public void onClick(View v) {
fnum = field1.getText().toString();
snum = field2.getText().toString();
tnum = field3.getText().toString();
ftnum = field4.getText().toString();
num1 = Double.parseDouble(fnum);
num2 = Double.parseDouble(snum);
num3 = Double.parseDouble(tnum);
num4 = Double.parseDouble(ftnum);
num5 = num2 - num1;
num6 = num4 - num3;
num7 = num6 / num5;
num8 = Math.pow(num2-num1,2);
num9 = Math.pow(num4-num3, 2);
num10 = num8+num9;
num11 = Math.sqrt(num10);
num12 = num1+num2;
num13 = num3+num4;
num14 = num12/2;
num15 = num13/2;
RAnswer = Double.toString(num7);
Answer = Double.toString(num11);
answer = Double.toString(num14);
num16 = Double.toString(num15);
text1.setText(RAnswer);
text2.setText(Answer);
text3.setText(answer + "," + num16);
}

Related

About the "unfortunately has stopped" error.

I am recently building an app that calculates the mortgage as my school project in Android studio using Java. However, when I try to run the app on my tablet, it keeps crashing and appearing "unfortunately the app has stopped". I wonder what's wrong with my codes, the below are my codes.
This is my controller:
package ca.roumani.mcalc;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import hr.YumModel;
public class EntryForum extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_forum);
}
public void buttonClicked(View v)
{
View principleView = findViewById(R.id.principlebox);
EditText principleEdit = (EditText) principleView;
String principle = principleEdit.getText().toString();
View amortizationView = findViewById(R.id.amortizationbox);
EditText amortizationEdit = (EditText) amortizationView;
String amortization = amortizationEdit.getText().toString();
View annualinterestView = findViewById(R.id.interestbox);
EditText annualinterestEdit = (EditText) annualinterestView;
String annualinterest = annualinterestEdit.getText().toString();
MortgageModel model = new MortgageModel(principle, amortization, annualinterest);
String answer = model.computePayment();
((TextView) findViewById(R.id.answer)).setText( "$" + answer);
}
public void yumButton(View v)
{
View principleView = findViewById(R.id.principlebox);
EditText principleEdit = (EditText) principleView;
String principle = principleEdit.getText().toString();
View amortizationView = findViewById(R.id.amortizationbox);
EditText amortizationEdit = (EditText) amortizationView;
String amortization = amortizationEdit.getText().toString();
View annualinterestView = findViewById(R.id.interestbox);
EditText annualinterestEdit = (EditText) annualinterestView;
String annualinterest = annualinterestEdit.getText().toString();
YumModel yumModel = new YumModel();
yumModel.setAmortization(amortization);
yumModel.setInterest(annualinterest);
yumModel.setPrinciple(principle);
String answer2 = yumModel.computePayment();
((TextView) findViewById(R.id.answer2)).setText(answer2);
}
}
The following is my model:
public class MortgageModel
{
private double principle;
private int amortization;
private double annualInterest;
public MortgageModel(String p, String a, String i)
{
this.principle = Double.parseDouble(p);
this.amortization = Integer.parseInt(a);
this.annualInterest = Double.parseDouble(i);
}
public String computePayment()
{
double r = this.annualInterest * 0.01 / 12 ;
double n = this.amortization * 12;
double index1 = 1 + (n * r) + (n * (n-1) * r * r) / 2;
double index2 = 1 - (1 / index1);
double index3 = (r * this.principle) / index2;
String result = String.format("%.d", index3);
return result;
}
}
Does anyone know what's wrong with my code?

how to set the button so as not to force close when empty EditText [duplicate]

getting an error of invalid Double
java.lang.numberformatexception invalid double: ""
what is the reason for this
Activity 1
package com.example.solarcalculator;
import android.os.Bundle;
import android.widget.Button;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
#SuppressLint("UseValueOf")
public class MainActivity extends Activity {
private EditText input1;
private EditText input2;
private EditText input3;
private EditText input4;
private EditText input5;
private MainActivity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
input5 = (EditText) findViewById(R.id.input5);
Button button1 = (Button) findViewById(R.id.button1);
input4 = (EditText) findViewById(R.id.input4);
input1 = (EditText) findViewById(R.id.input1);
input2 = (EditText) findViewById(R.id.input2);
input3 = (EditText) findViewById(R.id.input3);
button1.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unused")
private AlertDialog show;
#SuppressLint("UseValueOf")
#Override
public void onClick(View arg0) {
if ( (input4.getText().toString() == " ")
|| (input4.getText().length() ==0) ||
(input5.getText().length() == 0)
|| (input5.getText().toString() == " ")){
show = new AlertDialog.Builder(mContext).setTitle("Error")
.setMessage("Some inputs are empty")
.setPositiveButton("OK", null).show();
}
else if ((input1.getText().length() != 0) &&
(input3.getText().length() ==0) && (input2.getText().length() == 0)){
double w = new Double(input3.getText().toString());
double t = new Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
float e = 7;
double num = 1000*x;
double den = w*t*e;
double payback = num/den;
double money = w*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
else if ((input1.getText().length() == 0) && (input3.getText().length() != 0) &&
(input2.getText().length() != 0)){
double t = new
Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
double v = new Double(input2.getText().toString());
double i = new Double(input3.getText().toString());
float e = 7;
double num = 1000*x;
double den = v*i*t*e;
double payback = num/den;
double money = v*i*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
else {
double t = new Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
double v = new Double(input2.getText().toString());
double i = new Double(input3.getText().toString());
float e = 7;
double num = 1000*x;
double den = v*i*t*e;
double payback = num/den;
double money = v*i*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
}
});
}
#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;
}
}
Activity2
package com.example.solarcalculator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
#SuppressLint("NewApi")
public class Power extends Activity {
private double money;
private double payback;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.power);
payback = getIntent().getDoubleExtra("payback",0);
money = getIntent().getDoubleExtra("money", 0);
TextView pay = (TextView) findViewById(R.id.textView2);
String payback1 = Double.toString(payback);
pay.setText(payback1);
TextView mon = (TextView) findViewById(R.id.textView4);
String money1 = Double.toString(money);
mon.setText(money1);
}
}
I am getting java.lang.numberformatexception invalid double: "" error in logcat
anyone please help
The reason is, that "" is not a valid double. You need to test the String before or catch such exceptions
double w;
try {
w = new Double(input3.getText().toString());
} catch (NumberFormatException e) {
w = 0; // your default value
}
The value of the double depends on the language of the device.For example, for devices in french the number 0.179927 becomes 0,179927 which will always throw a NumberFormatException when parsing it to double because of the comma.
You need to change the separator from a comma to a point.
You can change the separator either by setting a locale or using the DecimalFormatSymbols.
If you want the grouping separator to be a point, you can use a european locale:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);
You should do as below. Put it inside a try catch block
double w = new Double(input3.getText().toString());
Better to also test for .equals("") along with null.
Consider you have an afterTextChanged listener on an EditText. When you back press and clear the entered text, it'll pass != null, but still have "".
This worked for me:
double myDouble;
String myString = ((EditText) findViewById(R.id.editText1)).getText().toString();
if (myString != null && !myString.equals("")) {
myDouble = Double.valueOf(myString);
} else {
myDouble = 0;
}
Basically, you need to test whether the string that you want to convert into double is empty or not.
If it is empty, then you can just initialise it with some value and then proceed further.
For example:
if(myString.isEmpty()){
myString = ""+0.0;
}
double answer = Double.parseDouble(myString);
double latitude;
double longitude;
try {
latitude = Double.parseDouble(mApoAppointmentBeanList.get(position).getLatitude());
longitude = Double.parseDouble(mApoAppointmentBeanList.get(position).getLongitude());
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?q=loc:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
} catch (NumberFormatException e) {
// your default value
Toast.makeText(AppointmentsActivity.this, "Invalid location", Toast.LENGTH_LONG).show();
}

sharedPreference or onSaveInstanceState on an EditText/TextView result

I have a little test project below. All I want to do is save the EditText numbers entered and TextView result (thing1, thing2, result) . What's best? onSaveInstanceState, sharedPreference, or something different like SQLite?
I've frustratingly tried the first two (for probably embarrassingly too long), but couldn't figure it out. Could someone please help by adding it to the code below?
public class MainActivity extends ActionBarActivity {
EditText thing1;
EditText thing2;
TextView result;
double n1=0;
double n2=0;
double total=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button divideButton = (Button) findViewById(R.id.divideButton);
divideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
if (n2 !=0){
total = (n1 / n2);}
final double total = ((double)n1/(double)n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1+n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button subtractButton = (Button) findViewById(R.id.subtractButton);
subtractButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1-n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button multiplyButton = (Button) findViewById(R.id.multiplyButton);
multiplyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1*n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
}
If you will just use the values later like when you open your application, you
can use the SharedPreferences. Based on your code above you can add the code below
to save your EditText data to SharedPreferences and restore it later.
To save your EditText value:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("thing1", thing1.getText.toString());
editor.commit();
To get the value from SharedPreferences you can do this in your onCreate function:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
String sValue = sharedPreferences.getString("thing1", "default");
thing1.setText( sValue );

Putting double value into TextView

In my Android app I am calculating a double value using values entered into EditTexts and trying to put the answer into a TextView. My code is this:
double scoreDouble;
TextView score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
String gpaString = gpa.getText().toString();
if(gpaString.equals("")){
gpaString = "0";
}
final double gpaDouble = Double.parseDouble(gpaString);
sat = (EditText) findViewById(R.id.sat);
String satString = sat.getText().toString();
if(satString.equals("")){
satString = "0";
}
final int satInt = Integer.parseInt(satString);
act = (EditText) findViewById(R.id.act);
String actString = act.getText().toString();
if(actString.equals("")){
actString = "0";
}
final int actInt = Integer.parseInt(actString);
score = (TextView) findViewById(R.id.score);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(actInt/36>satInt/2400){
scoreDouble= (0.6*gpaDouble*25)+(0.4*(actInt/36)*100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is "+scoreString);
}else{
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/2400)*100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is "+scoreString);
}
}
});
}
As of now, when the button is pressed the TextView says: "Your score is 0.0." I feel this has something to do with the fact that I set the default values of the EditTexts to 0. Before I did this, I was getting an error stating NumberFormatException: invalid double: "". If this is the problem, how should I fix it. If that is not the problem, what it?
You define the actInt and satInt as final variables, and they will be assigned to a value only once (when the execution of the onCreate method) and the initial value will be zero as at the begining the edittext contain nothing.
To solve this issue:
move he actInt and satInt from local variables to a field variables and remove the final keyword. (I mean define those variables as a private variables inside the class) and assign the values for the variables inside the onclick Method.
public class test extends Activity {
double scoreDouble;
TextView score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
private int satInt;
private int actInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
sat = (EditText) findViewById(R.id.sat);
act = (EditText) findViewById(R.id.act);
score = (TextView) findViewById(R.id.score);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String gpaString = gpa.getText().toString();
if (gpaString.equals("")) {
gpaString = "0";
}
double gpaDouble = Double.parseDouble(gpaString);
String satString = sat.getText().toString();
if (satString.equals("")) {
satString = "0";
}
int satInt = Integer.parseInt(satString);
String actString = act.getText().toString();
if (actString.equals("")) {
actString = "0";
}
int actInt = Integer.parseInt(actString);
if (actInt / 36 > satInt / 2400) {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * (actInt / 36) * 100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is " + scoreString);
} else {
scoreDouble = (0.6 * gpaDouble * 25)
+ (0.4 * (satInt / 2400) * 100);
String scoreString = Double.toString(scoreDouble);
score.setText("Your score is " + scoreString);
}
}
});
}
}
You are doing everything on your onCreate method. So all your code is called at the start of your application. At this moment, your EditTexts are empty and your code goes to these parts:
if(gpaString.equals("")){
gpaString = "0";
}
if(actString.equals("")){
actString = "0";
}
if (actString.equals("")) {
actString = "0";
}
Which means that your values gpaDouble, actInt and satInt are equals 0.
Then, you are doing the following:
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/36)*100);
and this:
scoreDouble = (0.6*gpaDouble*25)+(0.4*(satInt/2400)*100);
With the 0 values, your scoreDouble value can only be equal to 0.
To fix it, get your EditTexts' texts in the onClick method of your Button.

Code for calculating the percentage not working

I don't know how to get the result from the price and percent to show the price after discount!!
// write the percentage
final EditText editPrice = (EditText) findViewById(R.id.editPrice);
// write the price
final EditText ePercent = (EditText) findViewById(R.id.ePercent);
// Hopefully to get the result
final TextView result = (TextView) findViewById(R.id.viewResult);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
double price = Double.valueOf(editPrice.getText()
.toString());
// percent
double per = (price / 100.0f) * ePercent;;
result.setText(String.valueOf(per));
Any Help!
Thanks!
Try this..
// getting value from editPrice and parsing to double
double price = Double.parseDouble(editPrice.getText().toString());
// same like that getting value from ePercent and parsing to double
double ePer = Double.parseDouble(ePercent.getText().toString());
// percent
double per = (price / 100.0f) * ePer;;
result.setText(String.valueOf(per));
// or
result.setText(""+per);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
double price = Double.parseDouble(editPrice.getText()
.toString());
// percent
double ePercent = Double.parseDouble(ePercent.getText()
.toString());
//if ePercent between 0 and 1
double result = price * (1.0f - ePercent);
//if ePercent between 0 and 100
double result = price * ((100.0f - ePercent)/100.0f);
result.setText(String.valueOf(result));
}
}

Categories

Resources