Android Studio搜索现有的sqlite db

时间:2018-03-15 19:35:44

标签: sqlite android-studio android-sqlite sqliteopenhelper

所以我正在开发一个应用程序,我希望用户在我的数据库中搜索食物项目,然后返回所有与搜索条件匹配的食物名称的列表视图。我已经创建了slqite数据库并将其添加到assets文件夹中。该数据库名为 foodDatabase.db

我已经像这样创建了数据库助手:

package com.example.codebind.databasedemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by tom on 15/03/2018.
 */

public class FoodDatabaseHelper extends SQLiteOpenHelper{
    public static final String DATABASE_NAME = "FoodDatabase.db";
    public static final String TABLE_NAME = "dataset";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "Food";
    public static final String COL_3 = "Description";
    public static final String COL_4 = "Protein";
    public static final String COL_5 = "Fat";
    public static final String COL_6 = "Carbohydrate";
    public static final String COL_7 = "Energy";
    public static final String COL_8 = "Starch";
    public static final String COL_9 = "Sugar";
    public static final String COL_10 = "Cholesterol";

    public FoodDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("create table " + TABLE_NAME +" (ID INTEGER 
PRIMARY KEY AUTOINCREMENT,FOOD TEXT,DESCRIPTION TEXT,PROTEIN BLOB,FAT 
BLOB,CARBOHYDRATE BLOB,ENERGY BLOB,STARCH BLOB,SUGAR BLOB,CHOLESTEROL BLOB) 
");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
        onCreate(sqLiteDatabase);
    }
}

目前我的MainActivity.java很干净。我还没碰过它。

我正在寻求有关如何添加监听器的指导,以便当用户输入食物名称时,应用程序将返回foodDatabase.db中符合搜索查询的所有食物。

由于

1 个答案:

答案 0 :(得分:0)

您的搜索基础将是基于FOOD列的查询(我相信)。

e.g。 SELECT * FROM dataset WHERE FOOD LIKE '%your_food%'

例如,假设您的数据库包含数据(注意只有food和id列已经填充了数据): -

enter image description here

然后查询SELECT * FROM dataset WHERE FOOD LIKE '%mash%'将导致: -

enter image description here

  • 即。 ID为2和3的食物含有食物 mash

您可以使用SQLiteDatabase query 方法运行此查询。 query方法返回带有提取数据的Cursor。因此,DatabaseHelper中的方法可能是: -

public Cursor getFoodsWithProvidedFood(String provided_food) {
    return this.getWritableDatabase().query(
            TABLE_NAME,
            null,
            COL_2 + " LIKE '%" + provided_food + "%' ",
    null,
            null,
            null,
            null
    );
}

将此转换为完整但非常基本的应用程序: -

数据库助手 - FoodDatabaseHelper.java

public class FoodDatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "FoodDatabase.db";
    public static final String TABLE_NAME = "dataset";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "Food";
    public static final String COL_3 = "Description";
    public static final String COL_4 = "Protein";
    public static final String COL_5 = "Fat";
    public static final String COL_6 = "Carbohydrate";
    public static final String COL_7 = "Energy";
    public static final String COL_8 = "Starch";
    public static final String COL_9 = "Sugar";
    public static final String COL_10 = "Cholesterol";

    SQLiteDatabase sqLiteDatabase; //<<<< Added

    public FoodDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        sqLiteDatabase = this.getWritableDatabase(); //<<<< Amended
    }

    //@Override
    public void onNotRecommendedCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("create table " + TABLE_NAME +
                        " (ID INTEGER PRIMARY KEY AUTOINCREMENT," +
                "FOOD TEXT," +
                "DESCRIPTION TEXT," +
                "PROTEIN BLOB," +
                "FAT BLOB," +
                "CARBOHYDRATE BLOB," +
                "ENERGY BLOB," +
                "STARCH BLOB," +
                "SUGAR BLOB," +
                "CHOLESTEROL BLOB)");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtsql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
                "(" +
                COL_1 + " INTEGER PRIMARY KEY, " +
                COL_2 + " TEXT, " +
                COL_3 + " TEXT, " +
                COL_4 + " BLOB, " +
                COL_5 + " BLOB, " +
                COL_6 + " BLOB, " +
                COL_7 + " BLOB, " +
                COL_8 + " BLOB, " +
                COL_9 + " BLOB, " +
                COL_10 + " BLOB " +
                ")";
        db.execSQL(crtsql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME);
        onCreate(sqLiteDatabase);
    }

    public void insertFood(
            String food,
            String description,
            byte[] protien,
            byte[] fat,
            byte[] carbohydrate,
            byte[] energy,
            byte[] starch,
            byte[] sugar,
            byte[] cholesterol) {
        ContentValues cv = new ContentValues();
        cv.put(COL_2,food);
        cv.put(COL_3,description);
        cv.put(COL_4,protien);
        cv.put(COL_5,fat);
        cv.put(COL_6,carbohydrate);
        cv.put(COL_7,energy);
        cv.put(COL_8,starch);
        cv.put(COL_9,sugar);
        cv.put(COL_10,cholesterol);
        SQLiteDatabase db = this.getWritableDatabase();
        db.insert(TABLE_NAME,null,cv);
    }

    public Cursor getFoodsWithProvidedFood(String provided_food) {
        return this.getWritableDatabase().query(
                TABLE_NAME,
                null,
                COL_2 + " LIKE '%" + provided_food + "%' ",
        null,
                null,
                null,
                null
        );
    }
}
  • 注释
  • 如果您只有一个用于定义表名和列名的位置,则可能会导致更少的问题。

    • 因此改变了onCreate
    • 尽管SQLite中的列名不区分大小写,但Cursor的getColumnIndex方法(在主要活动中使用)是区分大小写的(IMO是一个错误)。< / LI>
    • AUTOINCREMENT没有做它所暗示的内容,而INTEGER PRIMARY KEY本身会创建一个增加添加AUTOINCREMENT的列,这是一个特殊情况,可以确保id更大间接费用。因此AUTOINCREMENT已被移除。
  • 增加了两种方法

    • insertFood将数据插入(添加)到数据集表。
    • getFoodsWithProvidedFood,如上所述。

活动 - MainActivity.java

public class MainActivity extends AppCompatActivity {

    FoodDatabaseHelper foodDBHlpr;
    Cursor mCsr;

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

        foodDBHlpr = new FoodDatabaseHelper(this);
        byte[] dummy = new byte[]{0,1,2,3,4,5,6,7,8,9};

        // Add some data oif none exists
        if (DatabaseUtils.queryNumEntries(foodDBHlpr.getWritableDatabase(),FoodDatabaseHelper.TABLE_NAME) < 1) {
            foodDBHlpr.insertFood("Fish and Chips", "The English Seaside meal",
                    dummy, dummy, dummy, dummy, dummy, dummy, dummy);
            foodDBHlpr.insertFood("Bangers and Mash", "Yummy!!",
                    dummy, dummy, dummy, dummy, dummy, dummy, dummy);
            foodDBHlpr.insertFood("Mashed Potatoe", "Boring",
                    dummy, dummy, dummy, dummy, dummy, dummy, dummy);
        }

        // get a Cursor with the extracted foods
        mCsr = foodDBHlpr.getFoodsWithProvidedFood("Mash");
        // Loop Through the Cursor
        while (mCsr.moveToNext()) {
            Log.d("FOODFOUND","You found the food called - " + mCsr.getString(mCsr.getColumnIndex(FoodDatabaseHelper.COL_2)));
        }
        if (mCsr.getCount() < 1) {
            Log.d("FOODFOUND","No foods found that match the search criteria.");
        }
        mCsr.close(); //<<<< Should always close Cursors when done with them
    }
}

日志中的结果: -

03-15 21:48:21.170 1702-1702/foodsdb.so49307874_foodsdb D/FOODFOUND: You found the food called - Bangers and Mash
03-15 21:48:21.170 1702-1702/foodsdb.so49307874_foodsdb D/FOODFOUND: You found the food called - Mashed Potatoe