Ternary operator for Bigdecimal null validation - java

Why am I getting null pointer exception in this code?
BigDecimal test = null;
String data = "";
try {
System.out.println(test==null?"":test.toString());
data = test==null?"":test.toString();
System.out.println(data);
data = data + " " + test==null?"":test.toString(); // catching null pointer in this line
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

It's evaluating the expressions as:
data = (data + " " + test==null)?"":test.toString();
so, since data + " " + test is not null, it attempts to call test.toString() even when test is null.
Change
data = data + " " + test==null?"":test.toString();
to
data = data + " " + (test==null?"":test.toString());

Since Java 8 there is also an alternative way to deal with potential null references: Optional
To prevent an NPE while converting a BigDecimal to a String you can use an Optional like that:
String data = Optional.ofNullable(test).map(BigDecimal::toString).orElse("");
This way you don't need to check test several times if it is null. Having test once wrapped in an Optional you could work on being safe, that any conversion (map) will be performed only if test is not referencing null.

Related

How to compare actual message with expected message when the lines in actual message are changing

I am trying to compare the below messages through java-selenium.But the lines are changing in the actual message during execution.Please let me know how to handle it.
Ex:
String expMsg="Line1.\n"
+ "Line2\n"
+ "Line3\n"
+ "Line4\n"
+ Line5\n" + "\n"
+ "Line6."
String actMsg="Line1.\n"
+ "Line3\n"
+ "Line2\n"
+ "Line5\n"
+ Line4\n" + "\n"
+ "Line6."
I tried the following but it is failing :
if(actMsg.contains(expMsg){
System.out.println("both the messages are same")
}
Please let me know how to resolve this.
Convert your Strings to Streams
Arrays.stream(actMsg.split("\n"));
And then compare streams
Here is how I solved your example:
List<String> expMsg = Arrays.asList("Line1", "Line2", "Line3", "Line4", "Line5", "Line6");
String actMsg = "Line1.\n"
+ "Line3\n"
+ "Line2\n"
+ "Line5\n"
+ "Line4\n" + "\n"
+ "Line6.";
boolean containsAll = expMsg.stream()
//select only elements which are in actMsg
.filter(actMsg::contains) //e -> actMsg.contains(e)
//all strings from expMsg should be present
.count() == expMsg.size();
System.out.println(containsAll);
Split all lines from expMsg and check if all line are in actMsg.
AS per my understanding, the order of actualMessage does not matter, you just need to check all the expectedMessage is present in the actualMessage ? In this case save each line in a separate variable/array then verify each expectedMessage is present in actual using contains.
`
for(i=1, i<6, i++) {
if(actMsg.contains(expMsg+i){
System.out.println("both the messages are same")
}else
System.out.println("both the messages are not same")
}
`
Let me know if this works

Parsing Double from CSV throws RuntimeException

I am trying to read the data from CSV file. everything works fine but when i try to read the data for longitude and latitude. it gives me an below error message.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.yogi.guestlogix/com.example.yogi.guestlogix.MainActivity}: java.lang.NumberFormatException: Invalid double: "EVE"
Caused by: java.lang.NumberFormatException: Invalid double: "EVE"**
MainActivity.java
//Airports data begin
InputStream isss = getResources().openRawResource(R.raw.airports);
BufferedReader readerss = new BufferedReader(
new InputStreamReader(isss, Charset.forName("UTF-8"))
);
String liness = "";
//for airports.csv
try {
readerss.readLine();
while ((liness = readerss.readLine()) != null) {
//split by ',' first
String[] airport = liness.split(",");
//Read the data
AirportsData airdata = new AirportsData();
airdata.setAirportname(airport[0]);
airdata.setAirportcity(airport[1]);
airdata.setAirportcountry(airport[2]);
airdata.setAirportIATAcode(airport[3]);
//airdata.setAirportlang(Double.parseDouble(airport[4]));
//airdata.setAirportlat(Double.parseDouble(airport[5]));
AirportsDatas.add(airdata);
}
} catch (IOException e) {
Log.wtf("My Activity", "Reading data file error " + liness, e);
e.printStackTrace();
}
Log.d("Airline", "name is " + AirportsDatas);
AirportsData.java
public double getAirportlang(double airportlang) {
return airportlang;
}
public void setAirportlang(double airportlang) {
this.airportlang = airportlang;
}
public double getAirportlat( ) {
return airportlat;
}
public void setAirportlat(double airportlat) {
this.airportlat = airportlat;
}
#Override
public String toString() {
return "AirportsData{" +
"airportname='" + airportname + '\'' +
", airportcity='" + airportcity + '\'' +
", airportcountry='" + airportcountry + '\'' +
", airportIATAcode='" + airportIATAcode + '\'' +
", airportlang=" + airportlang +
", airportlat=" + airportlat +
'}';
}
**Any solution for this problem would be greatly appreciated....
The problem with CSV files is, that users (and other programmers) can pretty much write into the file what they want.
In your case, somebody entered a non-number into a CSV cell where you were expecting a double floating point number. Java correctly complains that this cannot be parsed to double. You have two approaches, to treat such situations:
A) Design by Contract
First, you could resolve that by relying on design by contract. You could have a parseLat method:
public Double parseLat(String[] csvRow) {
final String lat= csvRow[4];
assertIsNumeric(lat);
}
private void assertIsNumeric(String lat) {
if(!isNumeric(lat)) {
throw new IllegalArgumentException("Lattitude '" + lat + "' is not numeric");
}
}
There are countless options to implement an isNumeric method, some are discussed here. This will still stop the execution, but it will give a clearer message to users.
B) Defensive Design
A second option, is to provide a parseLAttitude method, that replaces non numeric value with null:
public Double parseLattitude(String[] csvRow) {
final String lattitude = csvRow[4];
if(!isNumeric(lattitude)) {
System.out.println("Could not parse lattitude '" + lat + "'");
return null;
}
return Double.parseDouble(lat);
}
I think the problem is that airport[4] & airport[5] might not be the lon and lat of the airport. If these field contain alpha characters [a-z] you will get an numberFormatException. Can you add the the output when you print airport like:
System.out.println(Arrays.asList(airport));
to the question? Than we will be better able to help you

Print the object and check null

public void printManagerAvailable(Manager mgr) {
System.out.println(" Is Manager object available : " + mgr!=null);
}
Output:
true
Why output is only true here? I'm expecting:
Is Manager object available : true
because it thinks that you are saying " Is Manager object available : " + mgr is all to the left of != null. In other words, it does " Is Manager object available : " + mgr first and then it compares " Is Manager object available : [Object:Manager]" != null.
Do this.
Manager mgr = new Manager();
mgr.setChangeClass(5);
mgr.setChangeClockIn(10);
System.out.println(" Is Manager object available : " + (mgr!=null));
Other answers cover what is happening, this is why it is happening:
The order of operator precedence in Java puts addition, +, ahead of equality, !=.
It's important to realize that it's not caused by left-to-right ordering here.
So what you have is applying the operators in the order like so:
("Is null : " + mgr) != null
And to fix it you can use brackets to force the precedence the other way:
"Is null : " + (mgr != null)
Try using this line of code.
System.out.println(" Is Manager object available : " + (mgr == null ? "is null" : "not null"));

Fetch data of JSON array on Android

I have a few test values in my database and i want to fetch them all in android.
This is my following JSON output of the values inside my Database:
[{"email_address":"rainier_gaari#hotmail.com","comment":"qwehgashdgaskdaweq","date_comment":"2014-06-21","time_comment":"08:28:00","password":"rainier1990"},
{"email_address":"rainier_gaari#hotmail.com","comment":"asfasdasdasd","date_comment":"2104-06-12","time_comment":"09:03:00","password":"rainier1990"}
{"email_address":"rainier_gaari#hotmail.com","comment":"asdsfafd","date_comment":"2014-06-22","time_comment":"04:44:00","password":"rainier1990"}]
But every time that I run this code: http://prntscr.com/3vhs5j , it only gives me the first line of the JSON output.: http://prntscr.com/3vi34b
How can I show all the rows( instead of 1 row)in android?
You can use a JSONObject provided by the android API. The JSONObject has a method called getJSONArray()
http://developer.android.com/reference/org/json/JSONObject.html#getJSONArray(java.lang.String)
your error there is that you are instantiating a JSONArray with your Object. you should try this:
JSONArray myArray =jsonObject.getJSONArray();
This is a snippet of code from one of my apps that worked very well to retrieve Json data.
success = jObject.getInt(TAG_SUCCESS);
vehicles = jObject.getJSONArray(Vehicle.TAG_VEHICLES);
if(success == 1) {
// loop through all the vehicles
for(int i = 0; i < vehicles.length(); i++) {
JSONObject obj = vehicles.getJSONObject(i);
// Get each element based on it's tag
String year = obj.getString(Vehicle.TAG_YEAR);
String model = obj.getString(Vehicle.TAG_MODEL);
String brand = obj.getString(Vehicle.TAG_BRAND);
String color = obj.getString(Vehicle.TAG_COLOR);
String license_plate = obj.getString(Vehicle.TAG_LICENSE);
String main_driver = obj.getString(Vehicle.TAG_DRIVER);
String policeNumber = obj.getString(Vehicle.TAG_POLICENUMBER);
String driversLicense = obj.getString(Vehicle.TAG_DRIVER_LICENSE);
String licenseState = obj.getString(Vehicle.TAG_LICENSE_STATE);
String driverBirthday = obj.getString(Vehicle.TAG_BIRTHDAY_MONTH) + "/" +
obj.getString(Vehicle.TAG_BIRTHDAY_DAY) + "/" +
obj.get(Vehicle.TAG_BIRTHDAY_YEAR);
String driverGender = obj.getString(Vehicle.TAG_DRIVER_GENDER);
ListRowGroup group = new ListRowGroup(brand + " " + year + " " + model, brand);
group.children.add(brand + " " + year + " " + model);
group.children.add(policeNumber);
group.children.add(model);
group.children.add(color);
group.children.add(license_plate);
group.children.add(main_driver);
group.children.add(driversLicense + " - " + licenseState);
group.children.add(driverBirthday + " - " + driverGender);
vehiclesGroup.append(i, group);
}
It would help if you put some of the code for getting the JSON in your question, to make it easier to reference, but, I don't see a loop, which is why it only gets the first line.
You may want to refer to this question: JSON Array iteration in Android/Java but basically use the length property of the JSONArray and loop through that many times.

Adding the results to an arraylist

I am facing some difficulties while assigning the values in an array list. My code is :
while (answer.hasMore()) {
SearchResult rslt = (SearchResult)answer.next();
Attributes attrs = rslt.getAttributes();
System.out.println();
if (attrs.get("department") != null && attrs.get("telephonenumber") != null) {
System.out.println(attrs.get("department") + " " + attrs.get("name") + " " +
attrs.get("Description") + " " + attrs.get("mail") + " " +
attrs.get("telephonenumber")+
attrs.get("samaccountname") + attrs.get("samaccountname") );
}
I want to assign the values of attrs.get("department") + attrs.get("description")+ attrs.get("name")+attrs.get("mail") each one to an array list.
I tried to define at the beginning:
String[] name = new String[100];
and in the while loop i tried to read the name attribute, I tried to do:
name = attrs.get("name");
But it did not work. Can anyone help.
In Java, an array and an ArrayList are quite different.
String[] name_array = new String[100];
creates a fixed-length array of Strings, but
ArrayList name_list = new ArrayList();
creates a variable-length ArrayList of objects (it will grow as you add more objects).
To add an object to an ArrayList, you can use its add() method.
name_list.add("Hello");
However, with an array you need to set the object at a specific index, e.g:
name_array[23] = "Hello";
You need to read a basic tutorial on the Java language and standard library.
You cannot directly assign strings to a array made of string "references". You need to index it first. But it would be much better to actually use a list (and maybe convert it to an array later). Check out List and ArrayList in the Java documentation.
As an example:
Attributes attrs = new Attributes();
List<String> attribValues = new ArrayList<String>();
System.out.println();
if (attrs.get("department") != null
&& attrs.get("telephonenumber") != null) {
System.out
.println(attrs.get("department") + " " + attrs.get("name")
+ " " + attrs.get("Description") + " "
+ attrs.get("mail") + " "
+ attrs.get("telephonenumber")
+ attrs.get("samaccountname")
+ attrs.get("samaccountname"));
attribValues.add(attrs.get("department"));
attribValues.add(attrs.get("telephonenumber"));
}
final String[] attribArray = attribValues.toArray(new String[attribValues.size()]);
First of all define your name as String not as an array of String like this:
String name;
And then read name as:
name = attrs.getString("name");
Now coming back to your issue of populating List, I am sure you will get ready-made answers here but I suggest you to do some reading on how to create and populate a List in Java.

Categories

Resources