Chaibi Alaa
Chaibi Alaa

Reputation: 1386

Testing if a list is null with Spring

I need to test if a list is empty (meaning table is empty) or not in order to display a different panelGroup for each condition. I'm not an expert in Java, here is what I'm doing :

ManagedBean :

public List<Platform> getPlatformList() {
        if(platformList == null){
            platformList = new ArrayList<Platform>();
            platformList.addAll(getPlatformService().getPlatform());
        }
        return platformList;
    }

    public void setPlatformList(List<Platform> platformList) {
        this.platformList = platformList;
    }

public int getFirstedit() { 
        if(platformList == null){return 1; 
        // Display add form
        }
        else  {return 0;
        // Display update form
        }
            }
    public void setFirstedit(int firstedit) {this.firstedit = firstedit;    }

DAO :

public Platform getPlatformById(int id) {
     List list = getSessionFactory().getCurrentSession().createQuery("from platform where Id=?").setParameter(0, id).list();
      if ( list.size() == 0 )
        return null;
      else
        return (Platform)list.get(0);
    }

public List<Platform> getPlatform() {
    List list = getSessionFactory().getCurrentSession().createQuery("from Platform").list();
    return list;
}

But in index.xhtml, it always shows the condition 1 (like the list is empty) while in a first time, this was correct and I saved a new entry and I verified it exists in the database, but this is still showing 1 as a result for firstEdit.

Upvotes: 0

Views: 84

Answers (1)

pyb
pyb

Reputation: 5269

You're instantiating platformList if it's null in getPlatformList(), so in getFirstEdit the null test is never true:

if(platformList == null){
        platformList = new ArrayList<Platform>();

Test if the list is empty using platformList.isEmpty() from the Collection interface:

public int getFirstedit() { 
    if(getPlatformList().isEmpty()){ // change here
        return 1; 
        // Display add form
    }
    else  {
        return 0;
        // Display update form
    }
}

Upvotes: 2

Related Questions