Android: If/Else statement makes app crash - android

I'm trying to tell if an android int is null by using If/Else
public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}
res.setText(String.valueOf(f));
There are no any errors, but when I'm running the app its crashing when im pressing the button.
I'm also trying to use null instead of "":
if (minString.equals(null))
{
// Do Nothing
}
if (maxString.equals(null))
{
// Do Nothing
}
And i have a crash.
Please help me!!!

public boolean equals (Object object)
Compares the specified object to this string and returns true if they are equal. The object must be an instance of string with the same characters in the same order.
So its returning error so if you want to check if its null then use == operator on the object.
if (maxString == null )
Use
int myMin = 0;
int myMax = 0;
if(min.getText().toString()!="")
myMin = Integer.parseInt(min.getText().toString());
if(max.getText().toString()!="")
myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
if (minString.equals(""))
{
// Do Nothing
}
if (maxString.equals(""))
{
// Do Nothing
}

do if (maxString == null )
{
// do something
}

int variables can't be null
If a null is to be converted to int, then it is the converter which decides whether to set 0, throw exception, or set another value (like Integer.MIN_VALUE)
So if you convert int to string again you cannot get null value.

check = input.getText().toString();
try {
if (!check.equals("null")) {
int max = Integer.parseInt(input.getText().toString());
int constant1 = 1;
int constant2 = 1;
int nextNumber = 0;
int count = 0;
String fibResult = "";
for (int i = 0; i <= max; i++) {
fibResult += "F" + count + "=" + nextNumber + "\n";
constant1 = constant2;
constant2 = nextNumber;
nextNumber = constant1 + constant2;
count++;
}
dspResults.setText("\n" + fibResult);
} else {
dspResults.setVisibility(View.VISIBLE);
dspResults.setText("Invalid");
dspResults.setText(Gravity.CENTER);
dspResults.setTextColor(Color.DKGRAY);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}

public void onClick(View v) {
EditText min = (EditText) findViewById(R.id.EditText01);
EditText max = (EditText) findViewById(R.id.maxnum);
EditText res = (EditText) findViewById(R.id.res);
int myMin = Integer.parseInt(min.getText().toString());
int myMax = Integer.parseInt(max.getText().toString());
String minString = String.valueOf(myMin);
String maxString = String.valueOf(myMax);
int f = (int) ((Math.random()*(myMax-myMin+1))+myMin);
{
if (minString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else if (maxString.equals(""))
{
// Do Nothing
res.setText(String.valueOf(f));
return false;
}
else
res.setText(String.valueOf(f));
return true ;
}

Related

User Input of int won't be null

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();
}

How can I convert numbers to currency format in android

I want to show my numbers in money format and separate digits like the example below:
1000 -----> 1,000
10000 -----> 10,000
100000 -----> 100,000
1000000 -----> 1,000,000
Thanks
Another approach :
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMaximumFractionDigits(0);
format.setCurrency(Currency.getInstance("EUR"));
format.format(1000000);
This way, it's displaying 1 000 000 € or 1,000,000 €, depending on device currency's display settings
You need to use a number formatter, like so:
NumberFormat formatter = new DecimalFormat("#,###");
double myNumber = 1000000;
String formattedNumber = formatter.format(myNumber);
//formattedNumber is equal to 1,000,000
Hope this helps!
double number = 1000000000.0;
String COUNTRY = "US";
String LANGUAGE = "en";
String str = NumberFormat.getCurrencyInstance(new Locale(LANGUAGE, COUNTRY)).format(number);
//str = $1,000,000,000.00
Currency formatter.
public static String currencyFormat(String amount) {
DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
return formatter.format(Double.parseDouble(amount));
}
Use this:
int number = 1000000000;
String str = NumberFormat.getNumberInstance(Locale.US).format(number);
//str = 1,000,000,000
This Method gives you the exact output which you need:
public String currencyFormatter(String num) {
double m = Double.parseDouble(num);
DecimalFormat formatter = new DecimalFormat("###,###,###");
return formatter.format(m);
}
Try the following solution:
NumberFormat format = NumberFormat.getCurrencyInstance();
((TextView)findViewById(R.id.text_result)).setText(format.format(result));
The class will return a formatter for the device default currency.
You can refer to this link for more information:
https://developer.android.com/reference/java/text/NumberFormat.html
Here's a kotlin Extension that converts a Double to a Currency(Nigerian Naira)
fun Double.toRidePrice():String{
val format: NumberFormat = NumberFormat.getCurrencyInstance()
format.maximumFractionDigits = 0
format.currency = Currency.getInstance("NGN")
return format.format(this.roundToInt())
}
Use a Formatter class
For eg:
String s = (String.format("%,d", 1000000)).replace(',', ' ');
Look into:
http://developer.android.com/reference/java/util/Formatter.html
The way that I do this in our app is this:
amount.addTextChangedListener(new CurrencyTextWatcher(amount));
And the CurrencyTextWatcher is this:
public class CurrencyTextWatcher implements TextWatcher {
private EditText ed;
private String lastText;
private boolean bDel = false;
private boolean bInsert = false;
private int pos;
public CurrencyTextWatcher(EditText ed) {
this.ed = ed;
}
public static String getStringWithSeparator(long value) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
String f = formatter.format(value);
return f;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
bDel = false;
bInsert = false;
if (before == 1 && count == 0) {
bDel = true;
pos = start;
} else if (before == 0 && count == 1) {
bInsert = true;
pos = start;
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
lastText = s.toString();
}
#Override
public void afterTextChanged(Editable s) {
ed.removeTextChangedListener(this);
StringBuilder sb = new StringBuilder();
String text = s.toString();
for (int i = 0; i < text.length(); i++) {
if ((text.charAt(i) >= 0x30 && text.charAt(i) <= 0x39) || text.charAt(i) == '.' || text.charAt(i) == ',')
sb.append(text.charAt(i));
}
if (!sb.toString().equals(s.toString())) {
bDel = bInsert = false;
}
String newText = getFormattedString(sb.toString());
s.clear();
s.append(newText);
ed.addTextChangedListener(this);
if (bDel) {
int idx = pos;
if (lastText.length() - 1 > newText.length())
idx--; // if one , is removed
if (idx < 0)
idx = 0;
ed.setSelection(idx);
} else if (bInsert) {
int idx = pos + 1;
if (lastText.length() + 1 < newText.length())
idx++; // if one , is added
if (idx > newText.length())
idx = newText.length();
ed.setSelection(idx);
}
}
private String getFormattedString(String text) {
String res = "";
try {
String temp = text.replace(",", "");
long part1;
String part2 = "";
int dotIndex = temp.indexOf(".");
if (dotIndex >= 0) {
part1 = Long.parseLong(temp.substring(0, dotIndex));
if (dotIndex + 1 <= temp.length()) {
part2 = temp.substring(dotIndex + 1).trim().replace(".", "").replace(",", "");
}
} else
part1 = Long.parseLong(temp);
res = getStringWithSeparator(part1);
if (part2.length() > 0)
res += "." + part2;
else if (dotIndex >= 0)
res += ".";
} catch (Exception ex) {
ex.printStackTrace();
}
return res;
}
Now if you add this watcher to your EditText, as soon as user enter his number, the watcher decides whether it needs separator or not.
i used this code for my project and it works:
EditText edt_account_amount = findViewById(R.id.edt_account_amount);
edt_account_amount.addTextChangedListener(new DigitFormatWatcher(edt_account_amount));
and defined class:
public class NDigitCardFormatWatcher implements TextWatcher {
EditText et_filed;
String processed = "";
public NDigitCardFormatWatcher(EditText et_filed) {
this.et_filed = et_filed;
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable editable) {
String initial = editable.toString();
if (et_filed == null) return;
if (initial.isEmpty()) return;
String cleanString = initial.replace(",", "");
NumberFormat formatter = new DecimalFormat("#,###");
double myNumber = new Double(cleanString);
processed = formatter.format(myNumber);
//Remove the listener
et_filed.removeTextChangedListener(this);
//Assign processed text
et_filed.setText(processed);
try {
et_filed.setSelection(processed.length());
} catch (Exception e) {
// TODO: handle exception
}
//Give back the listener
et_filed.addTextChangedListener(this);
}
}
Updated 2022 answer
Try this snippet. It formats a number in string complete with the currency & setting fractional digits.
Upvote if this helped you! :)
/**
* Formats amount in string to human-readable amount (separated with commas
* & prepends currency symbol)
*
* #param amount The amount to format in String
* #return The formatted amount complete with separators & currency symbol added
*/
public static String formatCurrency(String amount) {
String formattedAmount = amount;
try {
if (amount == null || amount.isEmpty())
throw new Exception("Amount is null/empty");
Double amountInDouble = Double.parseDouble(amount);
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
numberFormat.setMaximumFractionDigits(2);
numberFormat.setMinimumFractionDigits(2);
formattedAmount = numberFormat.format(amountInDouble);
} catch (Exception exception) {
exception.printStackTrace();
return formattedAmount;
}
return formattedAmount;
}
private val currencyFormatter = NumberFormat.getCurrencyInstance(LOCALE_AUS).configure()
private fun NumberFormat.configure() = apply {
maximumFractionDigits = 2
minimumFractionDigits = 2
}
fun Number.asCurrency(): String {
return currencyFormatter.format(this)
}
And then just use as
val x = 100000.234
x.asCurrency()
If you have the value stored in a String like me, which was coming from the server like "$20000.00".
You can do something like this in Kotlin (JetpackCompose):
#Composable
fun PrizeAmount(
modifier: Modifier = Modifier,
prize: String,
)
{
val currencyFormat = NumberFormat.getCurrencyInstance(Locale("en", "US"))
val text = currencyFormat.format(prize.substringAfter("$").toDouble())
...
}
Output: "$20,000.00"
NumberFormat.getCurrencyInstance(Locale("ES", "es")).format(number)
here is a kotlin version to Format Currency, here i'm getting an argument from another fragment from an input Field then it will be set in the textView in the main Fragment
fun formatArgumentCurrency(argument : String, textView: TextView) {
val valueText = requireArguments().get(argument).toString()
val dec = DecimalFormat("#,###.##")
val number = java.lang.Double.valueOf(valueText)
val value = dec.format(number)
val currency = Currency.getInstance("USD")
val symbol = currency.symbol
textView.text = String.format("$symbol$value","%.2f" )
}
You can easily achieve this with this small simple library.
https://github.com/jpvs0101/Currencyfy
Just pass any number, then it will return formatted string, just like that.
currencyfy (500000.78); // $ 500,000.78 //default
currencyfy (500000.78, false); // $ 500,001 // hide fraction (will round off automatically!)
currencyfy (500000.78, false, false); // 500,001 // hide fraction & currency symbol
currencyfy (new Locale("en", "in"), 500000.78); // ₹ 5,00,000.78 // custom locale
It compatible with all versions of Android including older versions!

NumberFormat Exception in Android [duplicate]

This question already has an answer here:
android number format exception
(1 answer)
Closed 7 years ago.
This is my calculator app, I know that NumberFormat are caused when we try convert string to numerical type.I have also surrounded them by TRY/CATCH but i cant seem to get them as INT values. Here in my app, I'm getting the strings in the textview and trying to perform operations on them.
Can anyone suggest an alternative approach for the problem?
Here's the code:
public class MainActivity extends AppCompatActivity {
private static String TAG = MainActivity.class.getSimpleName();
private static String GAT = "Tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
ArrayList<String> arrayList = new ArrayList<String>();
String stringOne = " ";
String stringTwo = " ";
public void onClick1(View view) {
//Getting Input from TextView
TextView inputText = (TextView) findViewById(R.id.inputTextView);
Button button = (Button) view;
//Store as String from button press
stringOne = (String) button.getText().toString();
Log.d(TAG, stringOne);
//For entering multiple values
if (!stringOne.contains("+") && !stringOne.contains("-") && !stringOne.contains("/") && !stringOne.contains("*")) {
//Concat if it has multiple digits to original string
stringTwo = stringTwo + stringOne;
Log.d(TAG, stringTwo);
//Remove the last string and place as StringTwo
if (arrayList.size() > 0) {
//Get last position in the array
arrayList.remove((arrayList.size() - 1));
}
arrayList.add(stringTwo);
} else {
//For operators add two times because we removed the previous index
arrayList.add(stringOne);
arrayList.add(stringOne);
//Clear
stringTwo = " ";
Toast.makeText(this, stringOne, Toast.LENGTH_LONG).show();
Log.d(TAG, stringOne);
// Log.d("Veer",stringTwo);
}
//Add to TextView
inputText.setText(inputText.getText().toString()+stringOne);
//inputText.setText(arrayList.toString());
}
public void calculate(View view) {
TextView outputText = (TextView) findViewById(R.id.outputTextView);
int result = 0;
int list = arrayList.size();
while (list != 1) {
if (list > 3) {
//Considering the equation to be like 4+5*5-2/4, Get the third operator, if * and /, then multiply
if (arrayList.get(3).contains("*") || arrayList.get(3).contains("/")) {
if (arrayList.get(3).contains("*")) {
result = Integer.parseInt(arrayList.get(2)) * Integer.parseInt(arrayList.get(4));
} else if (arrayList.get(3).contains("/")) {
result = Integer.parseInt(arrayList.get(2)) / Integer.parseInt(arrayList.get(4));
}
arrayList.remove(2);
arrayList.remove(2);
arrayList.remove(2);
arrayList.add(2, Integer.toString(result));
list = arrayList.size();
} else {
//Vice versa, here for + and - ,replace 1st and 2nd digit
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
else
{
//If size is 3
if (arrayList.get(1).contains("+")) {
result = Integer.parseInt(arrayList.get(0)) + Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("-")) {
result = Integer.parseInt(arrayList.get(0)) - Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("*")) {
result = Integer.parseInt(arrayList.get(0)) * Integer.parseInt(arrayList.get(2));
}
if (arrayList.get(1).contains("/")) {
result = Integer.parseInt(arrayList.get(0)) / Integer.parseInt(arrayList.get(2));
}
arrayList.remove(0);
arrayList.remove(0);
arrayList.remove(0);
arrayList.add(0, Integer.toString(result));
list = arrayList.size();
}
}
outputText.setText(Integer.toString(result));
}
public void clearView(View view) {
TextView input = (TextView)findViewById(R.id.inputTextView);
TextView output = (TextView)findViewById(R.id.outputTextView);
stringOne = "";
stringTwo = "";
input.setText("");
output.setText("");
arrayList.clear();
}
}
You need to catch exception whenever you convert string to numerical type. If it throw an exception then you return. And if no exception, you continue to perform operations on them.
String text = "";
int num;
try {
num = Integer.parseInt(text);
// text is a number");
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Can not parse string to int: " + text,Toast.LENGTH_LONG).show();
// text is not a number";
// Show Log or make a Toast here to easy see when String is not Int format. After that find the reason why text is not int format
}
Hope this help
float num1 = 0;
float num2 = 0;
float result = 0;
num1 = Float.parseFloat(etNum1.getText().toString());
num2 = Float.parseFloat(etNum2.getText().toString());
result = num1 * num2 ;
Log.e("Result",""+result);
Hope it helps.

txtt.setText(getString(R.string.("i" + j++)));

What's wrong with this code? I want to use id automatically. I think after R.string there is a mistake. What can ı do
Do it like this
public static int getStringIDFromName(String stringName)
{
int stringID= 0;
if(stringName == null
|| stringName.equalsIgnoreCase(""))
{
return 0;
}
try
{
#SuppressWarnings("rawtypes")
Class res = R.string.class;
Field field = res.getField(stringName);
stringID = field.getInt(null);
}
catch(Exception e)
{
// Error
}
return stringID;
}
Set your value like this
int stringVal = getStringIDFromName("i" + j++);
if( stringVal != 0)
txtt.setText(getResource().getString(stringVal));
This would work only if you are doing everything else right.
// initialization for TextView
TextView txtt = (TextView) findViewById(R.id.myTextViewId);
// set the text
txtt.setText(getResources().getString(R.string.mystring));

NXC StrToNum always returns 0

I have a strange problem with NXC. I try to receive a message from android phone and convert the string to a int value.
The problem is it's always 0
Thats just a test programm. so its very strange^^
// MASTER
#define INBOX 0
string tmps1 = "";
string tmps2 = "";
int size;
char ret;
byte tmpi;
bool btn = false;
string msg;
long number;
int countMSG = 0;
int sudoku[9][9];
task main ()
{
SetSensorTouch(IN_3);
SetSensorMode(IN_3, SENSOR_MODE_BOOL);
TextOut (0 , LCD_LINE1 ," Master Receiving ",true );
while (btn == 0)
{
if(ReceiveMessage(INBOX ,true , msg) == NO_ERR)
{
TextOut (0, LCD_LINE3 ,msg, false);
break;
}
Wait(250);
btn = Sensor(IN_3);
}
for(int i = 0; i < 9; i++)
{
tmps1 = SubStr(msg, i, 1);
sudoku[i][0] = StrToNum(strcat(tmps1, "\n"));
TextOut(i*6, LCD_LINE4, tmps1, false);
NumOut(i*6, LCD_LINE5, sudoku[i][0], false);
Wait(1000);
}
Wait(2500);
}
sudoku[9][9] is the problem. there are no 2d arrays in nxc :)
i replaced it with
int sudoku[81];
now it works fine!

Categories

Resources