it's me again... I want to ask how to make my "button" (calculateButton) not to function if the user won't input their weight & height... or the user don't input their weight or their height... Hope you can help me... thanks..
Here is the code for my calculateButton:
public void calculateClickHandler(View view) {
if (view.getId() == R.id.calculateButton) {
}
EditText weightText = (EditText) findViewById(R.id.weightT);
EditText heightText = (EditText)findViewById(R.id.heightT);
TextView resultText = (TextView)findViewById(R.id.resultLabel);
TextView categoryText = (TextView)findViewById(R.id.categoryLabel);
rGroup = (RadioGroup)findViewById(R.id.rGroup);
int weight = (int) Float.parseFloat(weightText.getText().toString());
int height = (int) Float.parseFloat(heightText.getText().toString());
int bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
resultText.setText("Your BMI is:" + " " + bmiValue + " " + "and you're");
categoryText.setText(bmiInterpretation + ".");}
You need to insert "validations" in your code. Basically checking the value of the string in your EditText before performing any operation.
Something like:
rGroup = (RadioGroup)findViewById(R.id.rGroup);
if( !weightText.getText().toString.equals(" ")){
int weight = (int) Float.parseFloat(weightText.getText().toString());
int height = (int) Float.parseFloat(heightText.getText().toString());
int bmiValue = calculateBMI(weight, height);
}
Refer:
Android, Validate an empty EditText field
https://sites.google.com/site/khetiyachintan/sample-example/edit-text-validation-example
Android EditText validation
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Issue with empty EditText
(3 answers)
convert EditText to float - android eclipse
(6 answers)
when EditText is empty and click calculateButton, app crashes
(3 answers)
How to stop the app crashing when String is empty
(4 answers)
Closed 5 years ago.
#Override
public void onClick(View v)
{
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
}
Above is my code, when I leave any one of them empty, it crashes.How to get over it.
Just check whether user has entered anything or not and then parse your value:
if(!Total.getText().toString().matches(""))
float num1 = Float.parseFloat(Total.getText().toString());
Try Using Try...Catch
float num1 = 0.00f;
float num2 = 0.00f;
try {
num1 = Float.parseFloat(Total.getText().toString());
num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
catch(NumberFormatException ex) {
//Handle Non Float Exception
Toast.makeText(getApplicationContext(), "Invalid input !",Toast.LENGTH_LONG).show();
}
try this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Total.getText().toString().trim().equals("")&&!Done.getText().toString().trim().equals("")){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});
You can apply condition if EditText is not empty then your code is run like that
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
String total=Total.getText().toString();
String done=Done.getText().toString();
if (!total.isEmpty() && !done.isEmpty()) {
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}else {
Toast.makeText(OpenFile.this, "Fill values", Toast.LENGTH_SHORT).show();
}
Firstly Check whether you find editText properly or not
After that also check isEmpty condition for avoiding NullPointer Exception
if (!editText1.getText().toString().isEmpty() && !editText2.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
}
check for empty text, if not empty than perform calculation
if(!Total.getText().toString().isEmpty() && !Done.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});
I have developed an calculator app. It needs two inputs num1 and num2.
When i give the 2 inputs the arithmetic process is working good. But, when i click any buttons(add,sub,mul,division) without any inputs, the app has closed and shows the error "Unfortunately calc has stopped.
public void onButtonClick(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
TextView t1 = (TextView)findViewById(R.id.textView);
float num1 = Integer.parseInt(e1.getText().toString());
float num2 = Integer.parseInt(e2.getText().toString());
float sum = num1 + num2; t1.setText(Float.toString(sum));
}
Just add a validation method before Onclick
private boolean validation(){
int error = 1;
if(num1.getText().toString.equals("")){error = error + 1;}
if(num2.getText().toString.equals("")){error = error + 1;}
if(error == 0){return true;} else { return false; }
}
I guess its because you're having null value in the 'editText' and you're converting null value to float without checking for the condition that it is not null.
So before conversion. check if the editText is null. Like this:
if(e1.getText().toString()!="" && e2.getText().toString()!="")
{
float num1 = Float.parseFloat(e1.getText().toString());
float num2 = Float.parseFloat(e2.getText().toString());
}
And you should use 'Float' for conversion and not 'Int'
Try this
String mNum1="",mNum2="";
mNum1=e1.getText().toString();
mNum2=e2.getText().toString();
if(!mNum1.equalsIgnoreCase("") && !mNum2.equalsIgnoreCase("") )
{
float num1 = (float) Double.parseDouble(mNum1);
float num2 = (float) Double.parseDouble(mNum2);
float sum = num1 + num2;
System.out.println("sum"+String.valueOf(sum));
t1.setText(String.valueOf(sum));
}
I want to code a simple calculator with 3 inputs (NUM1,NUM2,NUM3), 3 buttons(SUM,SUB,MUL) and 1 RESULT text plane. In my app if I give all inputs, the app works correctly. However if I don't give any input for 1 field, I encounter app stopped error. I want to make my app work with any number of inputs.
Here is my code.
public void onButtonClickSum(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sum = num1 + num2 + num3;
t1.setText(Integer.toString(sum));
}
public void onButtonClickSub(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sub = num1 - num2 - num3;
t1.setText(Integer.toString(sub));
}
public void onButtonClickMul(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int mul = num1 * num2 * num3;
t1.setText(Integer.toString(mul));
}
You need to put null or empty checks before you parse the input as integers
Try making the EditText objects fields, since you are reusing them in each method
Example:
// Fields
private EditText mEditText1 = (EditText)findViewById(R.id.editText);
private EditText mEditText2 = (EditText)findViewById(R.id.editText2);
private EditText mEditText3 = (EditText)findViewById(R.id.editText3);
private TextView mTextView = (TextView)findViewById(R.id.textView2);
public void onButtonClick(View v){
int num1 = 0;
int num2 = 0;
int num3 = 0;
String e1 = mEditText1.getText();
String e2 = mEditText2.getText();
String e3 = mEditText3.getText();
if(!e1.isEmpty()) {
num1 = Integer.parseInt(e1);
}
if(!e2.isEmpty()){
num2 = Integer.parseInt(e2);
}
if(!e3.isEmpty()){
num3 = Integer.parseInt(e3);
}
int sub = num1 - num2 - num3;
mTextView.setText(Integer.toString(sub));
}
Change from
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
to
int num1 = 0, num2 = 0, num3 = 0;
int num1_error = 0, num2_error = 0, num3_error = 0;
try{
num1 = Integer.parseInt(e1.getText().toString());
}Catch(Exception e){
num1_error = 1;
}
try{
num2 = Integer.parseInt(e2.getText().toString());
}Catch(Exception e){
num2_error = 1;
}
try{
num3 = Integer.parseInt(e3.getText().toString());
}Catch(Exception e){
num3_error = 1;
}
// for addition
int sum = 0;
if(num1_error == 0){
sum += num1;
}
if(num2_error == 0){
sum += num2;
}
if(num1_error == 0){
sum += num3;
}
t1.setText(Integer.toString(sum));
// for subtraction
int sub = 0;
if(num1_error == 0){
sub = num1 - sub;
}
if(num2_error == 0){
sub = sub - num2;
}
if(num3_error == 0){
sub = sub - num3;
}
t1.setText(Integer.toString(sub));
// for multiplication
int mul = 1;
if(num1_error == 0){
mul = mul*num1;
}
if(num2_error == 0){
mul = mul*num2;
}
if(num3_error == 0){
mul = mul*num3;
}
t1.setText(Integer.toString(mul));
Try doing this and same for other methods:
EditText e1 ,e2, e3;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.editText);
e2 = (EditText)findViewById(R.id.editText2);
e3 = (EditText)findViewById(R.id.editText3);
t1 = (TextView)findViewById(R.id.textView2);
}
public void onButtonClickSum(View v){
if(e1.getText().toString().length()==0){
e1.setError("Required");
}
else if(e2.getText().toString().length()==0){
e2.setError("Required");
}
else if(e3.getText().toString().length()==0){
e3.setError("Required");
}
else{
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sum = num1 + num2 + num3;
t1.setText(Integer.toString(sum));
}
}
I have 2 Edittext which only accepts numbers.
I want to make sure that the fields are not empty before the submit button is pressed to stop the application from crashing.
These are the 2 edittext fields i have.
EditText weightText = (EditText)findViewById(R.id.WeightText);
EditText heightText = (EditText)findViewById(R.id.Heighttext);
Code:
public class BMI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
}
public void calculateHandler(View view) {
// make sure we handle the click of the calculator button
if (view.getId() == R.id.calculate) {
// get the references to the widgets
EditText weightText = (EditText)findViewById(R.id.WeightText);
EditText heightText = (EditText)findViewById(R.id.Heighttext);
TextView resultText = (TextView)findViewById(R.id.resultLabel);
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
}
}
private float calculateBMI (float weight, float height) {
return (float)Math.round((weight / (height * height)) * 100) / 100 ;
}
// interpret what BMI means
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
}
You can check that your EditTexts are not empty like below:
weightText.getText().length() != 0 && heightText.getText().length() != 0
And you can use this condition inside the onClick(View) method, which is called when your button is clicked like below:
yourButton.setOnClickListener( new OnClickListener(){
public void onClick(){
if(weightText.getText().length() != 0 && heightText.getText().length() != 0){
//do sth
}
});
The second way, you can create TextWatcher which set to both EditTexts and in onTextChanged() you can check that both EditTexts are not empty like below:
private class YourTextWatcher implements TextWatcher{
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
yourButton.setEnabled(weightText.getText().length() != 0 && heightText.getText().length() != 0)
}
#Override
public void afterTextChanged(Editable editable) {
}
}
you can set this TextWatcher for your EditText like below:
weightText.addTextChangedListener(new YourTextWatcher());
heightText.addTextChangedListener(new YourTextWatcher());
Here is code that your Activity should look like:
public class BMI extends Activity {
EditText weightText;
EditText heightText;
TextView resultText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bmi);
weightText = (EditText) findViewById(R.id.WeightText);
heightText = (EditText) findViewById(R.id.Heighttext);
resultText = (TextView) findViewById(R.id.resultLabel);
Button button = (Button) findViewById(R.id.calulate);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calculateHandler();
}
});
}
public void calculateHandler() {
// make sure we handle the click of the calculator button
if (weightText.getText().length() == 0 || heightText.getText().length() == 0) {
return;
}
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
// display toast additionally to example
Toast.makeText(this, bmiValue + " = " + bmiInterpretation, Toast.LENGTH_LONG).show();
}
private float calculateBMI(float weight, float height) {
return (float) Math.round((weight / (height * height)) * 100) / 100;
}
// interpret what BMI means
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue < 25) {
return "Normal";
} else if (bmiValue < 30) {
return "Overweight";
} else {
return "Obese";
}
}
}
Calculate method
public void calculateHandler() {
// make sure we handle the click of the calculator button
if (weightText.getText().toString().trim().length() == 0 || heightText.getText().toString().trim().length() == 0) {
Toast.makeText(this, "Please fill all field by numbers", Toast.LENGTH_LONG).show();
return;
}
// get the users values from the widget references
float weight = Float.parseFloat(weightText.getText().toString());
float height = Float.parseFloat(heightText.getText().toString());
// calculate the bmi value
float bmiValue = calculateBMI(weight, height);
// interpret the meaning of the bmi value
String bmiInterpretation = interpretBMI(bmiValue);
// now set the value in the result text
resultText.setText(bmiValue + " = " + bmiInterpretation);
// display toast additionally to example
}
weightText.getText().toString().isEmpty();
try like this..
String weight = weightText.getText().toString();
String height = heightText.getText().toString();
if((Integer.parseInt(weight)!=null) && (Integer.parseInt(height)!=null)){
//Not an empty
}
else{
//empty
}
I have been playing with android:gravity attribut but still cannot make my text content justify in the textview. Does anybody know if it is supported ? Is there a way ? Anybody succeeded ?
It would appear that Android does not support full Justification. :(
The best you can achieve is Left or Right Justification.
Android TextView Justify Text
You could also make the width of the TextView to wrap its content ("wrap_content") and justify the TextView in its parent Layout.
use the following code:
public class TextJustify {
final static String SYSTEM_NEWLINE = "\n";
final static float COMPLEXITY = 5.12f; // Reducing this will increase
// efficiency but will decrease
// effectiveness
final static Paint p = new Paint();
/* #author Mathew Kurian */
public static void run(final TextView tv, float origWidth,
int paddingLeft, int paddingRight, int marginLeft, int marginRight) {
origWidth-= paddingRight+marginRight+paddingLeft+marginLeft;
String s = tv.getText().toString();
p.setTypeface(tv.getTypeface());
String[] splits = s.split(SYSTEM_NEWLINE);
float width = origWidth - 5;
for (int x = 0; x < splits.length; x++)
if (p.measureText(splits[x]) > width) {
splits[x] = wrap(splits[x], width, p);
String[] microSplits = splits[x].split(SYSTEM_NEWLINE);
for (int y = 0; y < microSplits.length - 1; y++)
microSplits[y] = justify(removeLast(microSplits[y], " "),
width, p);
StringBuilder smb_internal = new StringBuilder();
for (int z = 0; z < microSplits.length; z++)
smb_internal.append(microSplits[z]
+ ((z + 1 < microSplits.length) ? SYSTEM_NEWLINE
: ""));
splits[x] = smb_internal.toString();
}
final StringBuilder smb = new StringBuilder();
for (String cleaned : splits)
smb.append(cleaned + SYSTEM_NEWLINE);
tv.setGravity(Gravity.RIGHT);
tv.setText(smb);
}
private static String wrap(String s, float width, Paint p) {
String[] str = s.split("\\s"); // regex
StringBuilder smb = new StringBuilder(); // save memory
smb.append(SYSTEM_NEWLINE);
for (int x = 0; x < str.length; x++) {
float length = p.measureText(str[x]);
String[] pieces = smb.toString().split(SYSTEM_NEWLINE);
try {
if (p.measureText(pieces[pieces.length - 1]) + length > width)
smb.append(SYSTEM_NEWLINE);
} catch (Exception e) {
}
smb.append(str[x] + " ");
}
return smb.toString().replaceFirst(SYSTEM_NEWLINE, "");
}
private static String removeLast(String s, String g) {
if (s.contains(g)) {
int index = s.lastIndexOf(g);
int indexEnd = index + g.length();
if (index == 0)
return s.substring(1);
else if (index == s.length() - 1)
return s.substring(0, index);
else
return s.substring(0, index) + s.substring(indexEnd);
}
return s;
}
private static String justifyOperation(String s, float width, Paint p) {
float holder = (float) (COMPLEXITY * Math.random());
while (s.contains(Float.toString(holder)))
holder = (float) (COMPLEXITY * Math.random());
String holder_string = Float.toString(holder);
float lessThan = width;
int timeOut = 100;
int current = 0;
while (p.measureText(s) < lessThan && current < timeOut) {
s = s.replaceFirst(" ([^" + holder_string + "])", " "
+ holder_string + "$1");
lessThan = p.measureText(holder_string) + lessThan
- p.measureText(" ");
current++;
}
String cleaned = s.replaceAll(holder_string, " ");
return cleaned;
}
private static String justify(String s, float width, Paint p) {
while (p.measureText(s) < width) {
s = justifyOperation(s, width, p);
}
return s;
}
}
and for calling this I create formula, you must use following code:
public static final int FinallwidthDp = 320 ;
public static final int widthJustify = 223 ;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int widthPixels = metrics.widthPixels;
float scaleFactor = metrics.density;
float widthDp = widthPixels / scaleFactor;
TextView tv = (TextView) findViewById(R.id.textView1);
ViewGroup.MarginLayoutParams lp1 = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();
tv.setText(text);
TextJustify.run(tv,widthDp / FinallwidthDp * widthJustify , tv.getPaddingLeft(),tv.getPaddingRight() , lp1.leftMargin, lp1.rightMargin);
this algorithm tested on various device and worked fine in normal activity (not dialog) and wrap-content width for TextView, and worked with every padding and margin.if not good for you, you can change widthJustify until look good to you, I hope this useful
XML Layout: declare WebView instead of TextView
<WebView
android:id="#+id/textContent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
Java code: set text data to WebView
WebView view = (WebView) findViewById(R.id.textContent);
String text;
text = "<html><body><p align=\"justify\">";
text+= "This is the text will be justified when displayed!!!";
text+= "</p></body></html>";
view.loadData(text, "text/html", "utf-8");
This may Solve your problem.