为什么我的SQLite数据库查询返回null?

时间:2016-06-29 22:18:46

标签: java android database sqlite search

我不知道为什么我搜索SQLite数据库并返回游标的方法返回null。我已经从txt文件加载了数据库,并且在尝试在应用程序中实现搜索功能时,我试图查询同一个数据库以返回可能匹配的列表。但是,当我追溯错误时,我意识到这个方法不断返回null而不是我想要的游标。谁能帮我这个?我很高兴地承认我对此非常陌生,并希望得到任何帮助。

这是我的数据库表,方法getWordMatches()返回null:

public class DatabaseTable {

    public static final String TAG = "ConstantDatabase";

    //the columns included in the table
    public static final String COL_QUANTITY = "QUANTIY";
    public static final String COL_VALUE = "VALUE";
    public static final String COL_UNCERTAINTY = "UNCERTAINTY";
    public static final String COL_UNIT = "UNIT";
    public static final String _id = "_id";

    private static final String DATABASE_NAME = "CONSTANTS";
    private static final String FTS_VIRTUAL_TABLE = "FTS";
    private static final int DATABASE_VERSION = 1;

    private final DatabaseOpenHelper mDatabaseOpenHelper;

    public DatabaseTable(Context context){
        mDatabaseOpenHelper = new DatabaseOpenHelper(context);
    }

    private static class DatabaseOpenHelper extends SQLiteOpenHelper {

        private final Context mHelperContext;
        private SQLiteDatabase mDatabase;

        private static final String FTS_TABLE_CREATE =
                "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
                        " USING fts3 (" +_id+ ", "+
                        COL_QUANTITY + ", " +
                        COL_VALUE + "," +
                        COL_UNCERTAINTY + "," +
                        COL_UNIT + ")";

        public DatabaseOpenHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            Log.e("Database Operation", "DatabaseOpenHelper constructor called");
            mHelperContext = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            mDatabase = db;
            mDatabase.execSQL(FTS_TABLE_CREATE);
            Log.e("Database Operation", "Constants Table Created ...");
            loadConstants();
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
            onCreate(db);
        }

        public SQLiteDatabase getmDatabase(){
            return mDatabase;
        }


//        populating the virtual table with a string reading code

        private void loadConstants() {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        loadConstantss();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();

            Log.e("Loading", "Constants Table Populated ...");
        }

        private void loadConstantss() throws IOException {
            final Resources resources = mHelperContext.getResources();
            InputStream inputStream = resources.openRawResource(R.raw.txt);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] strings = TextUtils.split(line, ",");
                    if (strings.length < 4) continue;
                    long id = addConstant(strings[0].trim(), strings[1].trim(), strings[2].trim(), strings[3].trim());
                    if (id < 0) {
                        Log.e(TAG, "unable to add word: " + strings[0].trim());
                    }
                }
            } finally {
                reader.close();
            }
        }

        public long addConstant(String quantity, String value, String uncertainty, String unit) {
            ContentValues initialValues = new ContentValues();
            initialValues.put(COL_QUANTITY, quantity);
            initialValues.put(COL_VALUE, value);
            initialValues.put(COL_UNCERTAINTY, uncertainty);
            initialValues.put(COL_UNIT, unit);

            return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
        }

        //database openhelper ends
    }

    public Cursor getWordMatches(String query, String[] columns) {
        String selection = COL_QUANTITY + " MATCH ?";
        String[] selectionArgs = new String[] {query+"*"};

        return query(selection, selectionArgs, columns);
    }

    public Cursor query(String selection, String[] selectionArgs, String[] columns) {
        SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
        builder.setTables(FTS_VIRTUAL_TABLE);

        Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
                columns, selection, selectionArgs, null, null, null);

        if (cursor == null) {
            return null;
        } else if (!cursor.moveToFirst()) {
            cursor.close();
            return null;
        }
        return cursor;
    }

    public Cursor getAllTitles()
    {
        return mDatabaseOpenHelper.getmDatabase().query(FTS_VIRTUAL_TABLE, new String[] {
                        COL_QUANTITY,
                        COL_UNCERTAINTY,
                        COL_UNIT,
                        COL_VALUE},
                null,
                null,
                null,
                null,
                null);
    }
}

再次,非常感谢你。

编辑:

导致我这样做的原始错误是当在另一个活动中调用它时:

Cursor c=db.getWordMatches(query,colums);
Log.e("cursor returned",c.toString());

log cat返回

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference

1 个答案:

答案 0 :(得分:2)

如果光标中没有数据,您的代码会关闭光标

if (cursor == null) {
    return null;
} else if (!cursor.moveToFirst()) {
    cursor.close();
    return null;
}

这样做会在常见用例中为您提供空值。然后你使用光标而不检查

Log.e("cursor returned", c.toString());

如果这是您取消选中光标的唯一地方,您只需将其替换为

即可
Log.e("cursor returned", String.valueOf(c));

否则您可能需要改进实施。无论如何,你可能需要查看DatabaseUtils