adding object to list overwrite some results - java

I added objects to list however there was overriding problem.How can solve this? I sended 3 value in transactionIdList in my main method.
these three value to send below method, i want to add all results return. However there is only two results return with bsList which are in the ( basvuru != null && !basvuru.isEmpty())) state.
List<ApplicationResult> bsList = new ArrayList();
Application bsDB = new Application();
for (int i = 0; i < transactionIdList.size(); i++) {
List basvuru = session.createQuery("from Application as bsvr where bsvr.transactionId = :var1").setParameter("var1", transactionIdList.get(i)).list();
if (basvuru == null) {
ApplicationResult bss = new ApplicationResult();
bss.setTransactionId(transactionIdList.get(i));
bss.setBasvuruDurum("no value");
bsList.add(bss);
} else if (basvuru != null && !basvuru.isEmpty()){
ApplicationResult bs = new ApplicationResult();
bsDB = (Application) basvuru.get(0);
bs.setTransactionId(bsDB.getTransactionId());
bs.setBasvuruDurum(bsDB.getDurum());
bsList.add(bs);
}
}

The only explanation is that session.createQuery() returns one List that is not null, but is empty.

It is most likely that basvruru at some time is not null but an empty list. In this case, nothing is added to the bsList.
You probably want to update the if clause to basvuru == null || basvuru.isEmpty(), and just use and else.

in List implementation values never get overridden. You must have some other issue. could be basvuru is not null

Related

Null pointer exception, "Attempt to read from field on a null object reference"

I am making an app in which the user types in a list of tasks, and that list is saved to an array. Each task in the array is an instance of the Assignment class. However, I realized that in java it is not possible to add an element to an array after the array is created. So, what I did was I created an array called tasks which consisted of many null values: Assignment[]tasks = {null, null, null, null, null, null, null, null, null, null, null, null};. When I want to add a task to the array, I just replace the next null value with the object. However, I also need to have an array of just the tasks, with no null values. So I created an array called full_tasks for all of the elements that aren't null:
for (Assignment task: tasks) {
if (task != null) {
realLength += 1;
}
}
Assignment[] full_tasks = new Assignment[realLength];
for (int i=0; i <= full_tasks.length - 1; i++) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}
So now, the full_tasks array should be an array of all the tasks, none of which are null, right? However, when I run the app, it can't launch the activity, an error it says is caused by a null pointer exception:
Caused by: java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.example.lb.homeworkappv11.Assignment.name' on a null object reference
at com.example.lb.homeworkappv11.Schedule.sortTasks(Schedule.java:64)
The line that the error points to is:
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
I'm still not totally sure what a null object reference is, but I think it means that one of the elements in the full_tasks array is null. Would that be correct? And if it is, what can I do to make sure that the full_tasks array is only the non-null elements in the tasks array?
Thank you so much!
Edit: the constructor function for the assignment class is:
public Assignment(String name, int days, int time) {
this.name = name;
this.days_due = days;
this.time = time;
this.toSortBy = "nothing";
}
A null reference is just that null. In your code it is tasks[i].name where you try to call name on tasks[i] so tasks[i] is null.
There is one scenario I can think of, where your code would definitely throw a NullPointerException.
So, I will assume your tasks array can look looks like this:
tasks = [task0, null, task2, task3, null, task5]
Then full_tasks will have a size of 4 but
for (int i=0; i <= full_tasks.length - 1; i++) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}
will throw a NPE as soon as i == 1 because tasks[1] is null.
So, if you want to fill full_tasks with only non-null tasks make sure you got the right indexes of tasks.
Here's what I think
You are just finding the number elements that are not null. You don't know where in the array thest null's are present.
Suppose ONLY the first element is null. So realLength will be 7. The latter for loop runs from i=0 to i=7. When i=0, tasks[i].name tries to access the name field of the first element; but your first element happens to be null`. That's where things go wrong.
Solution:
There are a number of solutions. The most efficient one I can think of uses an ArrayList.
To get around using arrays, you should store the indices of all elements that are not null. That's one way.
Here's another:
for (Assignment task: tasks) {
if (task != null) {
realLength += 1;
}
}
Assignment[] full_tasks = new Assignment[realLength];
int count = 0;
for (Assignment task: tasks) {
if (task != null) {
full_tasks[count] = new Assignment(task.name, tasks.days_due, task.time);
count++;
}
}
You can think of null as something not exists, for example when you try to get task.name, where task is null, you get error, because you try to get name from some something which does not even exists.
Actually what your code is doing now is check how many non-null items in the original array, and try to extract the extra the first n items from the array to a new array.
i.e. if the list is {null, null, non-null, non-null}, it has 2 non-null item, however your code wrongly extracts the list of the first 2 items which are {null, null}
Edit, to actually do what you want:
ArrayList<Assignment> fullTaskList = new ArrayList<Assignment>();
for (Assignment task: tasks) {
if (task != null) {
fullTaskList.add(task);
}
}
//optional
Assignment[] fullTasks = fullTaskList.toArray(new Assignment[fullTaskList.size()]);
The problem in your code is here:
(tasks[i].name, tasks[i].days_due, tasks[i].time).
Although you're counting the real size, there could be some null value in between that is causing it to be get a null object from the list tasks[i].
A good idea to solve this is by using a List instead of an Array. A List can be increased or decreased as you want, you just have to add or remove an item of your object type. For example:
List<Assignment> list = new ArrayList<>();
Assignment assignment1 = new Assignment(etc.);
list.add(assignment1);
list.get(0) //-> returns the Assignment object that you added.
Then you can use list.size() to get the size to know how many items are there, or to remove the last item. And you would have no problems to add new items to the list.
It seems you are trying to copy and compact the tasks array into the full_tasks array (removing the null elements), but you are doing this partially incorrect since you are accessing tasks[i] in the second loop without checking whether its is null.
Instead of:
for (int i=0; i <= full_tasks.length - 1; i++) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}
you could write something like this:
for (int i = 0, f = 0; i < tasks.length; i++) {
if (tasks[i] != null) {
full_tasks[f] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
f++;
}
}
But then again to solve your original problem, regarding the fact that you cannot add any elements to an array, I suggest to use an ArrayList instead of a simple array. This allows you to add items with ArrayList.add(assignment) and remove them again with ArrayList.remove(index).
Seems like "tasks" list is empty. Make sure its get populated or put a null check
like :
if(tasks[i] !=null) {
full_tasks[i] = new Assignment(tasks[i].name, tasks[i].days_due, tasks[i].time);
}

Stop current process of loop when null value and continue with next value

Now when as[i].getUser() = null, the program stops with NullPointerException. But what I want is to stop the current process of the loop only and continue with next value, the best will be from the method convertUser() since it's used in many places. I know that catching the NullPointerException is not recommended.
public Project[] convertProjects(){
ProjectR[] as = getProjects();
Project[] bs = new Project[a.length];
for(int i = 0; i < as.length; i++){
Project b = new Project();
b.setName(as[i].getNameR());
b.setUser(convertUser(as[i].getUserR()));
b.setCenter(convertCenter(as[i].getCenterR()));
bs[i]=b;
}
return bs;
}
private Center convertCenter(CenterR centerR) {
Center centerL = new Center();
centerL.setManager(convertUser(centerR.getUser()));
centerL.setName(centerR.getName());
centerL.setResID(centerR.getID());
return centerL;
}
private User convertUser(UserR uR) {
User userL = new PFPWSUser();
userL.setID(uR.getID());
userL.setFirstName(uR.getFirstName());
userL.setLastName(uR.getLastName());
userL.setEmail(uR.getEmail());
return userL;
}
Add these two lines
as[i] == null
continue;
b.setUser(convertUser(as[i].getUserR()));
inside your convertProjects Method
Check if as[i].getUserR() is null before using it:
if(as[i].getUserR() != null) { // Can use since not null
b.setUser(convertUser(as[i].getUserR()));
}
Since no null values are used, the NullPointerException wont be thrown and the loop will continue.
insert checking element as[i] for null
if (as[i]==null) continue;
at start of for{} block

Adding Element of an Object in an Array in an Array to a String Array

I have a method that is suppose to traverse 2 arrays of Ojbects, the first being Menu of size 50, which contains Recipes, which hold up to 10 elements called ingredients, which holds up to 3 elements each, but I am only looking for their names! I want to take the matching names of those Ingredient elements in the Recipes and add them to my String array and then return it, here is my code...
public class Recipe implements Cloneable
{
String Name;
final int INGREDIENT_ARRAY_MAX = 10;
Ingredient Ingredients[] = new Ingredient[INGREDIENT_ARRAY_MAX];
public class RecipeBook
{
final static int MENU_ARRAY_MAX = 50;
static Recipe Menu[] = new Recipe[MENU_ARRAY_MAX];
public static String[] getRecipesByIngredient(String ingredientName)
{
String[] targetRecipes = new String[MENU_ARRAY_MAX];
int counter = 0;
for (int j = 0; j < Menu.length; j++)
{
if (Menu[j] == null)
{
break;
}
else
{
for (int k = 0; k < Menu[j].Ingredients.length; k++)
{
System.out.println(Menu[j].Ingredients[k]);
if (Menu[j].Ingredients[k].getName().equals(ingredientName))
{
targetRecipes[counter] = Menu[j].getName();
counter++;
}
}
}
}
return targetRecipes;
}
}
}
Now I know it doesn't work and why, but the solution I am not sure about. At the moment I only have 3 Recipes and 3 Ingredients in each recipe! The stuff up top is just for reference, those are the object arrays of RecipeBook (Menu) and Recipes (Ingredients).
Now when ran this code gets me into a NullPointerException because tries testing nulls against Strings, but how could I make it check through the Recipe, if it doesn't find anything, it moves on to the next Recipe in Menu, if it does, it simply adds it but continues to check til finish. I tried adding "if" statements checking for nulls and not nulls but it becomes convoluted and it still doesn't get my program to return to checking the rest of the arrays. I know the first "if" can stay because, well if the spot i check in Menu is null, the rest of it must be null so there's no point in going farther. But how do I check the Ingredients array, find something, add it, and go back to sifting through the Menu for recipes with that ingredient? Is it possible to add an if inside the inner loop to check for null and if it is, just go back to the outer loop?
update if conditions as below
1st if condition :
if (Menu[j] == null || Menu[j].Ingredients == null || Menu[j].Ingredients.length ==0)
2nd if condition :
if (Menu[j].Ingredients[k] != null && ingredientName.equal(Menu[j].Ingredients[k].getName()))
please let me know if there any issues.
I don't know how you fill the recipe array but what i can say is that your code is missing a lot of null checks. I would go this way (code not compiled / tested):
public static String[] getRecipesByIngredient(String ingredientName) {
String[] targetRecipes = null;
// check input parameter ingredientName against null and do lookup only if it is not null
if(ingredientName != null) {
// init the result array and do look up
targetRecipes = new String[MENU_ARRAY_MAX];
for (int j = 0; j < Menu.length; j++) {
// you might run into NPE if Menu[j] or if the array of ingredients in Menu[j] (Menu[j].Ingredients) is null
if(Menu[j] != null && Menu[j].Ingredients != null) {
for (int k = 0; k < Menu[j].Ingredients.length; k++) {
// Menu[j].Ingredients[k] may also be null
// Menu[j].Ingredients[k].getName() may also be null but no need to check it since
// you call equals of the string object ingredientName witch you already checked
// and equals(null) is always false in that case
if (Menu[j].Ingredients[k] != null && ingredientName.equals(Menu[j].Ingredients[k].getName()) {
// here you might want to check Menu[j].getName() against null otherwise you'll have
// a null inside your result array (this is some like a land mine) unless you want
// to check against null while iterating over you result array
if(Menu[j].getName() != null) {
targetRecipes[counter++] = Menu[j].getName();
}
}
}
} // save the else...
}
} // else targetRecipes is still null, with witch you may want to say "no result found"
return targetRecipes;
}

Some fields in a Java array are null, handling of these

I have the following code snippet.
Explanation:
I have the array called result.
This array consists of different String attributes like "city", "countryName" and "IATA".
With a for loop, I try to access and retrieve all the aforementioned fields.
My problem now is: While "city" and "countryName" always have a value, "IATA" sometimes does not have a value and thus returning me "null", which leads to the nullPointerException as soon as I access an empty "IATA".
I tried this:
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
But, this if condition is not working as I try to access a field which is null.
Has anyone an idea how I can solve this?
Here is the relevant code snippet:
private String[] startIATA = new String[200]; //That is more than long enough
...
for (int count = 0; count < result.getAirports().length(); count++) {
AirportsEntry entry = result.getAirports().get(count);
// Block for StartAirport
HorizontalPanel hp = new HorizontalPanel();
hp.setSpacing(5);
hp.add(new Label(entry.getCity()));
hp.add(new Label(entry.getCountryName()));
hp.add(new Label(entry.getIATA()));
GWT.log("IATA: " + entry.getIATA());
if(entry.getIATA().equals(null)) {
} else {
startIATA[count] = entry.getIATA();
}
startAirportVP.add(hp);
}
Thank you very much for your time and your help!
Perform a simple null check prior to accessing the property of the object.
if(entry != null && entry.getIATA() != null){
startIATA[count] = entry.getIATA();
}
You cannot use equals method to check for null. Use ==:
if (entry.getIATA () == null)
use this:
if (entry.getIATA() != null)

How to avoid null pointer error

I trying to find whether the elements of 2 arrayLists are match or not.
But this code give me error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException since some of the elements are null.
How can I solved this problem?
String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));
String choice []={null,"High","Low","High",null,"Medium"};
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));
//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
if(!(m.get(i).equals(n.get(i)))){
result= true;
break;
}
}
return result;
}
Just use Arrays.equals, like so:
String level []={"High","High","High","High","High","High"};
String choice []={null,"High","Low","High",null,"Medium"};
return Arrays.equals(level, choice);
The problem is that you are calling the equals method on some elements without first checking for null.
Change to:
for(int i=0; i<m.size(); i++){
if(m.get(i) != null && !(m.get(i).equals(n.get(i)))){
result = true;
break;
}
}
Or if you want to allow two null values to compare equal:
for(int i=0; i<m.size(); i++){
if (m.get(i) == null) {
if (n.get(i) != null) {
result = true;
}
} else if(!(m.get(i).equals(n.get(i)))){
result = true;
}
if (result) {
break;
}
}
One thing I don't get - why are you setting result to true when you find a mismatch? Don't you want to return true if both lists match and false otherwise?
The root of this problem could be you are using null as an actual value.
Just looking at your code you could use enum and instead of null use an EMPTY value. Then you can actually compare with in a list without nullpointerexceptions.
Check this out:
http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
Also try to avoid using arrays. Just use List but use the proper type. Don't use List<Object> that is almost never valid.
null should indicate an error or testing only. It should never be used in valid code as you will create null pointer exception bugs during runtime.
if you know the first list never contains nulls switch the call around
if(!(n.get(i).equals(m.get(i)))){
also specifying ArrayList<Object> is bad practice, use List<String> if it is actually String objects.
Check if the objects are the same object (or both null) first. Check for null before you do the equals() test.
boolean result = true;
String level[] = { "High", "High", "High", "High", "High", "High" };
ArrayList<String> n = new ArrayList<String>(Arrays.asList(level));
String choice[] = { null, "High", "Low", "High", null, "Medium" };
ArrayList<String> m = new ArrayList<String>(Arrays.asList(choice));
// Check if the two arrayList are identical
for (int i = 0; i < m.size(); i++) {
String mElement = m.get(i);
String nElement = n.get(i);
if (mElement == nElement) {
result = true;
} else if ((mElement == null) || (nElement == null)) {
result = false;
break;
} else if (!(m.get(i).equals(n.get(i)))) {
result = false;
break;
}
}
return result;
}
Rewrite your if like this in order to check for both double-nullity and single-nullity:
if((m.get(i) == null && n.get(i) == null) || (m.get(i) != null && !(m.get(i).equals(n.get(i)))))
Rather than solving this specific problem, give yourself a tool you can use over and again, e.g.:
public static final boolean areEqual(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
...in some handy utility class, then use that in your loop.
But of course, for this specific requirement, derivation has the right answer (use java.util.Arrays.equals(Object[],Object[])).
Remove NULLs
You can remove NULL values from your List objects before processing.
myList.removeAll( Collections.singleton( null ) );
The Collections class is a bunch of convenient utility methods. Not to be confused with Collection (singular), the interface that parents List and is implemented by ArrayList.
See this posting, Removing all nulls from a List in Java, for more discussion.

Categories