Android - 如何将数据库行放入ListView?

时间:2016-09-15 07:58:33

标签: android sqlite listview

我试图通过将其列在ListView中来查看我的数据库的内容。我究竟做错了什么?目标是在主页上单击按钮后加载页面时加载数据库数据列表。

XML页面只有一个ListView,名为" studentList",位于ScrollView

Java代码:

public class edit_student extends AppCompatActivity {
    private dbasemanager dBase;
    private ListView studentInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_student);

        dBase.openReadable();
        studentInfoList = (ListView)findViewById(R.id.studentList);
        ArrayList<String> dBaseContent = dBase.retrieveRows();
        ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, dBaseContent);
        studentInfoList.setAdapter(arrayAdpt);
        dBase.close();
    }
}

这是openReadable()功能:

public dbasemanager openReadable() throws android.database.SQLException {
    helper = new SQLHelper(context);
    db = helper.getReadableDatabase();
    return this;
}

这是retrieveRows()功能:

 public ArrayList<String> retrieveRows() {
    ArrayList<String> studentRows = new ArrayList<>();
    String[] columns = new String[] {"sid", "first_name", "last_name"};
    Cursor cursor = db.query(Table_Name, columns, null, null, null, null, null);
    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {
        studentRows.add(cursor.getString(0) + ", " + cursor.getString(1) 
                        + ", " + cursor.getString(2));
        cursor.moveToNext();
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    return studentRows;
}

logcat的:

logcat

1 个答案:

答案 0 :(得分:1)

第17行有一个空指针。

在调用它之前需要构造databasemanager对象

public class edit_student extends AppCompatActivity {
    private dbasemanager dBase;
    private ListView studentInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_student);

        // construct databasemanager
        dBase = new dbasemanager(...);

        dBase.openReadable();
        studentInfoList = (ListView)findViewById(R.id.studentList);
        ArrayList<String> dBaseContent = dBase.retrieveRows();
        ArrayAdapter<String> arrayAdpt = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, dBaseContent);
        studentInfoList.setAdapter(arrayAdpt);
        dBase.close();
    }
}

顺便说一下,我建议你使用java代码约定来命名类。 例如:edit_student应为editStudent,dbasemanager应为DBManager或DbManager。