简体   繁体   English

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

[英]Android Studio Select item from SQLite database by spinner selection

I am working on a project where I open up a random link in the browser after an imagebutton is pressed. 我正在一个项目中,在我按下imagebutton后在浏览器中打开一个随机链接。 I have created and populated a database table with different links and assigned them to categories. 我用不同的链接创建并填充了一个数据库表,并将它们分配给类别。 I would like to be able to filter which links are selected based upon a users' selection from a spinner dropdown. 我希望能够根据用户从微调框下拉菜单中选择的内容来过滤选择了哪些链接。 Right now, I am only able to select a random recipe from the database. 现在,我只能从数据库中选择一个随机配方。

This is the main activity with all the relevant methods (I have left out the import statements and any other unnecessary code : 这是所有相关方法的主要活动(我省略了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)));

                }
            }
    );
}
}

The openRandomRecipe() method calls this other method in my DatabaseHelper class: 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;

}

Where TABLE_RECIPES is the name of the table. 其中TABLE_RECIPES是表的名称。 What I'm thinking I need to do is create a new method such as this: 我想做的是创建一个像这样的新方法:

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;

And then in the onClickListener in the MainActivity file do 然后在MainActivity文件的onClickListener中执行

Cursor res = db.getRandomData(category);

I'm just not sure how to figure out how to pull in the user selected item from the spinner into the getRandomData method. 我只是不确定如何弄清楚如何将用户选择的项从微调器中拉到getRandomData方法中。 Is this even a correct way of solving this problem? 这甚至是解决此问题的正确方法吗? Thanks for the help. 谢谢您的帮助。

I believe he query would be along the lines of :- 我相信他的查询将遵循:-

SELECT * FROM your_table WHERE your_category_column LIKE '%your_value%' ORDER BY random() LIMIT 1
  • where your_table represents the table name 其中your_table代表表名
  • your_value represents the value select from the spinner your_value表示从微调器中选择的值
  • The above assumes LIKE so if you had categories of Dinner and AfterDinner then selecting Dinner from the spinner would select from both (easy to change to = for a specific match). 上面的示例假定为“ LIKE”,因此,如果您有Dinner和AfterDinner类别,则从微调器中选择Dinner会从两者中进行选择(对于特定的匹配,很容易更改为=)。

Saying that I'd suggest that you could have a single getRandaomData method would suit both eg :- 说我建议您可以有一个单独的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);
}
  • This assumes that the category is never null (see working example), and also LIKE. 这假定类别从不为空(请参见工作示例),也不得为LIKE。

WORKING EXAMPLE 工作实例

The following is a working example based upon the code you have supplied (omitting (commenting out) code not necessary to demonstrate eg calling the next activity). 以下是基于您提供的代码的工作示例(省略(注释掉)代码对于演示,例如,调用下一个活动不是必需的)。

DatabaseHelper.java 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);
    }
}
  • Note this adds a few recipes (with categories when the database is created) 请注意,这会添加一些配方(创建数据库时带有类别)

Strings.xml strings.xml中

ie just the Spinner items :- 即只是微调项目:-

<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 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)));

                    }
                }
        );
    }
}
  • Note a TextView has been added that will show the selected recipe along with it's category. 请注意,已添加一个TextView,它将显示所选配方及其类别。
  • No image was used for the ImageButton 没有图像用于ImageButton

Result 结果

在此处输入图片说明

  • Note Spinner clicked to show items 注意微调器单击以显示项目

After clicking on the button with Dinner as the selected item :- 单击“晚餐”作为所选项目的按钮后:

在此处输入图片说明

  • Note as only 2 recipes with Dinner as the category clicking the button will often show the same recipe. 请注意,只有2个食谱以“晚餐”为类别,单击按钮通常会显示相同的食谱。

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

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