【问题标题】:How to implement ASyncTask in my code for database operations如何在我的代码中实现 ASyncTask 以进行数据库操作
【发布时间】:2020-08-18 08:47:37
【问题描述】:

我有一个 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()”行。我暂时把它留了下来,以防万一事实证明这是正确的想法。我不想让它溜走。

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 这大部分是空的,因为我只是想弄清楚我是否需​​要这个单独的类,如果需要,我应该在这里放什么。 p>

 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);
 }

}

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

【问题讨论】:

    标签: java android database android-asynctask onclick


    【解决方案1】:

    这就是异步任务的工作方式

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

    在主要活动中

        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 方法中处理数据,如果您将其存储在数据库中,则在那里执行并侦听事件,例如,如果成功或失败,则将布尔字符串 i 或整数中的事件传递给 onpostexecute 到更新主线程。例如,如果我正在向数据库发送数据,我将首先从主线程中的编辑文本中获取值,然后将这些值从主线程传递到异步任务,然后在异步任务中,执行与数据库的连接,存储数据,收听对于成功或失败事件并从 DB 获取布尔或 JSOn 或字符串的响应,然后将其传递给 postExecute 以更新 UI。箍,清除一切。还有一件事,请确保您了解如何将值从主任务传递到异步任务。例如 OBJECTS、ARRAYLIST STRINGs 等等。因为一旦你理解了异步任务,它就更容易了

    【讨论】:

    • 我想我明白你在说什么,但我不确定,因为从你上面发布的内容看来,数据库操作仍然是直接从我的按钮单击方法执行的(正在在 UI 线程中执行)。我应该让数据库操作代码在我的 doInBackgroundMethod 中,然后让我的 buttonClick 方法调用它吗?如果是这样,我该如何让它根据单击的按钮执行两种不同的操作?最后,我是否需要将 DataEntryForm 类和 BackgroundThread 类放在同一个 Java 文件中才能使类似的东西工作?
    • 我似乎无法弄清楚如何将 edittextdata 数组中的值获取到我的 asynctask 变量中。我通过 execute 方法传入了数组并按照描述分配了变量,但是表格没有显示我输入的测试数据。它只是创建列名。
    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 2013-12-22
    • 2011-02-24
    • 1970-01-01
    相关资源
    最近更新 更多