Android Studio通过微调框选择从SQLite数据库中选择项目

时间:2018-12-06 18:45:19

标签: java database sqlite android-studio spinner

我正在做一个项目,在我按下图像按钮后在浏览器中打开一个随机链接。我用不同的链接创建并填充了一个数据库表,并将它们分配给类别。我希望能够根据用户从微调框下拉菜单中选择的内容来过滤选择了哪些链接。现在,我只能从数据库中选择一个随机配方。

这是所有相关方法的主要活动(我省略了import语句和任何其他不必要的代码:

package com.example.randomrecipeapp;


public class MainActivity extends AppCompatActivity {

//fields
ImageButton randomizer;
Spinner spinner_filter;
DatabaseHelper db;


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

    db = new DatabaseHelper(getApplicationContext());
    //connect fields
    randomizer = (ImageButton) findViewById(R.id.logo);
    //spinner things
    spinner_filter = (Spinner) findViewById(R.id.spinner_filter);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.category_array, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    // Apply the adapter to the spinner
    spinner_filter.setAdapter(adapter);

    //initialize methods
    openRandomRecipe();

}

///////////////////////////////////////////////////////////////////
//spinner response
public void onItemSelected(AdapterView<?> parent, View view,
                           int pos, long id) {
    // An item was selected. You can retrieve the selected item using
    Object item = parent.getItemAtPosition(pos);
}

public void onNothingSelected(AdapterView<?> parent) {
    // Another interface callback
}

public void openRandomRecipe() {

    randomizer.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cursor res = db.getRandomData();

                    //if no data exists
                    if (res.getCount() == 0) {
                        // show message
                        showMessage("Error", "Nothing found");
                        return;
                    }

                    //add recipe link (columnIndex 1) to buffer sequence
                    StringBuffer buffer = new StringBuffer();
                    while (res.moveToNext()) {
                        buffer.append(res.getString(1));
                    }
                    //convert buffer to st
                    String sr = buffer.toString();
                    //open link in browser
                    startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(sr)));

                }
            }
    );
}
}

openRandomRecipe()方法在我的DatabaseHelper类中调用了另一个方法:

 //get one random recipe
public Cursor getRandomData() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM "+TABLE_RECIPES+" ORDER BY RANDOM() LIMIT 1",null);
    return res;

}

其中TABLE_RECIPES是表的名称。我想做的是创建一个新方法,如下所示:

public Cursor getRandomDataByCategory(String category) {
SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT "+category+ " FROM "+TABLE_RECIPES+" ORDER BY RANDOM() LIMIT 1",null);
    return res;

然后在MainActivity文件的onClickListener中执行

Cursor res = db.getRandomData(category);

我只是不确定如何弄清楚如何将用户选择的项从微调器中拉到getRandomData方法中。这甚至是解决此问题的正确方法吗?谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我相信他的查询将遵循:-

SELECT * FROM your_table WHERE your_category_column LIKE '%your_value%' ORDER BY random() LIMIT 1
  • 其中您的表代表表名
  • 您的值代表从微调器中选择的值
  • 以上内容假设为“喜欢”,因此,如果您有Dinner和AfterDinner类别,则从微调器中选择Dinner即可从两者中进行选择(对于特定的匹配,很容易更改为=)。

说我建议您可以使用一个getRandaomData方法,例如, :-

public Cursor getRandomData(String category) {
    SQLiteDatabase db = this.getWritableDatabase();
    String whereclause = null;
    String[] whereargs = null;
    if (category.length() > 0 ) {
        whereclause = COLUMN_RECIPES_CATEGORY + " LIKE ?";
        whereargs = new String[]{"%" + category + "%"};
    }
    return db.query(TABLE_RECIPES,null,whereclause,whereargs,null,null,"random()","1");
    //Cursor res = db.rawQuery("SELECT * FROM "+TABLE_RECIPES+" ORDER BY RANDOM() LIMIT 1",null);
}
  • 这假定类别从不为null(请参见工作示例),也不得为null。

工作示例

以下是基于您提供的代码的有效示例(省略(注释掉)代码对于演示例如调用下一个活动不是必需的。)

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {

    SQLiteDatabase mDB;

    public static final String DBNAME = "recipee";
    public static final int DBVERSION = 1;
    public static final String TABLE_RECIPES = "recipes";
    public static final String COLUMN_RECIPES_ID = BaseColumns._ID;
    public static final String COLUMN_RECIPES_NAME = "name";
    public static final String COLUMN_RECIPES_CATEGORY = "category";

    public DatabaseHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        mDB = db;
        String crt_recipes_sql = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + "(" +
                COLUMN_RECIPES_ID + "INTEGER PRIMARY KEY," +
                COLUMN_RECIPES_NAME + " TEXT," +
                COLUMN_RECIPES_CATEGORY + " TEXT" +
                ")";
        db.execSQL(crt_recipes_sql);
        addRecipee("Egg on Toast","Breakfast");
        addRecipee("Bangers and Mash", "Dinner");
        addRecipee("Cheese Sandwich","Snack");
        addRecipee("Mud Cake","Desert");
        addRecipee("Spaghetti Bolognaise","Dinner");
        addRecipee("Blueberry Cheesecake","Desert");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    public long addRecipee(String name, String category) {
        if (mDB == null) {
            mDB = this.getWritableDatabase();
        }
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_RECIPES_NAME,name);
        cv.put(COLUMN_RECIPES_CATEGORY,category);
        return mDB.insert(TABLE_RECIPES,null,cv);
    }

    public Cursor getRandomData(String category) {
        SQLiteDatabase db = this.getWritableDatabase();
        String whereclause = null;
        String[] whereargs = null;
        if (category.length() > 0 ) {
            whereclause = COLUMN_RECIPES_CATEGORY + " LIKE ?";
            whereargs = new String[]{"%" + category + "%"};
        }
        return db.query(TABLE_RECIPES,null,whereclause,whereargs,null,null,"random()","1");
        //Cursor res = db.rawQuery("SELECT * FROM "+TABLE_RECIPES+" ORDER BY RANDOM() LIMIT 1",null);
    }
}
  • 请注意,这会添加一些配方(创建数据库时带有类别)

Strings.xml

即只是Spinner项目:-

<array name="category_array">
    <item>A</item>
    <item>B</item>
    <item>C</item>
    <item>Dinner</item>
    <item>Breakfast</item>
    <item>Desert</item>
    <item>Snack</item>
</array>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    //fields
    ImageButton randomizer;
    Spinner spinner_filter;
    TextView random_recipee;
    DatabaseHelper db;
    String current_category;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        random_recipee = this.findViewById(R.id.recipee);
        current_category = "";

        db = new DatabaseHelper(getApplicationContext());
        //connect fields
        randomizer = (ImageButton) findViewById(R.id.logo);
        //spinner things
        spinner_filter = (Spinner) findViewById(R.id.spinner_filter);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.category_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner_filter.setAdapter(adapter);
        spinner_filter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                Object item = parent.getItemAtPosition(pos);
                current_category = item.toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        //initialize methods
        openRandomRecipe();
    }

    public void openRandomRecipe() {
        randomizer.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Cursor res = db.getRandomData(current_category);
                        random_recipee.setText("Nothing Found");
                        if (res.moveToFirst()) {
                            random_recipee.setText(
                                    "Recipee is " +res.getString(
                                            res.getColumnIndex(DatabaseHelper.COLUMN_RECIPES_NAME)
                                    ) +
                                            ". Category is " +
                                            res.getString(
                                                    res.getColumnIndex(DatabaseHelper.COLUMN_RECIPES_CATEGORY)
                                            )
                            );
                        }
                        res.close(); //<<<<<<<<<< should always close cursor when done with it.
                        return;
                        //add recipe link (columnIndex 1) to buffer sequence
                        //StringBuffer buffer = new StringBuffer();
                        /*
                        while (res.moveToNext()) {
                            buffer.append(res.getString(1));
                        }
                        */
                        //convert buffer to st
                        //String sr = buffer.toString();
                        //open link in browser
                        //startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(sr)));

                    }
                }
        );
    }
}
  • 请注意,已添加一个TextView,它将显示所选食谱及其类别。
  • ImageButton没有使用图像

结果

enter image description here

  • Note Spinner单击以显示项目

在单击“晚餐”作为所选项目的按钮之后:-

enter image description here

  • 请注意,只有2个食谱,以晚餐为类别,单击按钮通常会显示相同的食谱。