2017-02-23 37 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類的一個實例

相關問題