java.lang.NumberFormatException: Invalid double: "" Edit Text [duplicate] - java

This question already has answers here:
java.lang.numberformatexception: invalid double: " "
(6 answers)
Closed 6 years ago.
I have 6 edit text fields, and I'm trying to input them into a sqlite database and I'm trying to parse 5 of them into doubles, but it throws that error and I can not figure out what to do.
I've tried to use valueOf(String) and parsing, but neither seem to work.
I've used Long's and Integers as well, and have come to the same issue as well
Here's the code:
public class EditClass extends AppCompatActivity {
EditText name, exam, quiz, assignment, participation, lab;
String iName, sExam, sQuiz, sAss, sPart, sLab ;
double iExam, iQuiz, iLab, iAss, iPart;
FloatingActionButton fab;
Database database;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_class);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = (EditText) findViewById(R.id.class_name);
exam = (EditText) findViewById(R.id.exam_weight);
quiz = (EditText) findViewById(R.id.quiz_weight);
assignment = (EditText) findViewById(R.id.assignment_weight);
participation = (EditText) findViewById(R.id.participation_weight);
lab = (EditText) findViewById(R.id.lab_weight);
iName = name.getText().toString();
sExam = exam.getText().toString();
sQuiz = quiz.getText().toString();
sAss = assignment.getText().toString();
sPart = participation.getText().toString();
ImageView create = new ImageView(this);
create.setImageDrawable(getResources().getDrawable(R.drawable.checkmark));
fab = new FloatingActionButton.Builder(this).setContentView(create).build();
fab.setBackground(getResources().getDrawable(R.drawable.button_action_lightblue_ztek));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addData();
}
public void addData(){
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
/**
* Errors with parsing into integer form, comes up with NumberFormatException
*/
database.insertData(iName,
iExam = Double.valueOf(sExam),
iQuiz = Double.valueOf(sQuiz),
iLab = Double.valueOf(sLab),
iAss = Double.valueOf(sAss),
iPart = Double.valueOf(sPart));
Toast.makeText(EditClass.this, "Data was Successfully Inserted", Toast.LENGTH_SHORT).show();
}catch (Exception e){
String error= e.toString();
Toast.makeText(EditClass.this, "Data was Not Inserted", Toast.LENGTH_SHORT).show();
System.out.println(error);
}
}
});
}}
I've now ended up changing the addData method to this, but it comes up as null now, for both the string and doubles.
Here's the method:
public void addData(){
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
/**
* Errors with parsing into integer form, comes up with NumberFormatException
*/
database.insertData(name.getText().toString(),
Double.parseDouble(exam.getText().toString()),
Double.parseDouble(quiz.getText().toString()),
Double.parseDouble(lab.getText().toString()),
Double.parseDouble(assignment.getText().toString()),
Double.parseDouble(participation.getText().toString()));
Toast.makeText(EditClass.this, "Data was Successfully Inserted", Toast.LENGTH_SHORT).show();
}catch (Exception e){
String error= e.toString();
Toast.makeText(EditClass.this, "Data was Not Inserted", Toast.LENGTH_SHORT).show();
System.out.println(error);
}
}
});
}

onCreate() only runs once and is currently the only place you call getText(). Therefore, the values in iName, sExam, etc are all the default values you have for those fields - not the current values when your FloatingActionButton is clicked.
Instead, move the iName = name.getText().toString(); etc lines into your OnClickListener to get the current values when the button is clicked.
Also note that you cannot use Double.valueOf() on an empty field (that's the NumberFormatException you are getting) - consider wrapping each call in TextUtils.isEmpty() to check to see if there is any value at all.

Related

How do I take a number input, change it, then out put it, with submit button?

I am completely lost and don't have enough knowledge on coding/android studio.
I have the EditTexts (FoodIncomeCounter, FoodCampX, and FoodUpgradeX) as inputs.
Then the TextView (FoodIncomeResult) as output.
The 1st button (IncomeSubmitButton) Works properly. The 2nd button (FoodCampSubmitButton) does not, I want it to take the input of the FoodCampXs and FoodUpgradeXs then do a calculation and put that into integer TotalFood, then output TotalFood to the FoodIncomeResult TextView.
How the heck do I do this? I feel like I am close but I don't know what is wrong.
Thank you for the help!!!
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText FoodIncomeCounter;
EditText FoodCamp1Counter, FoodCamp2Counter, FoodCamp3Counter, FoodUpgrade1Counter, FoodUpgrade2Counter, FoodUpgrade3Counter;
TextView FoodIncomeResult;
int FoodIncome;
int FoodCamp1, FoodCamp2, FoodCamp3, FoodUpgrade1, FoodUpgrade2, FoodUpgrade3;
int TotalFood;
Button IncomeSubmitButton, FoodCampSubmitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//to get from user input and into variable form
FoodIncomeCounter = (EditText) findViewById(R.id.FoodIncomeCounter);
FoodIncomeResult = (TextView) findViewById(R.id.FoodIncomeResult);
IncomeSubmitButton = (Button) findViewById(R.id.IncomeSubmitButton);
FoodCamp1Counter = (EditText) findViewById(R.id.FoodCamp1Counter);
FoodCamp2Counter = (EditText) findViewById(R.id.FoodCamp2Counter);
FoodCamp3Counter = (EditText) findViewById(R.id.FoodCamp3Counter);
FoodUpgrade1Counter = (EditText) findViewById(R.id.FoodUpgrade1Counter);
FoodUpgrade2Counter = (EditText) findViewById(R.id.FoodUpgrade2Counter);
FoodUpgrade3Counter = (EditText) findViewById(R.id.FoodUpgrade3Counter);
FoodCampSubmitButton = (Button) findViewById(R.id.FoodCampSubmitButton);
//Submit button
IncomeSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to receive the inputted values
Food = Integer.parseInt(FoodIncomeCounter.getText().toString());
//to show the inputted values into the result fields
FoodIncomeResult.setText(FoodIncomeCounter.getText().toString());
}
});
//Submit button
FoodCampSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//receive the inputted values
FoodCamp1 = Integer.parseInt(FoodCamp1Counter.getText().toString());
FoodCamp2 = Integer.parseInt(FoodCamp2Counter.getText().toString());
FoodCamp3 = Integer.parseInt(FoodCamp3Counter.getText().toString());
FoodUpgrade1 = Integer.parseInt(FoodUpgrade1Counter.getText().toString());
FoodUpgrade2 = Integer.parseInt(FoodUpgrade2Counter.getText().toString());
FoodUpgrade3 = Integer.parseInt(FoodUpgrade3Counter.getText().toString());
//get food income and show
TotalFood = FoodCamp1 + (FoodCamp2 * 2) + (FoodCamp3 * 3) + (FoodUpgrade1 * 2) + (FoodUpgrade2 * 4) + (FoodUpgrade3 * 6);
FoodIncomeResult.setText(String.valueOf(TotalFood));
}
});
}
}

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 do i make a button take text from an edittext and compare it to a random number?

I'm trying to make my button compare the number in the edit text to the random number I'm generating and make a toast if they're the same. the code runs but no matter what i set the bound to the number in the edit text never equals the random number.
Here is my code
Button submit;
EditText etcode;
Random random = new Random();
String generatedPassword = String.format(String.valueOf(random.nextInt(1)));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
mFlower = findViewById(R.id.ivImage);
mDescription = findViewById(R.id.tvDescription);
submit = (Button) findViewById(R.id.btn_submit);
etcode = findViewById(R.id.et_code);
Bundle mBundle = getIntent().getExtras();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (etcode.getText().toString().equals(generatedPassword)){
Toast.makeText(getApplicationContext(), "CONGRATS", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "TRY AGAIN", Toast.LENGTH_SHORT).show();
}
}
});
Change this line
String generatedPassword = String.format(String.valueOf(random.nextInt(1)));
Because generatePassword is always 0 . That's why it works with zero.
random.nextInt(1);
Above code will always generate number less than 1.
You should change it to any other number.
Suppose you writerandom.nextInt(5);
Then above line will generate number between 0 to 5 means it can be 0,1,2,3,4.
Check this link https://www.geeksforgeeks.org/java-util-random-nextint-java/

Android app crashes when trying to use variable [duplicate]

#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.screenlocked);
//Retrieve stored ID
final String STORAGE = "Storage";
SharedPreferences unique = getSharedPreferences(STORAGE, 0);
LoginID = unique.getString("identifier", "");
//Retrieve stored phone number
final String phoneNumber = unique.getString("PhoneNumber", "");
phoneView = (TextView) findViewById(R.id.phone);
phoneView.setText(phoneNumber.toString());
//Retrieve user input
input = (EditText) findViewById(R.id.editText1);
userInput = input.getText().toString();
//Set login button
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
compareID();
}
});
}
public void compareID(){
if (userInput.equals(LoginID)){
//phone screen unlocked
//continue
Toast.makeText(ScreenLockActivity.this, "Success!", Toast.LENGTH_SHORT).show();
}
else{
count += 1;
input.setText("");
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
}
}
I am developing a login activity and I would like to record down how many times the user tried to login, so every time there is a login attempt the count will increment by one... but when i run the activity, this error appears in my logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1,
Can someone help me solve this problem?
Here is your mistake:
Toast.makeText(ScreenLockActivity.this, count, Toast.LENGTH_SHORT).show();
the makeText you are trying to invoke here, is the makeText that takes as second parameter a resId. See here for more info. Since you want to print the count value, you have to convert it in a String.
String value = String.valueOf(count);
Toast.makeText(ScreenLockActivity.this, value, Toast.LENGTH_SHORT).show();
This line should be inside onClick() or compareID():
userInput = input.getText().toString();

How to disable a button in onCreate method with if statment [duplicate]

This question already has answers here:
How to disable an Android button?
(13 answers)
Closed 5 years ago.
I have a problem, I want to disable a button in onCreate method, please share the way of disabling any button at runtime in onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_requests_interface);
Intent intent = new Intent(this, AdminPopup.class);
startActivity(intent);
String fName = getIntent().getStringExtra("fName");
TextView tfName = (TextView)findViewById(R.id.fName);
tfName.setText(fName);
String vuEmail = getIntent().getStringExtra("VUEmail");
TextView tEmail = (TextView)findViewById(R.id.vuEmail);
tEmail.setText(vuEmail);
EditText vuEmailTest = (EditText)findViewById(R.id.vuEmail);
String email = vuEmailTest.getText().toString();
String str = email.substring(0,2);
if(str.equals("bc")){
String str2 = email.substring(3,9);
boolean digitsOnly = TextUtils.isDigitsOnly(str2);
if (digitsOnly){
Button accButton = (Button)findViewById(R.id.accButton);
}
}
else{
Button accButton = (Button)findViewById(R.id.accButton);
}
}
Try this:
Button accButton = (Button) findViewById(R.id.accButton);
accButton.setEnabled(false);
Note that in your posted code, you are setting the button with findViewbyId(), which should be findViewById() (the By needs to be capitalized).
Button button =(Button) findViewById(R.id.buttonid);
button.setVisibility(View.GONE);
Use android:enabled="false" in xml or accButton.setEnabled(false) in code
Also, it's better to check is numeric by this method:
public static boolean isNumeric(String str) {
try {
double d = Double.parseDouble(str);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
Do this:
Button b = (Button) findViewById(R.id.mybutton);
b.setEnabled(false);

Categories

Resources