android studio通过微调器选择从sqlite数据库中选择项

mdfafbf1  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(352)

我正在做一个项目,在按下imagebutton后,我在浏览器中打开一个随机链接。我已经创建并填充了一个带有不同链接的数据库表,并将它们分配给了类别。我想能够过滤哪些链接是根据用户的选择从微调下拉选择。现在,我只能从数据库中随机选择一个食谱。
这是所有相关方法的主要活动(我省略了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\u 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方法。这是解决这个问题的正确方法吗?谢谢你的帮助。

dxxyhpgq

dxxyhpgq1#

我相信他会按照以下思路提出问题:-

SELECT * FROM your_table WHERE your_category_column LIKE '%your_value%' ORDER BY random() LIMIT 1

其中,\u表表示表名
_值表示从微调器中选择的值
上面的假设是这样的,如果您有晚餐和晚餐后的类别,那么从微调器中选择晚餐将从两者中进行选择(对于特定的匹配,很容易更改为“=”。
我建议您可以使用一个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);
}

这假设category从不为null(参见工作示例),也类似于。

工作示例

下面是一个基于您提供的代码的工作示例(省略(注解掉)不需要演示的代码,例如调用下一个活动)。

数据库助手.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);
    }
}

注意这会添加一些配方(在创建数据库时使用类别)

字符串.xml

i、 e.仅微调器项目:-

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

主活动.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)));

                    }
                }
        );
    }
}

注意:添加了一个文本视图,它将显示所选配方及其类别。
没有图像用于imagebutton

结果


注意微调器单击以显示项目
单击“晚餐”作为所选项目的按钮后:-

注意,只有2个食谱与晚餐作为类别点击按钮,往往会显示相同的食谱。

相关问题