我需要使用AsyncTask在我的应用程序中执行数据库更新(主要是添加和删除)。我不知道在我的程序中为该函数编码究竟是什么。它将进入我的第二个活动文件。
DatabaseActivity.java
package com.example.healthylife;
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){
MyDBHandler dbHandler = new MyDBHandler (this, null, null, 1);
Recipe recipe = new Recipe();
dbHandler.addRecipe(recipe);
RecipeBox.setText("");
CategoryBox.setText("");
IngredientsBox.setText("");
InstructionsBox.setText("");
}
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){
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
boolean result = dbHandler.deleteRecipe(RecipeBox.getText().toString());
if (result){
idView.setText("Record Deleted");
RecipeBox.setText("");
CategoryBox.setText("");
IngredientsBox.setText("");
InstructionsBox.setText("");
}else
idView.setText("No Match Found");
}
}
任何帮助将不胜感激。感谢。
答案 0 :(得分:0)
你的问题很广泛。我想,你不需要额外的Activity来执行该操作。
使用构造函数在同一活动中创建异步任务,该构造函数使用数据库连接处理程序,要更新的数据以及指示其更新或删除操作的标志。您的活动中将有一些回调功能(例如,当用户按下"保存"或"删除")时。在此触发器上,使用相应的值启动异步任务。
在asynctask类中,分别执行上面编码的操作。
您可以为每个操作编写单独的异步任务!这取决于你的设计!
private class AsyncTaskSaveDelete extends AsyncTask<Void, Void, boolean> {
private DBHandler handler;
private Recipe recipe;
private boolean isDelete;
public AsyncTaskSaveDelete(DBHandler handler,Recipe recipe,boolean isDelete ){
this.handler = handler;
this.recipe = recipe;
this.isDelete = isDelete;
}
protected Long doInBackground( {
if(isDelete){
return dbHandler.deleteRecipe(recipe);
}else{
return dbHandler.addRecipe(recipe);
}
}
protected void onPostExecute(boolean result) {
runOnUiThread(new PostRunnable(){
//update the UI
})
}
}
public void newRecipe (View view){
...
new AsyncTaskSaveDelete(handler,recipe,false).execute();
...
}