[英]Android Studio Select item from SQLite database by spinner selection
我正在一個項目中,在我按下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_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方法中。 這甚至是解決此問題的正確方法嗎? 謝謝您的幫助。
我相信他的查詢將遵循:-
SELECT * FROM your_table WHERE your_category_column LIKE '%your_value%' ORDER BY random() LIMIT 1
說我建議您可以有一個單獨的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);
}
以下是基於您提供的代碼的工作示例(省略(注釋掉)代碼對於演示,例如,調用下一個活動不是必需的)。
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);
}
}
即只是微調項目:-
<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>
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)));
}
}
);
}
}
單擊“晚餐”作為所選項目的按鈕后:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.