I tried using Integer.parseInt(), but it doesn't convert it EditText's String input to integer. I need to use integers to multiply data and calculate total. EditText is not empty. Why does this error occurs?
buttonAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
try {
if (twh.getText().toString() == "") {
total = 0;
} else {
total = (Integer.parseInt(twh.getText().toString()));
}
a = Integer.parseInt(textIn1.getText().toString());
b = Integer.parseInt(textIn2.getText().toString());
c = Integer.parseInt(textIn3.getText().toString());
total = total + (a * b * c);
twh.setText(String.valueOf(total));
}
catch (Exception e){
System.out.print(e+"");
}
}
Instead of this,
a = Integer.parseInt(textIn1.getText().toString());
try it,
a = Integer.valueOf(textIn1.getText().toString());
Also add
android:inputType="number"
in your xml layout file.
<EditText...
android:inputType="number"/>
to input only numbers.
Related
I've just started off learning Adroid studio and coding with Java. I'm not sure why my if statement returns a value of 0(The initialized value).
The code above the onclicklistener works fine.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thecart);
Intent caller = getIntent();
String item = caller.getStringExtra("choice");
TextView disptext = (TextView) findViewById(R.id.carttoptext);
disptext.setText("You selected " + item);
EditText quantity = (EditText) findViewById(R.id.inputquantity);
Button calc= (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double price=0;
double vquant = valueOf(quantity.getText().toString());
String item = caller.getStringExtra("choice");
if (item.equals("Eggs")) {
price = vquant * 4;
} else if (item.equals("Milk")) {
price = vquant * 30;
} else if (item.equals("Bread")) {
price = vquant * 23;
} else if (item.equals("Chips")) {
price = vquant * 20;
} else if (item.equals("Maggi")) {
price = vquant * 15;
}
DecimalFormat formatval = new DecimalFormat("##.##");
TextView pricetext = (TextView) findViewById(R.id.pricetext);
pricetext.setText("Total: " + formatval.format(price));
}
});
}
}
I'm expecting the textview beneath the edittext to give me the value vquant*(if condition value). But I'm getting the Textview as Total: 0 , which is the initializing value.
What changes should I make to the code so that I get desired output?
check if the vquant is able to fetch the value from the quantity as a double.
ValueOf() change the data into String and you are taking that data to a double variable. It won't work. Use Double.valueOf()
Have you tried "Double.parseDouble(..)" instead of valueOf?
I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}
I am trying to build a Bengali calculator. Here is the layout of English calculator :
By editing layout I can easily replace English digits with Bengali digits. But when it comes to the calculation i am unable to do it. Like i want it to calculate in Bengali too. e.g it will perform in Bengali like this (২+২=৪) instead of (2+2=4). I have tried the replacing method but it didn't work.
Bengali digits(০ ১ ২ ৩ ৪ ৫ ৬ ৭ ৮ ৯)
English digits(1 2 3 4 5 6 7 8 9)
Thank you for your time.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(result);
}
}
}
Your code tries to extract numerical values from the text on buttons.
You should write custom Double parser which parses Bengali number text to numerical value.
Also you should write a method which converts numerical double value to Bengali number text. You have to use this method while setting screen text.
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str2, result, str, sign;
private double a, b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.textview);
str = "";
}
public void onclick(View v) {
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = BengaliUtils.toDouble(str);
}
public void onclicksign(View v) {
Button button = (Button) v;
sign = button.getText().toString();
screen.setText(sign);
str = "";
}
public void calculate(View v) {
Button button = (Button) v;
str2 = screen.getText().toString();
b = BengaliUtils.toDouble(str2);
if (sign.equals("+")) {
result = a + b + "";
} else if (sign.equals("-")) {
result = a - b + "";
} else if (sign.equals("*")) {
result = a * b + "";
} else if (sign.equals("/")) {
result = a / b + "";
} else {
screen.setText("?????? ???");
}
{
screen.setText(BengaliUtils.toString(result));
}
}
}
class BengaliUtils {
static String toString(double value) {
//TODO implement logic
// You can convert value to regular number text, and then replace each char with the Bengali version. The performance could be improved with better logic.
return text;
}
static double toDouble(String text) {
//TODO implement logic
//You can do that, first replace each Bengali char with normal number char. The use Double.parse on new text. The performance could be improved with better logic.
return value;
}
}
#Override
public void onClick(View view) {
String num = editText.getText().toString();
//split the num
char[] charArray = num.toCharArray();
StringBuilder stringBuilder = new StringBuilder(charArray.length);
// loop and convert using switch case
for (int i=0; i<charArray.length; i++ ){
char character = charArray[i];
switch (character){
case '.':
stringBuilder.append(".");
break;
case '0':
stringBuilder.append("০");
break;
case '1':
stringBuilder.append("১");
break;
}
}
//Final result..
textView.setText(stringBuilder);
}
Try above code...
Here is the output
NOTE
I am taking English numbers from EditText on Button click. You will
have to change that in your code.
Currently, switch can handle 0,1,.(decimal) only. You can easily
add cases for other numbers too.
Please Check this answer too. Convert String to another locale in java
I have created a simple app to calculate the discount. it works fine when the values are provided, but keeps on crashing when calculation is done with empty text fields. thanks in advance..!!
public class Firstctivity extends AppCompatActivity {
Button find;
EditText ed1,ed2;
TextView tv1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstctivity);
find=(Button)findViewById(R.id.button);
tv1=(TextView)findViewById(R.id.text39);
ed1=(EditText)findViewById(R.id.sai);
ed2=(EditText)findViewById(R.id.editText);
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
try {
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
});
}
}
try tihs.
find.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if(ed1.getText().toString.length() >0){
try {
final double a =Double.parseDouble(String.valueOf(ed1.getText()));
final double b =Double.parseDouble(String.valueOf(ed2.getText()));
double results;
double c;
c = a * b;
results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
}
catch (NumberFormatException ex)
{
}
}
}
});
When you try to calculate the discount, you call ed1.getText() and then, you try to convert a null value into a double value, witch causes a NullPointerException.
To solve that issue, you have to check if the getText() method is returning a valid text to convert it.
You'll want to check for empty strings and null values:
find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ed1.getText() != null && !TextUtils.isEmpty(ed1.getText().toString()) &&
ed2.getText() != null && !TextUtils.isEmpty(ed2.getText().toString())) {
try {
final double a = Double.parseDouble(String.valueOf(ed1.getText().toString()));
final double b = Double.parseDouble(String.valueOf(ed2.getText().toString()));
double c = a * b;
double results = c / 100;
String total2 = String.valueOf(results);
// String total2="fuck u";
tv1.setText("You have recieved Rs" + total2 + "/- concession.");
tv1.setBackgroundColor(Color.parseColor("#4169E1"));
} catch (NumberFormatException ex) {
Log.e("SOME TAG", ex.getMessage(), ex);
}
}
}
});
using try- catch in such simple calculations is not recommended and may "hide" crusial errors. First of all start with an If-statement inside your click event and do all your checks inside there. (if txtValue.getText()!=null {do something} ). this way it is easier for you to debug and correct your code.
So, just to clarify; remove try-catch. do if-stament and check if your txt fields are not null before proceeding to any calculations.finish you click event without any problem and with a valid calculation.
I am trying to generate random number. And to do so ,
I am getting the text from edit text and passing it to the nextInt of Random class. But i have a problem. My textView is not changing.
Here its the code:
package random.vivek.com.random;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by Shiva on 09-08-2015.
*/
public class Random extends AppCompatActivity {
int number , i ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
java.util.Random genertor = new java.util.Random();
EditText editText = (EditText) findViewById(R.id.random);
TextView textView = (TextView) findViewById(R.id.text);
String s = editText.getText().toString();
try {
i = Integer.parseInt(s);
for (int roll = 0; roll < 20; roll++) {
number = genertor.nextInt(i);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
textView.setText(number + "");
}
}
Try:
try {
i = Integer.parseInt(s);
for (int roll = 0; roll < 20; roll++) {
number = genertor.nextInt(i);
textView.setText(number);
}
} catch (NumberFormatException e) {
e.printStackTrace();
You put all your code in the onCreate method, which is wrong. The onCreate method is called when the activity starts. You should add a button or something to your app so that when the user presses the button, a random number gets generated. I think you have the ability to do that so I won't show you here.
In the on click listener of the button, write your code above:
public void buttonOnClick (View view) {
java.util.Random genertor = new java.util.Random();
EditText editText = (EditText) findViewById(R.id.random);
TextView textView = (TextView) findViewById(R.id.text);
String s = editText.getText().toString();
try {
i = Integer.parseInt(s);
for (int roll = 0; roll < 20; roll++) {
number = genertor.nextInt(i);
}
textView.setText (Integer.toString(number));
} catch (NumberFormatException e) {
e.printStackTrace();
}
String s = editText.getText().toString();
try {
i = Integer.parseInt(s);
for (int roll = 0; roll < 20; roll++) {
number = genertor.nextInt(i);
textView.setText(String.ValueOf()number);
// But this will also keep continuing through the loop and change the text quickly.
}
If you want to append the values:
String s = editText.getText().toString();
try {
i = Integer.parseInt(s);
for (int roll = 0; roll < 20; roll++) {
number = genertor.nextInt(i);
textView.append(String.ValueOf()number + " ");
Also as it stands, your textView.setText(number + ""); the +"" does nothing.
You need to change your algorithm if you want a time delay between changing the Text of your textView.
You need to set your textview by using textView.setText(Integer.toString(number)) in your code
onCreate method:
First things first, you are writing this in the onCreate method. onCreate is the method where most of your initialization stuff goes.
So when the view is created there is nothing in the edittext, so you get nothing in the text view. Instead you should be doing it on the click of some button or on text change in edit text to make it more dynamic.
Responding to edit text change:
To perform some action on edittext text change use the text watcher as follows:
editText.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
String s = editText.getText().toString();
try {
i = Integer.parseInt(s);
for (int roll = 0; roll < 20; roll++) {
number = genertor.nextInt(i);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});