2017-02-23 52 views
-2

我试图检索由Person对象组成的ArrayList。下面是给出了错误的标题(第2行)的一部分:java.lang.NullPointerException:试图调用虚拟方法'java.util.ArrayList com.example。***。***。DBHelper.getAllPersons()

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人被初始化后不是空的。

+2

您初始化了'myDb'对象吗? –

回答

1

这是因为yourvariabe myDb为空。你可能不会初始化它。初始化myDb作为DBHelper类的一个实例

相关问题