尝试在JSF页面</string>中显示List <string>时出现java.lang.NullPointerException

时间:2012-07-17 17:20:39

标签: java jsf jsf-2

当我尝试在JSF页面中向国家/地区显示Java List<String>时,我在JSF页面中遇到了非常奇怪的问题。这是代码:

 private List<String> listCountries;

    // Get the list with Countries
    public List<String> getlistCountries() { 
        // Generate List of Countries
        initlistCountries();
        return listCountries;
    }

    public void initlistCountries(){
        listCountries.add("Afghanistan");
        listCountries.add("Albania");
        listCountries.add("Algeria");
        listCountries.add("Andorra");
        listCountries.add("Angola");
        ......
    }

这段代码是否正确?我不能使用@PostConstruct,因为我已经使用过它了。

加载JSF页面时出现错误:

java.lang.NullPointerException
    at com.DX_57.AC_57.AddAccount.initlistCountries(AddAccount.java:344)
    at com.DX_57.AC_57.AddAccount.getlistCountries(AddAccount.java:339)

3 个答案:

答案 0 :(得分:5)

您尚未初始化listCountries,请将其设为

 public void initlistCountries(){
        listCountries = new ArrayList<String>();
        listCountries.add("Afghanistan");
        listCountries.add("Albania");
        listCountries.add("Algeria");
        listCountries.add("Andorra");
        listCountries.add("Angola");
        ......
    }

答案 1 :(得分:1)

初始化arraylist。

private List<String> listCountries=new ArrayList<String>();

答案 2 :(得分:1)

看起来你没有初始化listCountries。

public void initlistCountries()
{
        listCountries = new ArrayList< String >(); // Add this line.

        listCountries.add("Afghanistan");
        listCountries.add("Albania");
        listCountries.add("Algeria");
        listCountries.add("Andorra");
        listCountries.add("Angola");
        ......
}