How to avoid argument might be null - android

I am getting a warning Argument amountTarget might be null. Is there any way to ignore this warning?
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("amountTarget");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.checkBox.setChecked(true);
//getting warning argument exception on amountTarget
int x = Integer.parseInt(amountTarget) * amountX - deductAmount;
holder.tx_counter.setText(x);
}

check that amountTarget isn't null by doing one of these:
if(amountTarget != null){
int x = Integer.parseInt(amountTarget) * amountX - deductAmount;
}
or initialize the variable to something before using it, for example
amountTarget = 0
int x = Integer.parseInt(amountTarget) * amountX - deductAmount;
alternatively you could also do something like this
if (amountTarget == null){
amountTarget = 0
}

Related

how put the varibale x and y defined to make sum function because i only have this way for null safety

how i fix these problem and make x and y to can sum it ,because the vs code tell me the x and y does not Undefined name 'y' and Undefined name 'x'
import 'dart:io';
void main() {
print('enter your first number ');
var s = stdin.readLineSync();
//for null safety
if (s != null) {
int x = int.parse(s);
}
print('enter your second number');
var a = stdin.readLineSync();
if (a != null) {
int y = int.parse(a);
}
print('the sum is');
//here can not see the x and y varibale how i can put it
int res = x + y;
print(res);
}
if (s != null) {
int x = int.parse(s);
}
Means here x is only available inside if statement.
Variables that are out of the scope to perform int res = x + y;.
You can provide default value or use late
import 'dart:io';
void main() {
print('enter your first number ');
var s = stdin.readLineSync();
late int x ,y; // I pefer providing default value x=0,y=0
//for null safety
if (s != null) {
x = int.parse(s);
}
print('enter your second number');
var a = stdin.readLineSync();
if (a != null) {
y = int.parse(a);
}
print('the sum is');
int res = x + y;
print(res);
}
More about lexical-scope on dart.dev and on SO.
In some cases, your variable might not get initialized with an int and it can be left as a null value, like in the if statement in your code (If the statement doesn't get triggered then the variables will be set as null). And dart with null safety ON doesn't allow that.
SOL: Initialize your variable with a default value or use the late keyword in front of them, while declaring.
var a=0;
var b=0;
OR
late var a;
late var b;

How to resolve java.lang.StringIndexOutOfBoundsException?

I am getting an error, while calculating on String,
java.lang.StringIndexOutOfBoundsException: length=4; regionStart=5; regionLength=2
My implementation is below.
private void initializeMyPLsAllotted() {
int theMonthWhenICame = Integer.parseInt(myDateHired.substring(5, 7)); //This line is showing the error
int theYearWhenICame = Integer.parseInt(myDateHired.substring(0,4));
int theCurrentMonth = Integer.parseInt(todaysDate.substring(5, 7));
int theCurrentYear = Integer.parseInt(todaysDate.substring(0, 4));
int myTotalMonths = (theCurrentYear - theYearWhenICame)*12 + theCurrentMonth - theMonthWhenICame;
if (myTotalMonths > 6) {
numberOfPLsAllotted = 2;
} else {
numberOfPLsAllotted = 0;
}
myPLs = numberOfPLsAllotted;
}
java.lang.StringIndexOutOfBoundsException: length=4; regionStart=5; regionLength=2
it clearly says that length of your string is 4 and you are trying to fetch sub-string from index 5. make sure your string is valid
you can check something like that to avoid crashing your app
private void initializeMyPLsAllotted() {
if(myDateHired.length() > 7 && todaysDate.length() > 7){
int theMonthWhenICame = Integer.parseInt(myDateHired.substring(5, 7));
int theYearWhenICame = Integer.parseInt(myDateHired.substring(0,4));
int theCurrentMonth = Integer.parseInt(todaysDate.substring(5, 7));
int theCurrentYear = Integer.parseInt(todaysDate.substring(0, 4));
int myTotalMonths = (theCurrentYear - theYearWhenICame)*12 + theCurrentMonth - theMonthWhenICame;
if(myTotalMonths>6) {
numberOfPLsAllotted = 2;
} else {
numberOfPLsAllotted = 0;
}
myPLs = numberOfPLsAllotted;
} else {
// print some error message
}
}
StringIndexOutOfBoundsException means that the section you're trying to substring is outside of the string length.
Example
String test = "123";
String testSubstringOne = test.substring(0, 1);
//testSubstringOne -> "1"
String testSubstringTwo = test.substring(0, 5);
//testSubstringTwo -> java.lang.StringIndexOutOfBoundsException
Make sure your myDateHired has the value you expect.
Tip from the coach
You say that those values are from a server... Maybe you should look into returning data in a more friendly format such as json.
As doc says, the IndexOutOfBoundsException will be throwed when:
if the beginIndex is negative, or endIndex is larger than the length
of this String object, or beginIndex is larger than endIndex
so check myDateHired before using it.

checking if variables are empty otherwise get the value

I want to get value from several variables for example user1, user2, user3, user4.
how to check if variables are empty otherwise get the value and ignore variables that empty.
how I achieve this?, and sorry for newbie question...
if I do this
if(user1 != null && user2!= null && user3 != null && user4 != null){
user1.getText(); // or v1 = user1.value();
user2.getText(); // or v2 = user2.value();
user3.getText(); // or v3 = user3.value();
user4.getText(); // or v4 = user4.value();
}
which I dont want to do that, I just want to get the variable which had value in it and save it in array
Try with the following code.
ArrayList<String> listItems=new ArrayList<String>();
if(user1!=null)
{
listItems.add(user1.getText());
}
if(user2!=null)
{
listItems.add(user2.getText());
}
if(user3!=null)
{
listItems.add(user3.getText());
}
if(user4!=null)
{
listItems.add(user4.getText());
}
String [] arrayData = listItems.toArray(new String[listItems.size()]);
Note:You can also use isEmpty() method instead of checking for not a null value.
You mean a null check?
Value v1;
Value v2;
if (user1 != null) {
v1 = user1.value();
}
if (user2 != null) {
v2 = user2.value();
}
...etc
If you are dealing with String values then you may want to check the empty or null using TextUtils.isEmpty(str) API
public static boolean isEmpty (CharSequence str) Returns true if the string is null or 0-length.
if(user1!=null && !TextUtils.isEmpty(user1.getText()){
//not empty or null
}

Why is this code throwing NumberFormatException Invalid int: ""?

I'm trying to get it to if a user doesn't enter a value in the EditText boxes, the initial value is set to 0 (to prevent the crash error NumberFormatException Invalid int: "") which is thrown assuming because there is no integer value to read, since the user didn't input one in this case.
I've tried a number of things most recently this:
String boozeAmount = boozeConsumed.getText().toString();
if (boozeAmount == "" || boozeAmount == null){
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
}
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
But it seems to still throw the same error, not sure why the int values aren't being set to 0?
Throwing error on
int boozeOz = Integer.parseInt(boozeAmount) * 12;
if (boozeAmount == "" || boozeAmount == null){
It can be easily deduced from your explanation that this particular if statement is returning true, that's why your string value is not being set to "0".
Strings in Java are not primitive, i.e they cannot be compared with the comparator ==.
You need to use the method equals to compare strings, as in boozeAmount.equals("").
Apache Commons has a StringUtils utility that can check if strings are null or empty.
Check out isEmpty and isBlank.
you dont compare strings with == you compare it with .equals()
Change it to:
if (boozeAmount.equals("") || boozeAmount == null)
Although it's probably safest to also do:
if (...)
{
// just set it to zero and skip even trying to parse
}
else
{
// do the actual parsing
}
Whenever you are fetching a string value from the EditText always trim that variable to avoid any white spaces from EditText.
String boozeAmount = boozeConsumed.getText().toString().trim(); // apply Trim
// Always compare strings with `equals()` method in Java & Android
if ( boozeAmount.equals( "" ) || boozeAmount == null )
{
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
}
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
You could check if it's blank and then fill it with 0 and then get the input.
Also, always compare string values with .equals and use .trim() to get rid of whitespace so that it's recognized as invalid input as well.
if (boozeConsumed.getText().toString().trim().equals("")) {
// if (boozeConsumed.length() == 0) { // doesn't consider spaces though
boozeConsumed.setText("0");
}
String boozeAmount = boozeConsumed.getText().toString();
int boozeOz = Integer.parseInt(boozeAmount) * 12;
double beerCalc = boozeOz * 4 * 0.075;
Or just do this, because you don't need to parse it to an integer if you know there's nothing there:
String boozeAmount = boozeConsumed.getText().toString();
int boozeOz = 0;
double beerCalc = 0;
if (boozeAmount.trim().equals("") || boozeAmount == null){
boozeConsumed.setText("0");
boozeAmount = boozeConsumed.getText().toString();
} else {
// only parse it if there's something there
boozeOz = Integer.parseInt(boozeAmount) * 12;
beerCalc = boozeOz * 4 * 0.075;
}

String array index error

I use the following method, but every time i use it i got error.
I cant figure out why because i perfrom this checking
if(unWanted == null || unWanted[0] == null)
The error is in this code:
unWanted[0] == null
but if i do only
if(unWanted == null)
It doest not see unWaned as null.
Thank for helping :)
the error code:
05-12 06:24:41.293: E/AndroidRuntime(24373): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workoutlog/com.example.workoutlog.AddWorkOutPage}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
My method:
public void checking(){
DataBaseMain data = new DataBaseMain(this);
data.open();
String[] unWanted = data.getAllUnwantedExercies();
data.close();
if(unWanted == null || unWanted[0] == null)
Toast.makeText(this, "good", Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "bad", Toast.LENGTH_LONG).show();
The method to get the String array from my DB.
public String[] getAllUnwantedExercies() {
Cursor c = ourDatabase.query(true, TABLE_NAME, new String[] {COLUMN_NOT_ON_LIST_EXERCISE}, null, null, COLUMN_NOT_ON_LIST_EXERCISE, null, null, null);
int dayExercise = c.getColumnIndex(COLUMN_NOT_ON_LIST_EXERCISE);
if(c.getCount() < 1)
return null;
int f = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false)
f++;
}
String[] list = new String[f];
int j = 0;
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
if(c.getString(dayExercise) != null && c.getString(dayExercise).equals("") == false){
list[j] = c.getString(dayExercise);
j++;
}
}
return list;
}
unWanted[0] == null
It's clear that your array has no values in it. Attempting to reference the first index of an array of length 0, as explained in your stack trace, is a run time error.
unWanted == null
This doesn't work because the array object itself is not null.
A work around
A simple solution here is, at the end of your function, check the length of the array. If it is 0, you know it has no values, and you can return null.
if(list.length == 0)
{
return null;
}
else
{
return list;
}
or more concisely:
return list.length == 0? null:list;
Then when you get your array back from your function, all you need to do is test to check if the array is null.
if(unWanted == null)
{
// Array is empty.
}
Maybe just change this line:
if(unWanted == null || unWanted[0] == null)
By this one:
if(unWanted.length <= 0)
unWanted[0] == null
Here you are trying to check the first position of your array is null or not. Instead of this check your array size is 0 or not.
if(unWanted.length==0){
// your code
}
I hope this will help you.
You need to check that the length is greater than 0. It is not null because you are returning a list albeit an empty list. So it isn't null but also doesn't have a length
unWanted is not null does not mean you can reference it is first element by using unWanter[0] because it might be an empty array.

Categories

Resources