ListView的ArrayList上的Android空指针异常 [英] Android null pointer exception on ArrayList for ListView

查看:68
本文介绍了ListView的ArrayList上的Android空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示数组列表内容的列表视图.我正在使用一个简单的适配器来实现这一点.

I have a listview that shows the contents of an arraylist. I'm using a simple adaptor to make this possible like so.

public static ArrayList<String> homeScreenContacts = new ArrayList<String>();

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
                R.layout.home_screen_contacts_view, NewContact.homeScreenContacts);

第二行给了我一个空指针异常.我想了想,我决定是因为 arrayList 是空的.所以我在 arraylist 声明和 arrayadaptor 声明之间添加了以下行...

The second line is giving me a null pointer exception. I thought about it and I decided it was because the arrayList is empty. So I added the following line between the arraylist declaration and the arrayadaptor declaration...

NewContact.homeScreenContacts.add("A Contact");

这解决了问题,我的代码运行良好,但现在列表视图显示联系人"而我不希望它显示.无论如何要摆脱空指针异常问题,但仍然让数组列表为空?因为我想用用户创建的联系人填充它,而不是硬编码的随机字符串.谢谢.

This solved the problem and my code worked fine but Now the list view shows "A Contact" and I dont want it to. Is there anyway to get rid of the null pointer exception problem but still have the arraylist empty? Because I want to populate it with user made contacts, not hard-coded, random strings. Thank you.

抱歉,arraylist 位于另一个名为 NewContact 的类中,另外,我是刚开始的非常初级的 Android 程序员.

Sorry, The arraylist is located in another class called NewContact, also, I am very beginner Android Programmer I just started.

推荐答案

如果ArrayListArrayList 中没有元素,则不初始化ListView 的简单解决方案ArrayList 为空.

Simple solution just don't initialize the ListView if there is no element in the ArrayList or the ArrayList is null.

if(NewContact.homeScreenContacts != null && NewContact.homeScreenContacts.size() > 0){
   ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
            R.layout.home_screen_contacts_view, NewContact.homeScreenContacts);

   listView.setAdapter(adapter);
}

另外你需要记住,如果你还没有初始化 Adapter 然后不要初始化 ListView 并且在对列表视图进行任何操作之前你应该检查它是 null 还是不是.

Also you need to remember that if you you haven't initialize Adapter then dont initialize the ListView and before any operation on list view you should check is it null or not.

正如您所说,您希望在用户在应用程序中添加一些联系人时进行填充,然后在添加事件时您只需要填充或更新 ListAdapter.

As you have said that you want to populate when user add some contact in the application then on add event only you need to populate or update the ListAdapter.

希望此解决方案能解决您的问题.

Hope this solution will resolve your problem.

这篇关于ListView的ArrayList上的Android空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆