Unable to get values from ArrayList - java

I have an ArrayList which takes an object.
Handler.java
public ArrayList<LinkedInAccountObject> getAllLinkedInUsersFromDatabase(){
LinkedInAccountObject lao = new LinkedInAccountObject();
counter++;
lao.setAccountId(rs.getLong("account_id"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setParentId(rs.getLong("parent_id"));
lao.setFirstName(rs.getString("first_name"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setEmail(rs.getString("email"));
lao.setAccessToken(rs.getString("access_token"));
lao.setExpiresOn(rs.getLong("expires_on"));
laoarray.add(counter, lao);
}
My PageLoader.java uses this object to set values
ArrayList<LinkedInAccountObject> laoarray = lndb.getAllLinkedInUsersFromDatabase();
for (LinkedInAccountObject lao : laoarray) {
LinkedInPageObject lpo = new LinkedInPageObject();
lpo.setCompanyID(lao.getParentId());
lpo.setComment(lao.getComment());
//lpo.setDescription(obj.getString("description"));
//lpo.setTitle(obj.getString("title"));
}
But im unable to use the lao object to get the details, getting an null pointer.
when i print the lao object, it gives the result as below,
array objects[null, LinkedInAccountObject [accountId=xxx,
parentId=xx, expiresOn=xxx]]

I would suggest that you replace your loop in the second code with the following:
Iterator<LinkedInAccountObject> iterator = laoarray.iterator();
while(iterator.hasNext()){
LinkedInAccountObject lao = iterator.next()
LinkedInPageObject lpo = new LinkedInPageObject();
lpo.setCompanyID(lao.getParentId());
lpo.setComment(lao.getComment());
//remaining of your code.
}
EDIT
From all the comments that have been posted here I feel that you have initialised the counter variable as 0. In your method getAllLinkedInUsersFromDatabase() you are looping through a loop using rs.hasNext(). Now if this is correct, Then when the first data is being stored, your method creates a new instance of LinkedInAccountObject in lao. Then it goes on to increment counter by 1. So in this case counter was 0 now it becomes 1.
After all your code that you uploaded being executed in the last line it executes laoarray.add(counter, lao);. Here counter being at 1 adds the lao object to the laoarray at position index 1, leaving position index 0 as null. Then it repeats till the end of the ResultSet. This means if your rs variable returned 10 rows, they would be added to laoarray in indices 1 to 10 with 0 index being null.
You could verify if this is happening or not by simply System.out.println("laoarray length = "+laoarray.size()); in your 'PageLoader.java' after you have initialised the laoarray variable.
If this is correct then you could remove the counter++; in the method getAllLinkedInUsersFromDatabase() from its present location and set it after laoarray.add(counter, lao); as shown below:
LinkedInAccountObject lao = new LinkedInAccountObject();
//counter++; remove it from here.
lao.setAccountId(rs.getLong("account_id"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setParentId(rs.getLong("parent_id"));
lao.setFirstName(rs.getString("first_name"));
lao.setLinkedInAccountId(rs.getString("linkedin_account_id"));
lao.setEmail(rs.getString("email"));
lao.setAccessToken(rs.getString("access_token"));
lao.setExpiresOn(rs.getLong("expires_on"));
laoarray.add(counter, lao);
counter++;//place it here

Does you counter start at -1? You do counter++ before adding to the arraylist.
This would mean that the first entry is never filled.
You could edit the code to start at index 0, or in the for loop check if the lao isen't null before handeling it.

This code doesn't seem complete but my guess is that you modify counter before adding the item so if you have an array and start with counter = 0 you add the first element to position 1 and position 0 remains null.
Make it:
LinkedInAccountObject lao = new LinkedInAccountObject();
.... fill object values ......
laoarray.add(counter, lao);
counter++;

Related

How to add the result of a quake entry index to a new list?

What is the variable type of quakeData.get(bigIndex)? How do I add quakeData.get(bigIndex) to my new list? I plan on passing a substring with each iteration to find the Largest quake how should I go about that?
I have also been using the .add() and it hasn't been working. Also, the x value is incorrect because I do not know what the variable type is.
public ArrayList<QuakeEntry>getLargest(ArrayList<QuakeEntry>quakeData,int howMany){
ArrayList<QuakeEntry> answer = new ArrayList<QuakeEntry>();
int bigIndex=indexOfLargest(quakeData);
x=quakeData.get(bigIndex);
// I do not understand what the data type I am getting back and I do not
currently know how to add it to my new Arraylist
answer=answer.set(0,x);"
// I will be adding a for loop and use variable k to replace 0 to get the 2nd, 3rd, 4th,etc highest by passing in a substring with each
// iteration
return answer;
}

ArrayList logic for recent entries?

Basically, i have an ArrayList titled "recentContacts", and i have limited the number of entries to 10.
Now im trying to get the ArrayList to replace all the entries from the first index, after the list is full.
Here is some code to demonstrate...
// Limits number of entries to 10
if (recentContacts.size() < 10)
{
// Adds the model
recentContacts.add(contactsModel);
}
else
{
// Replaces model from the 1st index and then 2nd and 3rd etc...
// Until the entries reach the limit of 10 again...
// Repeats
}
Note: The if statement above is just a simple example, and might not be the correct way to solve the problem.
What would be the most simplest way of achieving this? Thanks!
You have to maintain the index of the next element that would be replaced.
Actually you can use that index even before the ArrayList is "full".
For example :
int index = 0; // initialize the index to 0 when the ArrayList is empty
...
recentContacts.add(index,contactsModel);
index = (index + 1) % 10; // once index reaches 9, it will go back to 0
...

ArrayList for loop iterator causing infinite loop

I'm trying to iterate through an ArrayList and print each element in it but it only outputs the first element in the ArrayList. Then there's an infinite loop and it keeps printing out the first element.
ArrayList<String> startTime = new ArrayList<String>();
for (int i = 0; i < startTime.size(); i++) {
String getTime = startTime.get(i);
getTime = convertTime(getTime);
startTime.add(i, getTime);
System.out.println(startTime.get(i));
}
When you do startTime.add(i, getTime) you are adding an element in the i position. That means in your next iteration, you are going to have an extra element in your list. When you increment the counter and check startTime.size(), it's always going to be true. Hence your infinite loop.
As a suggestion, if you want to add your getTime element, you might want to use some sort of auxiliary structure, like another List.
Definitly use advanced for-loops:
ArrayList<String> startTime = new ArrayList<String>();
for(String aStartTime: startTime){
// do something
}
Try using this for-loop:
for(int i=0,n=startTime.size();i<n;i++){
//your for-loop code here
}
When you were adding elements to startTime, it was increasing its size. Therefore, it upped the boundary that i had to meet infinitely. In my example, n will be set to startTime's size at the beginning of the loop and won't change as the loop executes.
You can try doing the loop backward (from the last element to the first element ) such as:
// assume that I have ArrayList variable named *list*
for(int i = list.size() - 1 ; i >= 0 ; i--){
list.add(//something);
}
this code won't give you an infinite loop since the loop control variable never going to change ( i >= 0 ) even though your list size keeps changing. The lower bound will always be 0 and the i will decrease towards 0

Java List values changes when any change in one of the element is made

I am having a weird issue with java list. Please see the code below:
for ( int i=0; i < tripList.size(); i++ ) {
ModeChoiceTrip trip = tripList.get(i);
int newUniqueId = tripListIds[trip.uniqueId];
int newLinkedId = trip.linkedId >= 0 ? tripListIds[trip.linkedId] : -1;
int jointTripNum = trip.linkedId >= 0 && trip.tourType != TourTypes.SPECIAL_EVENT ? jointTripListIds[trip.linkedId] : 0;
trip.uniqueId = newUniqueId;
trip.linkedId = newLinkedId;
trip.jointTripNum = jointTripNum;
}
In the above code, the values in tripList seem correct but after executing a few iterations (up to i = 6), the values in tripList changes for all the positions.
I cannot provide the whole source code here but showing the snippet of the code where I have an issue.
I found that there are some duplicate trips in tripList. When one of the trips is changed, the copy of it (located at different position) is also changed.
I am guessing this piece of code is executed by multiple threads, Then there is every chance that List could be modified by another thread while this loop is going on.
you could try synchronizing the loop and see if issue gets resolved.
Also, you could try using for-each loop instead of the loop with counter.
for (ModeChoiceTrip trip : tripList) {
.....
}
The issues was the duplicate values in the list. Thus, when I update a value in list the copy to that value changes as well
You set the unique id to -1. So if the trip list id comes in as -1, you grab the index like tripListIds[-1]; which might be the second to the last item in the list.

Java problems with iteration

Currently I am writing a program that must iterate through and arraylist inside of a for loop which looks like this.
List<Integer> currentLevel = new ArrayList<Integer>();
List<Integer> nextLevel = new ArrayList<Integer>();
Iterator<Integer> it = currentLevel.iterator();
currentLevel.add(1);
for(x=0;x<20;x++){
while(it.hasNext()){
int element = it.next();
nextLevel.add(element*2);
if(element%6 == 4){
nextLevel.add((element-1)/3);
}
}
currentLevel.clear();
currentLevel.addAll(nextLevel);
nextLevel.clear();
}
With this code it seams that it only goes through the while loop once. Is this because after the first loop it only adds one number to the nextLevel array and the currentLevel array has the same amount of indexes as before? Or is it something that I am leaving out? If I try to add additional elements to the nextLevel array after the while loop it gives me an error at the line
int element = it.next();
You're entering the for loop several times, but can only enter the while loop on the first pass through the for loop.
The iterator, it is defined outside the for loop and only assigned once.
The first time through the for loop you enter a while loop:
while(it.hasNext()){
int element = it.next();
...
}
which completely exhausts the iterator. Every subsequent time through the for loop, it.hasNext() is false, so the while loop does nothing.
You're also trying to re-use nextLevel and currentLevel, but those are only assigned once. So currentLevel will only contain the last set of elements added to nextLevel.
If I try to add additional elements to the nextLevel array after the while loop it gives me an error at the line
You are probably getting a concurrent modification exception. You can not use an iterator for a list after you modify it. https://stackoverflow.com/a/1496206/20394 explains how to deal with these problems.

Categories