ListView已满,但在尝试更改Backround Color时会出现Null指针异常



我有一个由字符串组成的列表视图。里面有两项。

// System.out.println("X->"+listView.getLastVisiblePosition()+"Y->"+listView.getFirstVisiblePosition());
listView.getChildAt(listView.getLastVisiblePosition()).setBackgroundColor(Color.GREEN);

当我打印最后一个和第一个可见位置时,它会打印1和0;然而,当我尝试更改背景颜色时,它会给出一个空指针预期错误。原因可能是什么?

错误->引起原因:java.lang.NullPointerException:试图在null对象引用上调用虚拟方法"void android.view.view.setBackgroundColor(int(">

这不是必要的,但我也想分享listView的实现,

listView=(ListView)findViewById(R.id.listViewProductList);
if(products!=null){
ArrayList<String> names=new ArrayList<>();
for(int i=0;i<products.size();i++){
names.add("Ürün Adı-> "+products.get(i).getProductName()+"n"+"Konum-> "+ products.get(i).getLocationName());
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, names);
listView.setAdapter(adapter);
}

尝试使用arraylist的索引,而不是listview的索引。像这样的东西:

int lastIndex = products.indexOf(products.get(products.size() - 1 )) ;

int firstIndex = products.indexOf(products.get(0 )) ;

但是您应该确保您的列表既不为空也不为null

listView.getChildAt(lastIndex).setBackgroundColor(Color.GREEN);

listView.getChildAt(firstIndex).setBackgroundColor(Color.GREEN);

最新更新