简体   繁体   中英

Android NullPointerException while retrieving data from SQLite Database and storing it in an Array

I am trying to retrieve string data from a column in database and insert into a string array in android. I have used the following code to retrieve data - (helper.java)

public String[] personslist() {
                // TODO Auto-generated method stub
                int i=0;
                Cursor c=myDataBase.rawQuery("select PersonName from Persons;",null);
                String[] values = {};

            for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
                   values[i] = c.getString(c.getColumnIndex("PersonName"));
                   i++;
                }
            return values;


        }

I have used the following code in "adapter.java" class to return the data returned by personslist().

public String[] plist() {
    // TODO Auto-generated method stub

    String[] persons = mDbHelper.personslist(); //this is line no. 131 in adapter class
    return persons;
}

While I am running the application, it is getting crashed and showwing the following error

09-08 08:23:19.715: E/AndroidRuntime(29373): Caused by: java.lang.NullPointerException
09-08 08:23:19.715: E/AndroidRuntime(29373):    at com.example.fromstart.adapter.plist(adapter.java:131)

The query, when run on sqlitebrowser, it returns four rows of four persons names. But, while running on an application, it is returning NullPointerException. Can you please suggest me, where I might have gone wrong?

Thanks in advance.

mDbHelper is null. That's what's throwing your exception. Make sure it gets initialized.

Check where you are initialzing the mDbHelper. You are doing mDbHelpe.personslist(). and here your mDbHelper could be Null and so nullpointer exception.

Did u do anything similar to this to initialize

Context context;
SQLiteDatabase db = null ;
CallDBHelper dbHelp = null;

       public Constructor(Context context) {
            this.context = context;
            dbHelp = new CallDBHelper(context);
            db = dbHelp.getWritableDatabase();
       }

       Cursor c = db.query(...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM