gpt4 book ai didi

java - 如何在我的代码中实现ASyncTask来进行数据库操作

转载 作者:行者123 更新时间:2023-12-01 16:56:19 24 4
gpt4 key购买 nike

我有一个 Android Studio 程序(Java 语言),它从用户收集数据,然后允许他们 a) 通过按“添加”按钮将该数据输入到表中,或者 b) 从表中删除该信息(如果它已经在那里了)通过按删除按钮。这并不令人惊奇,但它是实践并且有效的。问题是我想让这些操作发生在后台线程而不是 UI 线程中。

我似乎不知道到底该怎么做。我发现的所有建议的解决方案要么不适用于我的情况,要么我尝试实现它们但失败了(或者它们不起作用;我无法区分我当前的技能水平)。帮助将不胜感激。相关文件如下。 (请注意,我从此处的代码中删除了包名称,因为它们中有我的真实姓名,但它们位于实际文件中)。

DataEntryForm.java(这是我的“添加”和“删除”按钮及其 onClick 方法所在的位置)

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class DataEntryForm extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_entry_form);
final Spinner spinner = findViewById(R.id.categorySelect);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.categories_Array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final DBAdapter db = new DBAdapter(this);
db.open();
final EditText recipeNameInput = findViewById(R.id.recipeNameInput);
final Spinner categorySelect = findViewById(R.id.categorySelect);
final EditText ingredientsInput = findViewById(R.id.ingredientsInput);
final EditText instructionsInput = findViewById(R.id.instructionsInput);
Button addBtn = findViewById(R.id.addBtn);
Button deleteBtn = findViewById(R.id.deleteBtn);
addBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
new BackgroundThread().execute();
String editRecipeName = recipeNameInput.getText().toString();
String chooseCategory = categorySelect.getSelectedItem().toString();
String editIngredients = ingredientsInput.getText().toString();
String editInstructions = instructionsInput.getText().toString();
db.insertRecipeChoice(editRecipeName, chooseCategory, editIngredients, editInstructions);
Toast.makeText(DataEntryForm.this, "Recipe added!", Toast.LENGTH_LONG).show();

}
});

deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new BackgroundThread().execute();
if (db.deleteChoice(1))
Toast.makeText(DataEntryForm.this, "Recipe deleted!", Toast.LENGTH_LONG).show();
else
Toast.makeText(DataEntryForm.this, "Recipe deletion failed!",
Toast.LENGTH_LONG).show();
}
}
);


}

}

请注意,其中有一个“new BackgroundThread.execute()”行,来 self 之前的一次尝试,以使其工作。我暂时把它保留下来,以防万一事实证明这是正确的想法。我不想让它溜走。

DBAdapter.java

    import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class DBAdapter extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adapter_db);
}
static final String KEY_ROWID = "_id";
static final String KEY_RECIPENAME = "RecipeName";
static final String KEY_CATEGORY = "Category";
static final String KEY_INGREDIENTS = "Ingredients";
static final String KEY_INSTRUCTIONS = "Instructions";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB";
static final String DATABASE_TABLE = "MyChoices";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table MyChoices (_id integer primary key autoincrement, " + "RecipeName text not null, category text not null, ingredients text not null, instructions text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS MyChoices");
onCreate(db);
}
}
//---opens the database----
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database----
public void close() {
DBHelper.close();
}
//---insert a recipe choice into the database---
public long insertRecipeChoice(String recipeName, String category, String ingredients, String instructions) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_RECIPENAME, recipeName);
initialValues.put(KEY_CATEGORY, category);
initialValues.put(KEY_INGREDIENTS, ingredients);
initialValues.put(KEY_INSTRUCTIONS, instructions);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular recipe choice---
public boolean deleteChoice(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
}

BackgroundThread.java 这大部分是空的,因为我只是迷失在试图弄清楚我是否需​​要这个单独的类,如果需要,我应该放在这里。

 import android.content.Context;
import android.os.AsyncTask;

public class BackgroundThread extends AsyncTask<Void, Void, Void> {

@Override
protected Void doInBackground(Void... voids) {
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}

}

如果我需要包含其他任何内容才能获得此问题的答案,请告诉我,但我认为这些是相关文件。其他一切都不会触及或影响表或数据。

最佳答案

这就是异步任务的工作原理

假设您想在单击按钮时将名称、用户名和密码从 editTexts 发送到 php 脚本

主要 Activity

    import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class DataEntryForm extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_entry_form);
final Spinner spinner = findViewById(R.id.categorySelect);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.categories_Array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final DBAdapter db = new DBAdapter(this);
db.open();
final EditText recipeNameInput = findViewById(R.id.recipeNameInput);
final Spinner categorySelect = findViewById(R.id.categorySelect);
final EditText ingredientsInput = findViewById(R.id.ingredientsInput);
final EditText instructionsInput = findViewById(R.id.instructionsInput);
Button addBtn = findViewById(R.id.addBtn);
Button deleteBtn = findViewById(R.id.deleteBtn);
addBtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {

String editRecipeName = recipeNameInput.getText().toString();
String chooseCategory = categorySelect.getSelectedItem().toString();
String editIngredients = ingredientsInput.getText().toString();
String editInstructions = instructionsInput.getText().toString();
// declare an array of string
String[] edittextdata = new String[4];
edittextdata[0] = editRecipeName;
edittextdata[1] = chooseCategory;
edittextdata[2] = editIngredients;
edittextdata[3] = editInstructions;
new BackgroundThread().execute(edittextdata);
db.insertRecipeChoice(editRecipeName, chooseCategory, editIngredients, editInstructions);
Toast.makeText(DataEntryForm.this, "Recipe added!", Toast.LENGTH_LONG).show();

}
});

deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new BackgroundThread().execute();
if (db.deleteChoice(1))
Toast.makeText(DataEntryForm.this, "Recipe deleted!", Toast.LENGTH_LONG).show();
else
Toast.makeText(DataEntryForm.this, "Recipe deletion failed!",
Toast.LENGTH_LONG).show();
}
}
);


}
//to send data or add data to your databse be it sqlite or mysql sql script via Async task
public class BackgroundThread extends AsyncTask<String, Void, Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected Void doInBackground(String... strings) {
//inside on do in background get the data passed from above contained inside editxt data
String recipeName = strings[0];
/*.
.
.
. get all the arguments
*/
//Here you can do anything with the strings be it calculations and return results on post execute
//or network operations
return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}

查看此链接..它将帮助您了解异步任务操作 check this one out

我向您展示的只是将您想要处理的数据从主线程发送到扩展异步任务的类。因此,您需要做的是在 doinbackground 方法中处理数据,如果您将其存储在数据库中,请执行该操作并监听事件,例如,如果成功或失败,则将 boolean 字符串 i 或整数中的事件传递给 onpostexecute更新主线程。例如,如果我将数据发送到数据库,我将首先从主线程中的编辑文本获取值,然后将这些值从主线程传递到异步任务,然后在异步任务中,执行与数据库的连接,存储数据,监听对于成功或失败事件,并从数据库获取 boolean 值、JSOn 或字符串的响应,然后将其传递给 postExecute 以更新 UI。清除一切的希望。还有一件事,请确保您了解如何将值从主任务传递到异步任务。例如对象、数组列表字符串等...因为一旦你理解了异步任务就更容易

关于java - 如何在我的代码中实现ASyncTask来进行数据库操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61583539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com