java.lang.NullPointerException:尝试调用虚方法'java.util.ArrayList com.example。***。***。DBHelper.getAllPersons()

时间:2017-02-23 16:59:26

标签: android arraylist nullpointerexception initialization

我正在尝试检索由Person对象组成的ArrayList。这是在标题(第2行)中给出错误的部分:

ArrayList<Person> persons = new ArrayList<Person>();
persons = myDb.getAllPersons();

这是Person类:

public class Person {

    private int id;
    private String name;
    private int age;
    private double locationX;
    private double locationY;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getLocationX() {
        return locationX;
    }

    public void setLocationX(double locationX) {
        this.locationX = locationX;
    }

    public double getLocationY() {
        return locationY;
    }

    public void setLocationY(double locationY) {
        this.locationY = locationY;
    }
}

以下是DBHelper类检索Person对象的ArrayList的方法:

    public ArrayList<Person> getAllPersons() {
        ArrayList<Person> array_list = new ArrayList<Person>();

        //hp = new HashMap();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery( "select * from " + ITEMS_TABLE_NAME + " order by item asc", null );
        res.moveToFirst();

        while(res.isAfterLast() == false){
            Person person = new Person();
            person.setName(res.getString(res.getColumnIndex(ITEMS_COLUMN_NAME)));
            person.setAge(res.getInt(res.getColumnIndex(ITEMS_COLUMN_AGE)));
            person.setLocationX(res.getDouble(res.getColumnIndex(ITEMS_COLUMN_LOCATIONX)));
            person.setLocationY(res.getDouble(res.getColumnIndex(ITEMS_COLUMN_LOCATIONY)));
            array_list.add(person);
            res.moveToNext();
        }
        return array_list;
    }

可能是什么原因引起的?我不知道,因为ArrayList个人因为它被初始化而不是空的。

1 个答案:

答案 0 :(得分:1)

这是因为yourvariabe myDb为空。你可能没有初始化它。将myDb初始化为DBHelper类的实例