简体   繁体   中英

How Do I get Data from SQLite DB to other activity which has ListView

I want to get the data from getName() method which is in Database class and put those data into ListView.Can anyone please help me out here. It crashes everytime I try to open this activity.

Caused by : java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.addAll(java.util.Collection)' on a null object reference"

This is the Error msg that appears when I run below code:

public class ListActivity extends android.app.ListActivity {
    ListView mListNames;
    ArrayList<String> mNames;
    DBForm dbForm = new DBForm(this);`

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        mListNames = (ListView) findViewById(android.R.id.list);

        mNames.addAll(dbForm.getName());
        this.setListAdapter(new ArrayAdapter<>(this, R.layout.list_head, mNames));

    }
}

And this how I store and Retrieve the data inside DB class:

public ArrayList<String> getName() {
        ArrayList<String> array_list = new ArrayList<>();

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res = db.rawQuery("select name from contacts" , null);
        res.moveToFirst();

        while (!res.isAfterLast()) {
            array_list.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_NAME)));
            res.moveToNext();
        }
        res.close();
        return array_list;
    }

Your problem in getName() method. Maybe your table is empty. You need to check null of your cursor before loop it. Like below:

if (cursor.moveToFirst()) {
       while (cursor.isAfterLast() == false) {
         String name = cursor.getString(cursor.getColumnIndex(countyname));
         list.add(name);
         cursor.moveToNext();
       }
}

Refer to: Get all rows from SQLite

So I made a silly mistake here in defining the target XML file.I choose one layout file and instead of choosing the textView id from the same layout file I accidently put another layout files textView id.

adapter = new ArrayAdapter<>(this, R.layout.list_view, R.id.list_names, mNames);
mListNames.setAdapter(adapter);

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