Button causes Fatal Exception: main, and how to insert "$" - java

I'm programming a gas calculator that has two outputs (Total Cost of Gas and Total Gallons); how can I put a "$" in front of totalCost but not in front of totalGas?
Also when I run the program in the emulator, when I click on the reset button it force closes the program and I get a FATAL EXCEPTION: main error.
EDIT: I figured it out. I forgot to import myClickHandler on the reset button.
Here's the java file:
package com.example.gas;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import com.example.gas.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity
{
private EditText totalMiles;
private EditText price;
private EditText mpg;
private TextView totalGas;
private TextView totalCost;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalMiles = (EditText) findViewById(R.id.milesTxt);
totalCost = (EditText) findViewById(R.id.costTxt);
totalGas = (EditText) findViewById(R.id.gasTxt);
price = (EditText) findViewById(R.id.priceTxt);
mpg = (EditText) findViewById(R.id.mpgTxt);
}
public void myClickHandler(View view)
{
NumberFormat nf = new DecimalFormat("#,###.00");
switch (view.getId())
{
case R.id.calcBtn:
float inputMiles = Float.parseFloat(totalMiles.getText().toString());
float inputMPG = Float.parseFloat(mpg.getText().toString());
float inputPrice = Float.parseFloat(price.getText().toString());
float result1 = inputMiles/inputMPG;
String output1 = nf.format(result1);
totalGas.setText(output1);
float result = result1 * inputPrice;
String output = nf.format(result);
totalCost.setText(output);
break;
case R.id.resetBtn:
totalMiles.setText("");
totalCost.setText("");
totalGas.setText("");
price.setText("");
mpg.setText("");
break;
}
}
}

You should pre-pend it to the String variable:
totalCost.setText(output);
to
totalCost.setText("$"+output);

Related

Logic is off somewhere, trying to get input from user between 1-100

I am making a calculator and I am stumped on this part. I want to have the value inputted from the user for inputG only to be between numbers 1-100. Then, grab that value and use it in a formula.
My logic is off somewhere and I need help finding what I did wrong. I am using Java, not Kotlin.
package com.example.rvbtcal;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView inputMoles = (EditText) findViewById(R.id.txtMoles);
EditText inputML = (EditText) findViewById(R.id.txtmL);
EditText inputG = (EditText) findViewById(R.id.txtG);
TextView outputAnswer = (TextView) findViewById(R.id.txtAnswer);
Button btnCalculate = (Button) findViewById(R.id.btnCalculate);
Spinner spinner = (Spinner) findViewById(R.id.spnN);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.arrayN, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
double iM = Double.parseDouble(inputMoles.getText().toString());
double iML = Double.parseDouble(inputML.getText().toString());
double ioA = Double.parseDouble(inputG.getText().toString());
double textN = Double.parseDouble(spinner.getSelectedItem().toString());
if (ioA >= 0 || ioA <= 101){
Toast.makeText(MainActivity.this,"Enter a number between 1-100", Toast.LENGTH_SHORT);
}
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double Answer1 = (iM * iML * textN) / (ioA / 1000);
double FinalAnswer=(Answer1*1000000);
outputAnswer.setText(String.format("%.3f",FinalAnswer));
// String FinalAnswer2=String.valueOf(FinalAnswer);
// outputAnswer.setText(FinalAnswer2);
}
});
}
}
I now have my code like this below, however, the calculations are still made even with the If statement. I tried an else statement but then the answer is blank no matter if the numbers for input g fall within the parameters.
package com.example.rvbtcal;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView inputMoles = (EditText) findViewById(R.id.txtMoles);
EditText inputML = (EditText) findViewById(R.id.txtmL);
EditText inputG = (EditText) findViewById(R.id.txtG);
TextView outputAnswer = (TextView) findViewById(R.id.txtAnswer);
Button btnCalculate = (Button) findViewById(R.id.btnCalculate);
Spinner spinner = (Spinner) findViewById(R.id.spnN);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.arrayN, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double iM = Double.parseDouble(inputMoles.getText().toString());
double iML = Double.parseDouble(inputML.getText().toString());
double ioA = Double.parseDouble(inputG.getText().toString());
double textN = Double.parseDouble(spinner.getSelectedItem().toString());
if (ioA < 0 || ioA > 100) {
Toast.makeText(MainActivity.this, "Enter a number between 1-100", Toast.LENGTH_SHORT);
}
double Answer1 = (iM * iML * textN) / (ioA / 1000);
double FinalAnswer = (Answer1 * 1000000);
outputAnswer.setText(String.format("%.3f", FinalAnswer));
}
});
}
}
My final code for others who may struggle with this in the future here is the finished product (for now):
package com.example.rvbtcal;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView inputMoles = (EditText) findViewById(R.id.txtMoles);
EditText inputML = (EditText) findViewById(R.id.txtmL);
EditText inputG = (EditText) findViewById(R.id.txtG);
TextView outputAnswer = (TextView) findViewById(R.id.txtAnswer);
Button btnCalculate = (Button) findViewById(R.id.btnCalculate);
Spinner spinner = (Spinner) findViewById(R.id.spnN);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.arrayN, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
btnCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double iM = Double.parseDouble(inputMoles.getText().toString());
double iML = Double.parseDouble(inputML.getText().toString());
double ioA = Double.parseDouble(inputG.getText().toString());
double textN = Double.parseDouble(spinner.getSelectedItem().toString());
if (ioA <= 0 || ioA > 100) {
Toast.makeText(MainActivity.this, "Enter a number between 1-100", Toast.LENGTH_LONG).show();
outputAnswer.setText("");
return;
}
double Answer1 = (iM * iML * textN) / (ioA / 1000);
double FinalAnswer = (Answer1 * 1000000);
outputAnswer.setText(String.format("%.3f",FinalAnswer));
}
});
}
}
You need to move the following lines into the btnCalculate.setOnClickListener,
double iM = Double.parseDouble(inputMoles.getText().toString());
double iML = Double.parseDouble(inputML.getText().toString());
double ioA = Double.parseDouble(inputG.getText().toString());
double textN = Double.parseDouble(spinner.getSelectedItem().toString());
if (ioA < 1 || ioA > 100) {
Toast.makeText(MainActivity.this,"Enter a number between 1-100", Toast.LENGTH_SHORT).show();
return;
}
You need to get the user input after the user taps on the btnCalculate because that's where you can get the latest input of the user.
What you are doing is fetching the value as soon as the EditText view is being created. Hence it returns an empty string. And when you try to pass an empty string to double it should give you an Exception. Unless you have assigned a text value to the EditText in your XML.

EditText all possible number in random output in Android

I'm new to Android. I'm developing an app which gives all the possible combination number based on the user input and separated it by comma.
For example the user input is: 1234
The output should be list all the possible number combination from "1234" like
"1234,1243,1324,1342,1423,1432,2134,etc.."
And there's also another EditText that limit the output by setting it to 1 or 2 or 3 or 4(max).
For example the user input is: 2
The output should be list all the possible number combination from "1234" by "2" digits
"12,13,14,21,23,24,31,32,34,41,42,43"
This is my MainActivity.java
package com.example.androidtest1;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
EditText et_input1, et_output1;
Button b_generate, b_clear;
CheckBox checkBox1;
Random r;
int min,output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText mEdit = (EditText) findViewById(R.id.et_output1);
mEdit.setEnabled(false);
r = new Random();
et_input1 = (EditText) findViewById(R.id.et_input1);
et_output1 = (EditText) findViewById(R.id.et_output1);
b_generate = (Button) findViewById(R.id.b_generate);
b_clear = (Button) findViewById(R.id.b_clear);
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
b_generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (et_input1.length()==0){
et_input1.setError("Insert numbers");
}else if(checkBox1.isChecked()){
min = Integer.parseInt(et_input1.getText().toString());
output = (min);
et_output1.setText("" + output + "*");
et_input1.setError(null);
}
else{
et_input1.setError("Check the checkbox");
}
}
});
b_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
et_output1.getText().clear();
et_input1.getText().clear();
return;
}
});
}
}

NumberFormatException: empty String ; Double.parseDouble

My app keeps crashing and gives me a:
java.lang.NumberFormatException: empty String
Also says this
FATAL EXCEPTION: main
Process: com.example.ayyan.jellybeanestimator, PID: 2966
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ayyan.jellybeanestimator/com.example.ayyan.jellybeanestimator.MainActivity}: java.lang.NumberFormatException: empty String
package com.example.ayyan.jellybeanestimator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class MainActivity extends AppCompatActivity {
EditText jellyBeanLength, jellyBeanDiameter, jarSizeVolume;
double jellybeantall, jellybeanfat, jellybeanspace, volumeOfOneJellyBean, volumeofBeans;
final double loadFactor = .698;
TextView answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jellyBeanLength = (EditText) findViewById (R.id.length);
jellyBeanDiameter = (EditText) findViewById (R.id.diameter);
jarSizeVolume = (EditText) findViewById (R.id.jarsize);
jellybeantall = Double.parseDouble(jellyBeanLength.getText().toString());
jellybeanfat = Double.parseDouble(jellyBeanDiameter.getText().toString());
jellybeanspace = Double.parseDouble(jarSizeVolume.getText().toString());
answer = (TextView) findViewById (R.id.answer);
Button calculate = (Button) findViewById (R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
volumeOfOneJellyBean = ((3.14159265359/6)*(jellybeanfat*jellybeanfat)*jellybeantall);
volumeofBeans = (jellybeanspace*loadFactor)/volumeOfOneJellyBean;
int jellyguess = (int) (volumeofBeans);
answer.setText("You have this amount of beans in your jar" + jellyguess);
}
});
}
}
jellybeantall = Double.parseDouble(jellyBeanLength.getText().toString());
jellybeanfat = Double.parseDouble(jellyBeanDiameter.getText().toString());
jellybeanspace = Double.parseDouble(jarSizeVolume.getText().toString());
All your EditTexts start as empty. You can't getText() in onCreate, you have to do it in onClick
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jellybeantall = Double.parseDouble(jellyBeanLength.getText().toString());
jellybeanfat = Double.parseDouble(jellyBeanDiameter.getText().toString());
jellybeanspace = Double.parseDouble(jarSizeVolume.getText().toString());
volumeOfOneJellyBean = ((3.14159265359/6)*(jellybeanfat*jellybeanfat)*jellybeantall);
volumeofBeans = (jellybeanspace*loadFactor)/volumeOfOneJellyBean;
int jellyguess = (int) (volumeofBeans);
answer.setText("You have this amount of beans in your jar" + jellyguess);
}
});
Note: when volumeOfOneJellyBean == 0, you'll get a division by zero error

Currency app needs update

I just need som minor help now. The app runs great but when you enter for ex. USD, 2 TO SEK it results 13,38. But if i change the amount to 3 nothing happens. I would have to change the currencys back and forth to make a change. I would like the app to change the result as soon as i change the value. Please help!:)
package com.example.currencyconverter;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private String [] currency_name;
private ArrayAdapter<String> adapter;
private Spinner spin1, spin2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpTheSpinners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
private void setUpTheSpinners() {
currency_name = getResources().getStringArray(R.array.currency_name);
adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, currency_name);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
OnItemSelectedListener listener = new CurrencySelectedListener();
spin1 = (Spinner)findViewById(R.id.spinner1);
spin1.setAdapter(adapter);
spin1.setOnItemSelectedListener(listener);
spin2 = (Spinner)findViewById(R.id.spinner2);
spin2.setAdapter(adapter);
spin2.setOnItemSelectedListener(listener);
}
private void calculateSum() {
String [] rates = getResources().getStringArray(R.array.currency_rate);
int index1 = spin1.getSelectedItemPosition();
int index2 = spin2.getSelectedItemPosition();
double rate1 = Double.parseDouble( rates[index1] );
double rate2 = Double.parseDouble( rates[index2] );
EditText editAmount = (EditText) findViewById(R.id.editText1);
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
double amount = Double.valueOf(editAmount.getText().toString());
double totalRate = amount * rate1 / rate2;
TextView totalRateText = (TextView)findViewById(R.id.editText2);
totalRateText.setText("" + totalRate);
}
}
private class CurrencySelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
calculateSum();
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
Your editAmount.getText().toString() value is NULL(empty). And you still trying to convert this value into DOUBLE so you got NumberFormatException .
Check editText value before parsing like:
if(!editAmount.getText().toString().equals(""))
{
//Do your job
}
Or another way is
if (!TextUtils.isEmpty(editAmount.getText().toString())) {
//Do your job
}

why does my code crash

So I am running a tutorial app, and it all works except when I try to run the bellow class, however I don't get errors in the code so I was wondering if anyone could help if there is maybe something wrong with the code.
Also on a side not when programming for example you type say: android: in the xml or something. in java how come I don't get the drop down menu with all the options of what can go after?
code:
package com.example.learn.tam;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class textplay extends Activity implements View.OnClickListener{
Button chkCommand;
ToggleButton passToggle;
EditText input;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
holder();
passToggle.setOnClickListener(this);
chkCommand.setOnClickListener(this);
}
private void holder() {
Button chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bResults:
String check = input.getText().toString();
display.setText(check);
if(check.contentEquals("left")){
display.setGravity(Gravity.LEFT);
}
else if(check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
}
else if(check.contentEquals("right")){
display.setGravity(Gravity.RIGHT);
}
else if(check.contentEquals("blue")){
display.setTextColor(Color.BLUE);
}
else if(check.contentEquals("WTF")){
Random crazy = new Random();
display.setText("WTF!!!!");
display.setTextSize(crazy.nextInt(75));
display.setTextColor(Color.rgb(crazy.nextInt(265),crazy.nextInt(265),crazy.nextInt(265)));
switch(crazy.nextInt(3)){
case 0:
display.setGravity(Gravity.LEFT);
break;
case 1:
display.setGravity(Gravity.CENTER);
break;
case 2:
display.setGravity(Gravity.RIGHT);
break;
}
}
else{
display.setText("Invalid");
display.setGravity(Gravity.CENTER);
display.setTextColor(Color.WHITE);
}
break;
case R.id.tbPassword:
if (passToggle.isChecked() == true){
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}else{
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
break;
}
}
}
Change:
private void holder() {
Button chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
To
private void holder() {
chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
By declaring a new variable with the same name, you were hiding the class field. Due to this, the class level chkCommand remained null, and gave you an exception when you tried to use chkCommand.setOnClickListener(this);.

Categories