我正在学习Android工作室,本周开始使用数据库。我想对这个应用程序有点帮助。很简单。用户输入字符串并按下第一个活动中的按钮。然后将此字符串发送到第二个活动,并将其与数据库中的值进行比较,并显示相似的值:
public class DrinkCategoryActivity extends ListActivity {
public static final String EXTRA_MESSAGE = "message";
private SQLiteDatabase db;
private Cursor cursor;
private Cursor newcursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String messageText = intent.getStringExtra(EXTRA_MESSAGE);
//setContentView(R.layout.activity_drink_category);
ListView listDrinks = getListView();
try{
SQLiteOpenHelper starbucksDatabaseHelper = new StarbucksDatabaseHelper(this);
db = starbucksDatabaseHelper.getReadableDatabase();
/*
SELECT _id, NAME FROM DRINKS;
*/
cursor = db.query("DRINK",
new String[]{"_id", "NAME"},
null, null, null, null, null);
newcursor = cursor.equals(messageText);
CursorAdapter listAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
cursor,
new String[]{"NAME"},
new int[]{android.R.id.text1},
0);
listDrinks.setAdapter(listAdapter);
}catch (SQLiteException ex){
Toast toast = Toast.makeText(this, "Database unavailable",
Toast.LENGTH_LONG);
toast.show();
}
我一直在寻找网络,但我找不到一个好的解释。 数据库
这是数据库中的饮料
public class StarbucksDatabaseHelper extends SQLiteOpenHelper{
add a varaible for the db name
private static final String DB_NAME = "starbucks";
version of the database
private static final int DB_VERSION = 1;
StarbucksDatabaseHelper (Context context){
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE DRINK ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insert data
insertDrink(db, "Soy Latte", "Esspresso and steamed soy milk", R.drawable.latte);
insertDrink(db, "Mocaccino", "Esspresso, hot milk, steamed milk foam, and cocoa", R.drawable.cappuccino);
insertDrink(db, "American", "Drip coffee", R.drawable.filter);
}
private static void insertDrink (SQLiteDatabase db,
String name,
String description,
int resourceId){
ContentValues drinkValues = new ContentValues();
drinkValues.put("NAME", name );
drinkValues.put("DESCRIPTION", description);
drinkValues.put("IMAGE_RESOURCE_ID", resourceId);
db.insert("DRINK", null, drinkValues);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
答案 0 :(得分:1)
如果您希望检索在开头,中间或结尾包含messageText
的任何行,请尝试此查询 -
cursor = db.query("DRINK", new String[]{"_id", "NAME"}, "NAME like %?%", new String[]{messageText}, null, null, null);