SQLIte错误(返回带对象的ArrayList)

时间:2016-11-26 16:36:02

标签: android sql sqlite

我需要帮助来返回一个包含学生的stduent_id的ArrayList对象,并且只选择状态为' Graduated'或者'无效'

public class DBHelper extends SQLiteOpenHelper { 
private static final String DATABASE_NAME= "TPRRHSCHOOL";
private static final String TABLE_STUDENT = "student";
private static final String COLUMN_ID = "student_id";
private static final String COLUMN_STATUS = " status";
private static final int DATABASE_VERSION = 1;



public ArrayList<String> getStudents(){
ArrayList<String> students = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null; 
if (cursor.getCount() > 0){
for (int i = 0; i < cursor.getCount(); i++){
Cursor rawQuery (String status, String[] 'Graudate', String[] "Inactive")
cursor.moveToNext();

db.close;
return getStudents;

&lt; -I认真地不知道哪个部分是错的,因为这些教程有很多看起来和我不相符的术语,而且我从昨天起就开始尝试了,所以我真诚地需要你的帮助! - &GT;

1 个答案:

答案 0 :(得分:0)

根据给定的信息,我将假设您当前正在获取NullPointerException,并且还不知道如何查询SQL数据库。

我将首先直接回答您的问题,最后提供一些资源,以帮助您了解正在发生的事情。

NPE来自将Cursor初始化为null,并立即调用getCount()。要正确初始化光标,您需要创建一个查询。我想它看起来类似于:

Cursor cursor = getReadableDatabase().query(
        TABLE_STUDENT,
        new String[] { /* this is an array of column names that I want */ },
        COLUMN_STATUS + " in (?, ?)", // this is Prepared Statement syntax
        new String[] { 'Graudate', 'Inactive' },
        null,
        null,
        null  // Assuming you don't care about order
);

这是在创建类似于

的SQL语句
SELECT * FROM student WHERE status IN ('Graudate', 'Inactive')

其中*将替换为您需要的实际列名。

您现在可以使用光标检索数据:

if(cursor != null) { //makes sure that the query returned a cursor
    try {
        if(cursor.moveToFirst()) { //makes sure that the cursor contains data
            List<Student> students = new ArrayList<>(cursor.getCount());
            do {
                Student s = new Student();
                // do this for each variable in student
                s.setSomeVar(
                    cursor.getString(
                        cursor.getColumnIndexOrThrow("SOME_COLUMN_NAME")
                    )
                );
            } while(c.moveToNext()) // position the cursor at the next index
            return students;
        }
    } finally {
        cursor.close();
    }
}

有关创建和理解上述光标的详细信息,请查看javadoc here。您也应该熟悉SQL。 This有基础知识。

与早期安装到Android中的大多数内容一样,SqlLite查询结构过于冗长,可能会对新手产生不利影响。我建议使用谷歌搜索你不熟悉的任何术语。

我建议:

  • SQL select语句
  • SQL预备声明
  • Android Sqlite游标示例