Activity Crashing When editText fields left empty - android

I've seen a few other headings similar to mine , but were mine differs is that the string entered is being parsed to a double and as long as all the editText fields are filled, it works fine, but if one field is left empty it goes back to the last activity! And if I'm honest the error is vague in logcat and I think it talking about the fact there is no intent on the button for the next activity, which I've implemented, but it still crashes, so I'm not sure where I'm going wrong. Any advice would be appreciated, here is my code and the logcat error:
package com.example.siuni.mymedicare;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class weighinscreen extends ActionBarActivity {
private Button result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weighinscreen);
result = (Button) findViewById(R.id.button1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText txtTempC = (EditText) findViewById(R.id.editText1);
String strC = txtTempC.getText().toString();
double TempC = Double.parseDouble(strC);//Parses the string as double
EditText txtTempF = (EditText) findViewById(R.id.editText2);
String strF = txtTempF.getText().toString();
double TempF = Double.parseDouble(strF););//Parses the string as double
EditText txtBPS = (EditText) findViewById(R.id.editText3);
String strBPS = txtBPS.getText().toString();
double BPS = Double.parseDouble(strBPS););//Parses the string as double
EditText txtBPD = (EditText) findViewById(R.id.editText4);
String strBPD = txtBPD.getText().toString();
double BPD = Double.parseDouble(strBPD););//Parses the string as double
EditText txtHeartR = (EditText) findViewById(R.id.editText5);
String strH = txtHeartR.getText().toString();
double HeartR = Double.parseDouble(strH););//Parses the string as double
if (Double.compare(TempC, Double.NaN) == 0) {//Should check the double to see if it null and produce
Toast.makeText(getApplicationContext(), "Please enter your temperature",
Toast.LENGTH_SHORT).show();
result.setEnabled(true);
} else if (Double.compare(TempF, Double.NaN) == 0){//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your temperature",
Toast.LENGTH_SHORT).show();
result.setEnabled(true);
} else if (Double.compare(BPS, Double.NaN) == 0) {//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your blood pressure",
Toast.LENGTH_LONG).show();
result.setEnabled(true);
} else if (Double.compare(BPD, Double.NaN) == 0) {//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your blood pressure",
Toast.LENGTH_LONG).show();
result.setEnabled(true);
} else if (Double.compare(HeartR, Double.NaN) == 0{//Should check the double to see if it null and produce the toast
Toast.makeText(getApplicationContext(), "Please enter your heart rate",
Toast.LENGTH_LONG).show();
result.setEnabled(true);
} else if (TempC <=36 && TempF <= 99 && BPS <= 100 && BPD <= 40 && HeartR <= 60) {//If the doubles are equal to the figures produces the toast
Toast.makeText(getApplicationContext(), "Please enter contact your GP",
Toast.LENGTH_LONG).show();
startActivity(new Intent(weighinclass.this, register.class));//moves on the next actvity
result.setEnabled(false);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And the error:
05-14 08:57:56.944 2392-2407/com.example.siuni.mymedicare W/EGL_emulation﹕ eglSurfaceAttrib not implemented
05-14 08:57:56.944 2392-2407/com.example.siuni.mymedicare W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6cc21c0, error=EGL_SUCCESS

Application will crash if you provide null values in EditText .
You are getting Strings in EditText (sometimes empty)in onClick & trying to parse it.
It will throw a NumberFormatException in your code & you are not using any Exception handling mechanism . So obviously your application will crash .
provide some checks like
if(!strH.equals("")){
double HeartR = Double.parseDouble(strH););
}
else{
Toast.makeText(getApplicationContext(), "Please enter your Heart Rate",Toast.LENGTH_LONG).show();
}
Note : The provided log is not related with your issue . The correct log will be like this
java.lang.NumberFormatException: Invalid double: ""

Related

How to use Textview output for another class method?

I have just started using eclipse adt(android developer tool) and i am working on electricbill calculator app. The app interface looks like this: App interface
The user will input a value in previous consumption and current consumption then calculate(1st button) to get the total consumption. Then enter the rate and compute(2nd button, multiplies total consumption and rate) to get the electricbill.
My main activity contains onClickListeners for the buttons. The first part of the calculation works, but when i try to input a value and rate and compute it, the application crashes and i dont know where is the problem. Here is my code:
Calculate Button
public class MainActivity extends Activity {
EditText PrevConEdt, CurrConEdt, RateEdt;
TextView ConsumptionTv, ElectricBillTv;
Button CalculateBtn, ComputeBtn, ClearBtn, ClearBtn2;
Double rateDbl, cbillDbl, consumptionDbl, prevDbl, currentDbl;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PrevConEdt = (EditText) findViewById(R.id.txtPreviousConsumption);
CurrConEdt = (EditText) findViewById(R.id.txtCurrentConsumption);
RateEdt = (EditText) findViewById(R.id.txtEnterRate);
ConsumptionTv = (TextView) findViewById(R.id.txtConsumption);
ElectricBillTv = (TextView) findViewById(R.id.txtEbill);
CalculateBtn = (Button) findViewById(R.id.btnCalculate);
CalculateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View Calculate) {
String prev, current, consumption;
prev = PrevConEdt.getText().toString();
current = CurrConEdt.getText().toString();
if(PrevConEdt.length() == 0){
Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
return;
}else if(CurrConEdt.length() == 0){
Toast.makeText(MainActivity.this, "Consumption Required", Toast.LENGTH_LONG).show();
return;
}else{
Double prevDbl, currentDbl, consumptionDbl;
prevDbl = Double.parseDouble(prev);
currentDbl = Double.parseDouble(current);
if(currentDbl < prevDbl){
//String msg = "Current should be greater than previous.";
//int duration = Toast.LENGTH_LONG;
//Toast.makeText(getBaseContext(), msg, duration).show();
//PrevConEdt.requestFocus();
CurrConEdt.setError("Current should be greater than previous.");
return;
}else{
consumptionDbl = currentDbl - prevDbl;
String consumptionStr = String.format("%.2f kWh", consumptionDbl);
ConsumptionTv.setText(consumptionStr);
}
}
}
});
Compute Button
ComputeBtn = (Button) findViewById(R.id.btnCompute);
ComputeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View compute) {
String rate, consumption;
rate = RateEdt.getText().toString();
consumption = ConsumptionTv.getText().toString();
if(RateEdt.length() == 0){
RateEdt.setError("Rate is required.");
return;
}else{
Double rateDbl, cbillDbl, consumptionDbl;
rateDbl = Double.parseDouble(rate);
consumptionDbl = Double.parseDouble(consumption);
cbillDbl = consumptionDbl * rateDbl;
String billStr = String.format("Php %.2f", cbillDbl);
ElectricBillTv.setText(billStr);
}
}
});

how to check if edittext is empty?

I have a sign up form that asking the users to enter a username and a password twice, I want to don't submit the form and alert the user if he messes to fill any of the fields, but the button is not working in all cases, this is my code:
user = (EditText) this.findViewById(R.id.username);
pass = (EditText) this.findViewById(R.id.password);
pass2 = (EditText) this.findViewById(R.id.password2);
u = user.getText().toString();
p1 = pass.getText().toString();
p2 = pass2.getText().toString();
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
btn = (Button) this.findViewById(R.id.register2);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!p1.equals(p2))
Toast.makeText(getApplicationContext(), "Passwords didn't match!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "Passwords match!", Toast.LENGTH_SHORT).show();
}
});
}
Remove this if condition line
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
And put this inside the click lisner
if(!(u.equals("")||p1.equals("")||p2.equals(""))){
//Toast message please enter the username or pwd
return;
}
I found the ideal answer is make a method as follow:
boolean isEmpty(EditText e){
return e.getText().toString().trim().length() == 0;
}
Simple way is check the length of the EditText box content
EditText resultInput = (EditText)findViewById(R.id.result);
if(resultInput.getText().length() > 0)
// Edit Text is Empty
else
// Edit Text is Empty
if(!(user.getText().length() <= 0) & (pass.getText().length() <= 0) & (pass2.getText().length() <= 0))){
btn = (Button) this.findViewById(R.id.register2);
...

Display toast for empty fields when user submits data

I have an activity in which there are three EditTexts: First Name, Middle Name, Last Name, and a Submit button. If the user submits with a field blank, a different toast appears for different field. Here's is an example when button will be clicked!:
I'll assume you can figure out how to use a button listener yourself. Inside that button listener, you can use this code:
// create EditText references
EditText etFirstName = (EditText)findViewById(R.id.firstName);
EditText etMiddleName = (EditText)findViewById(R.id.middleName);
EditText etLastName = (EditText)findViewById(R.id.lastName);
// boolean variables that each represent whether or not the each field is blank
// if the EditText length is 0, it's true (blank); otherwise, it's false (filled)
boolean firstNameBlank = etFirstName.length() == 0;
boolean middleNameBlank = etMiddleName.length() == 0;
boolean lastNameBlank = etLastName.length() == 0;
if (firstNameBlank && middleNameBlank && lastNameBlank) {
// toast all three blank
}
else if (firstNameBlank && middleNameBlank) {
// toast just first and middle are blank
}
else if (firstNameBlank && lastNameBlank) {
// toast just first and last are blank
}
else if (middleNameBlank && lastNameBlank) {
// toast just middle and last are blank
}
else if (firstNameBlank) {
// toast just first is blank
}
else if (middleNameBlank) {
// toast just middle is blank
}
else if (lastNameBlank) {
// toast just last is blank
}
else {
// none are blank
}
Try this way
EditText e = (EditText)findViewById(R.id.EDITTEXT));
if(e.getText().length == 0){
//Show Toast
}else{
//continue your code
}
implement onClick() event of your submit button as below:
#Override
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btnSubmit:
if(edtFirstName.getText().toString().length() < 1){
Toast.makeText(this, "please fill all boxes.",Toast.LENGTH_LONG).show();
}else if(edtSecondName.getText().toString().length() < 1){
Toast.makeText(this, "please fill middle name and last name.",Toast.LENGTH_LONG).show();
} else if(edtLastName.getText().toString().length() < 1){
Toast.makeText(this, "please fill last name.",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "please wait...processing.",Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}

Edit Text value always equals empty string

Here's the code snippet
s= e1.getText().toString();
iv1 = (ImageView) findViewById(R.id.imageView1);
iv1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(s.matches("")){
int time=2000;
Toast.makeText(Loadscreen.this, "Please specify the level", time).show();
}
else{
int str= Integer.valueOf(s);
if(str>0 && str<11){
calculate(str);
r2=new Random();
int nxt = r2.nextInt(2);
if(nxt==0){
//do some work
}
else{
//do some work
}
}
else{
int time=2000;
Toast.makeText(Loadscreen.this, "Enter a valid level", time).show();
}
}
}
});
Control never goes to the else block. The output on the screen is the text of the Toast with the comment "Please specify the level".
Please suggest why else part is not executed?
probably you are not getting the correct result while getting the text from edit text
write this line in onclick method before any comparison
s= e1.getText().toString();

Finish an activity,get string typed result from a class and use that result to another activity

I'm new in android environment and started a Software development project, so my knowledge is too few in it. I need help in detail.
Problem details:
Project is on ANDROID OCR code source from github Robert m.theis
currently it's outcome is - while i take an image of any written text,it retrieves quite exact output using tesseract engine as text and search in internet.
my work is -
use the text string (digits ) and call to a phone operator.
my project name is automated mobile card recharging system.
so that i took result text from a method getText() class named OcrResult.java and put into my own activity. But i don't know why this don't working in real device.
it builds, run in emulator, but in real device at least it should show messages! But it doesn't.
i also added in manifest.xml file as (angel braces are remover here)
under activity
activity android:name="edu.sfsu.cs.orange.ocr.call.CallManager"
under application
uses-permission android:name="android.permission.CALL_PHONE"
here my code is
package edu.sfsu.cs.orange.ocr.call;
import edu.sfsu.cs.orange.ocr.OcrResult;
import edu.sfsu.cs.orange.ocr.CaptureActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class CallManager extends Activity
{
public static final String preString = "*111*";
public static final String postString = "#";
//to store retrieved digits
String finalString;
//to get text result from ocr result
OcrResult getStringResult = new OcrResult();
String middleString = getStringResult.getText();
//if it fails to scan desired digit,call the process again
CaptureActivity tryProcessAgain = new CaptureActivity();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void setString(String x)
{
middleString = x;
}
public String getString( String toBeInserted)
{
if(toBeInserted.length() == 16)
{
int counter = 0;
char [] insertHere = new char[16];
for(int verifier = 0; verifier < 16; verifier ++)
{
insertHere[verifier] = toBeInserted.charAt(verifier);
if(!Character.isDigit(insertHere[verifier]))
{
break;
}
counter ++;
}
if(counter == 16)
{
finalString = preString + toBeInserted + postString;
return finalString;
}
else
{
// #SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scan invalid.....OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
else
{
//#SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scannin invalid...OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
public void CallToOperator(String callMe)
{
Toast toast = Toast.makeText(this,finalString,Toast.LENGTH_SHORT);
toast.show();
//Toast toast1 = Toast.makeText(this,middleString,Toast.LENGTH_SHORT);
//toast1.show();
if(callMe == finalString)
{
try
{
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + finalString)));
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
tryProcessAgain.onShutterButtonPressContinuous();
}
}
}

Categories

Resources