Carlos Escalera Alonso
Carlos Escalera Alonso

Reputation: 2363

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

Upvotes: 1

Views: 1296

Answers (3)

wmrk
wmrk

Reputation: 11

insert checking element as[i] for null

if (as[i]==null) continue;

at start of for{} block

Upvotes: 1

saum22
saum22

Reputation: 882

Add these two lines

    as[i] == null
    continue;
    b.setUser(convertUser(as[i].getUserR()));

inside your convertProjects Method

Upvotes: 2

Pphoenix
Pphoenix

Reputation: 1473

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.

Upvotes: 1

Related Questions