[英]Retrieving Data from SQLite Database through AsyncTask and Displaying it
因此,在過去的幾周中,我一直在使用該程序,該程序使用SQLite數據庫存儲由AsyncTask運行並存儲的用戶添加的配方。 可以添加和刪除配方,但是現在我必須使用AsyncTask來顯示在某些類別中輸入的配方。 因此,例如,如果用戶添加了“面包”食譜,那么當用戶單擊“面包”按鈕時,會在主屏幕上顯示該食譜。 這是我到目前為止的內容:
MyDBHandler.java:
package com.example.healthylife;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "recipeDB.db";
private static final String TABLE_RECIPE = "recipe";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_RECIPENAME = "_recipename";
private static final String COLUMN_CATEGORY = "_category";
private static final String COLUMN_INGREDIENTS = "_ingredients";
private static final String COLUMN_INSTRUCTIONS = "_instructions";
public MyDBHandler(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version){
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db){
String CREATE_RECIPE_TABLE = "CREATE TABLE " + TABLE_RECIPE + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_RECIPENAME + " TEXT," +
COLUMN_CATEGORY + " TEXT," + COLUMN_INGREDIENTS + " TEXT," +
COLUMN_INSTRUCTIONS + " TEXT" + ")";
db.execSQL(CREATE_RECIPE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECIPE);
onCreate(db);
}
public void addRecipe(Recipe recipe){
ContentValues values = new ContentValues();
values.put(COLUMN_RECIPENAME, recipe.getRecipeName());
values.put(COLUMN_CATEGORY, recipe.getCategory());
values.put(COLUMN_INGREDIENTS, recipe.getIngredients());
values.put(COLUMN_INSTRUCTIONS, recipe.getInstructions());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_RECIPE, null, values);
db.close();
}
public Recipe findRecipe(String recipename){
String query = "Select * FROM " + TABLE_RECIPE + "WHERE " + COLUMN_RECIPENAME + " = \"" +
recipename + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Recipe recipe = new Recipe();
if (cursor.moveToFirst()){
cursor.moveToFirst();
recipe.setID(Integer.parseInt(cursor.getString(0)));
recipe.setRecipeName(cursor.getString(1));
recipe.setCategory(cursor.getString(2));
recipe.setIngredients(cursor.getString(3));
recipe.setInstructions(cursor.getString(4));
cursor.close();
}else{
recipe = null;
}
db.close();
return recipe;
}
public boolean deleteRecipe(String recipename) {
boolean result = false;
String query = "Select * FROM " + TABLE_RECIPE + " WHERE " + COLUMN_RECIPENAME + " = \"" +
recipename + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Recipe recipe = new Recipe();
if (cursor.moveToFirst()) {
recipe.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_RECIPE, COLUMN_ID + " = ?",
new String[] { String.valueOf(recipe.getID()) });
cursor.close();
result = true;
}
db.close();
return result;
}
public Recipe getBread(String recipename) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "Select * FROM " + TABLE_RECIPE + "WHERE " + COLUMN_RECIPENAME + " = \"" +
recipename + "\"";
Cursor cursor = db.rawQuery(query, null);
Recipe recipe = new Recipe();
if (cursor != null) {
cursor.moveToFirst();
recipe.setID(Integer.parseInt(cursor.getString(0)));
recipe.setRecipeName(cursor.getString(1));
recipe.setCategory(cursor.getString(2));
recipe.setIngredients(cursor.getString(3));
recipe.setInstructions(cursor.getString(4));
cursor.close();
}else{
recipe = null;
}
db.close();
return recipe;
}
public Recipe getFruit(String recipename) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * FROM " + TABLE_RECIPE + "WHERE " + COLUMN_RECIPENAME + " = \"" +
recipename + "\"";
Cursor cursor = db.rawQuery(query, null);
Recipe recipe = new Recipe();
if (cursor != null) {
cursor.moveToFirst();
recipe.setID(Integer.parseInt(cursor.getString(0)));
recipe.setRecipeName(cursor.getString(1));
recipe.setCategory(cursor.getString(2));
recipe.setIngredients(cursor.getString(3));
recipe.setInstructions(cursor.getString(4));
cursor.close();
}else{
recipe = null;
}
db.close();
return recipe;
}
public Recipe getVeg(String recipename) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * FROM " + TABLE_RECIPE + "WHERE " + COLUMN_RECIPENAME + " = \"" +
recipename + "\"";
Cursor cursor = db.rawQuery(query, null);
Recipe recipe = new Recipe();
if (cursor != null) {
cursor.moveToFirst();
recipe.setID(Integer.parseInt(cursor.getString(0)));
recipe.setRecipeName(cursor.getString(1));
recipe.setCategory(cursor.getString(2));
recipe.setIngredients(cursor.getString(3));
recipe.setInstructions(cursor.getString(4));
cursor.close();
}else{
recipe = null;
}
db.close();
return recipe;
}
public Recipe getSoup(String recipename) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "Select * FROM " + TABLE_RECIPE + "WHERE " + COLUMN_RECIPENAME + " = \"" +
recipename + "\"";
Cursor cursor = db.rawQuery(query, null);
Recipe recipe = new Recipe();
if (cursor != null) {
cursor.moveToFirst();
recipe.setID(Integer.parseInt(cursor.getString(0)));
recipe.setRecipeName(cursor.getString(1));
recipe.setCategory(cursor.getString(2));
recipe.setIngredients(cursor.getString(3));
recipe.setInstructions(cursor.getString(4));
cursor.close();
}else{
recipe = null;
}
db.close();
return recipe;
}
[Recipe.java具有獲取器/設置器]
DatabaseActivity類使用AsyncTask中的添加和刪除功能:
package com.example.healthylife;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class DatabaseActivity extends AppCompatActivity {
TextView idView;
EditText RecipeBox;
EditText CategoryBox;
EditText IngredientsBox;
EditText InstructionsBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
idView = (TextView) findViewById(R.id.Recipe_ID);
RecipeBox = (EditText) findViewById(R.id.edit_RecipeName);
CategoryBox = (EditText) findViewById(R.id.input_category);
IngredientsBox = (EditText) findViewById(R.id.edit_Ingredients);
InstructionsBox = (EditText) findViewById(R.id.edit_Instructions);
}
public void newRecipe (View view){
AsyncTaskSave op = new AsyncTaskSave();
op.execute();
}
public void lookupRecipe (View view){
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
Recipe recipe = dbHandler.findRecipe(RecipeBox.getText().toString());
if (recipe != null){
idView.setText(String.valueOf(recipe.getID()));
CategoryBox.setText(String.valueOf(recipe.getCategory()));
IngredientsBox.setText(String.valueOf(recipe.getIngredients()));
InstructionsBox.setText(String.valueOf(recipe.getInstructions()));
}else {
idView.setText("No Match Found");
}
}
public void removeRecipe (View view){
AsyncTaskDelete task = new AsyncTaskDelete();
task.execute();
}
private class AsyncTaskSave extends AsyncTask <Object, Object, String> {
@Override
protected String doInBackground(Object...objects){
MyDBHandler dbHandler = new MyDBHandler (DatabaseActivity.this, null, null, 1);
Recipe recipe = new Recipe();
dbHandler.addRecipe(recipe);
return null;
}
@Override
protected void onPostExecute(String result) {
Recipe recipe = new Recipe();
RecipeBox.setText(String.valueOf(recipe.getRecipeName()));
CategoryBox.setText(String.valueOf(recipe.getCategory()));
IngredientsBox.setText(String.valueOf(recipe.getIngredients()));
InstructionsBox.setText(String.valueOf(recipe.getInstructions()));
result = "Added Successfully";
idView.setText(result);
}
}
private class AsyncTaskDelete extends AsyncTask<Object, String, String>{
@Override
protected String doInBackground(Object...objects){
MyDBHandler dbHandler = new MyDBHandler (DatabaseActivity.this, null, null, 1);
dbHandler.deleteRecipe(null);
return null;
}
@Override
protected void onPostExecute(String result){
if (result == null){
idView.setText("Record Deleted");
RecipeBox.setText("");
CategoryBox.setText("");
IngredientsBox.setText("");
InstructionsBox.setText("");
}else
idView.setText("No Match Found");
}
}
}
SyncActivity.java類應該顯示由DatabaseActivity類添加的配方,並在按下主屏幕按鈕時在屏幕上調用它們:
package com.example.healthylife;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class SyncActivity extends AppCompatActivity{
TextView idView;
TextView RecipeBox;
TextView CategoryBox;
TextView IngredientsBox;
TextView InstructionsBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync);
idView = (TextView) findViewById(R.id.Recipe_ID);
RecipeBox = (TextView) findViewById(R.id.edit_RecipeName);
CategoryBox = (TextView) findViewById(R.id.input_category);
IngredientsBox = (TextView) findViewById(R.id.edit_Ingredients);
InstructionsBox = (TextView) findViewById(R.id.edit_Instructions);
}
public void getBread (View view) {
AsyncTaskBread os = new AsyncTaskBread();
os.execute();
}
public void getFruit (View view){
AsyncTaskFruit ob = new AsyncTaskFruit();
ob.execute();
}
public void getVeg (View view){
AsyncTaskVeg ow = new AsyncTaskVeg();
ow.execute();
}
public void getSoup (View view){
AsyncTaskSoup ox = new AsyncTaskSoup();
ox.execute();
}
private class AsyncTaskBread extends AsyncTask <Object, Object, String>{
MyDBHandler dbHandler;
@Override
protected String doInBackground(Object...objects){
MyDBHandler dbHandler = new MyDBHandler (SyncActivity.this, null, null, 1);
dbHandler.getBread("Bread");
return "Bread";
}
@Override
protected void onPostExecute(String result){
Recipe recipe = dbHandler.getBread(CategoryBox.getText().toString());
if(recipe != null){
idView.setText(String.valueOf(recipe.getID()));
RecipeBox.setText(String.valueOf(recipe.getRecipeName()));
IngredientsBox.setText(String.valueOf(recipe.getIngredients()));
InstructionsBox.setText(String.valueOf(recipe.getInstructions()));
}else {
result = "No Match Found";
idView.setText(result);
}
}
}
private class AsyncTaskFruit extends AsyncTask <Object, Object, String>{
MyDBHandler dbHandler;
@Override
protected String doInBackground(Object...objects){
MyDBHandler dbHandler = new MyDBHandler (SyncActivity.this, null, null, 1);
dbHandler.getFruit("Fruit");
return "Fruit";
}
@Override
protected void onPostExecute(String result){
Recipe recipe = dbHandler.getFruit(CategoryBox.getText().toString());
if(recipe != null){
idView.setText(String.valueOf(recipe.getID()));
RecipeBox.setText(String.valueOf(recipe.getRecipeName()));
IngredientsBox.setText(String.valueOf(recipe.getIngredients()));
InstructionsBox.setText(String.valueOf(recipe.getInstructions()));
}else {
result = "No Match Found";
idView.setText(result);
}
}
}
private class AsyncTaskVeg extends AsyncTask <Object, Object, String>{
MyDBHandler dbHandler;
@Override
protected String doInBackground(Object...objects){
MyDBHandler dbHandler = new MyDBHandler (SyncActivity.this, null, null, 1);
dbHandler.getVeg("Vegetables");
return "Vegetables";
}
@Override
protected void onPostExecute(String result){
Recipe recipe = dbHandler.getVeg(CategoryBox.getText().toString());
if(recipe != null){
idView.setText(String.valueOf(recipe.getID()));
RecipeBox.setText(String.valueOf(recipe.getRecipeName()));
IngredientsBox.setText(String.valueOf(recipe.getIngredients()));
InstructionsBox.setText(String.valueOf(recipe.getInstructions()));
}else {
result = "No Match Found";
idView.setText(result);
}
}
}
private class AsyncTaskSoup extends AsyncTask <Object, Object, String>{
MyDBHandler dbHandler;
@Override
protected String doInBackground(Object...objects){
MyDBHandler dbHandler = new MyDBHandler (SyncActivity.this, null, null, 1);
dbHandler.getSoup("Soup");
return "Soup";
}
@Override
protected void onPostExecute(String result){
Recipe recipe = dbHandler.getSoup(CategoryBox.getText().toString());
if(recipe != null){
idView.setText(String.valueOf(recipe.getID()));
RecipeBox.setText(String.valueOf(recipe.getRecipeName()));
IngredientsBox.setText(String.valueOf(recipe.getIngredients()));
InstructionsBox.setText(String.valueOf(recipe.getInstructions()));
}else {
result = "No Match Found";
idView.setText(result);
}
}
}
}
現在是主屏幕:
在將食譜添加到食譜書中后,單擊每個按鈕時,它們應在某些字段中顯示詳細信息,但我的字段為空:
現在,SyncActivity類應該從數據庫中檢索通過DatabaseActivity類輸入的值,但不是。 我需要更改myDBHandler中的代碼嗎? 還是在SyncActivity中?
問題是,實例AsyncTaskBread中的私有對象dbHandler永遠不會初始化。 您可以在doInBackground中初始化dbHandler,但是該對象僅存在於該函數中。 嘗試更改行MyDBHandler dbHandler = new MyDBHandler (SyncActivity.this, null, null, 1);
到dbHandler = new MyDBHandler (SyncActivity.this, null, null, 1);
我還建議您將sql查詢從onPostExecute移至doInBackground,因為onPostExecute在UI(主)線程上運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.