简体   繁体   English

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

[英]Why is my query of my SQLite database returning null?

I don't know why my method to search my SQLite database and return a cursor is returning null. 我不知道为什么我搜索SQLite数据库并返回游标的方法返回null。 I have loaded the database from a txt file, and while trying to implement a search feature in the app, I am trying to query the same database to return a list of possible matches. 我已经从txt文件加载了数据库,并且尝试在应用程序中实现搜索功能时,我正在尝试查询同一数据库以返回可能的匹配项列表。 However, as I traced back errors, I realized that this method keeps returning null instead of the cursor that I want. 但是,当我追溯错误时,我意识到此方法一直返回null而不是我想要的游标。 Can anyone help me with this? 谁能帮我这个? I'll gladly admit I'm very new to this, and would appreciate any help. 我会很高兴地承认我对此很陌生,并希望获得任何帮助。

Here is my database table, with method getWordMatches() that is returning 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);
    }
}

Again, thank you so much. 再次,谢谢你。

EDIT: 编辑:

the original error that led me to this was that when this was called in another activity: 导致我这样做的原始错误是,在另一个活动中调用此命令时:

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

the log cat returned 日志猫回来了

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

Your code closes the cursor if there's no data in it 如果没有数据,您的代码将关闭游标

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

Doing so gives you a null value in a common use-case. 这样做在常见的用例中为您提供了一个空值。 Afterwards you use the cursor without checking 之后,您使用光标而不检查

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

If this is the only place where you use the cursor unchecked you could just replace it with 如果这是唯一未选中使用光标的地方,则可以将其替换为

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

Otherwise you might need to improve your implementation. 否则,您可能需要改善实施。 Anyway it might be a good idea for you to have a look into DatabaseUtils . 无论如何,对DatabaseUtils来说可能是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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