如何使用Async Task执行数据库操作

时间:2022-12-26 11:52:13

My application is getting stuck while performing database operation after googling for solutions it was suggested that I use AsyncTask so that main thread doesn't get blocked.

谷歌搜索解决方案后,我的应用程序在执行数据库操作时遇到困难,建议我使用AsyncTask,以免主线程被阻塞。

I have created seperate class and extended SQLiteOpenHelper and implemented "OnCreate" and "OnUpgrade" method. But to implement AsyncTask I need to extend "AsyncTask". Now my issue here is that I have already extended one class and I can't extend another class for the same class.

我创建了单独的类和扩展的SQLiteOpenHelper并实现了“OnCreate”和“OnUpgrade”方法。但是为了实现AsyncTask,我需要扩展“AsyncTask”。现在我的问题是我已经扩展了一个类,我不能为同一个类扩展另一个类。

My code is something like this.

我的代码是这样的。

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;

import com.example.project.R;

public class Database  extends SQLiteOpenHelper{

    static final String dbname="Project";
    static final int dbversion=1;

    TableA r=new TableA();


    SQLiteDatabase db;
    private Context Context;
    public Database(Context context) {
        super(context,  dbname, null, dbversion);
        try{
        db=getWritableDatabase();
        // TODO Auto-generated constructor stub
        if (db.isOpen()){

            System.out.println("Database is opened");
        }
            else{


                System.out.println("Database is not opened");
            }

        }
        catch(Exception e){

            Log.e(dbname, e.getMessage());

        }
    }


    @Override
    public void onCreate(SQLiteDatabase db) {

        // TODO Auto-generated method stub
        try{
        db.beginTransaction();

        db.execSQL(r.r_Table);


        db.insert(r.Tablename, null, r.insertdata());
        db.setTransactionSuccessful();
        retrivedata();
        }
        catch(Exception e){

            android.util.Log.e(r.Tablename, e.getMessage());

        }

        finally{

            db.endTransaction();
        }


    }//

Can anyone suggest how I can perform database operations with SQLiteOpenHelper within an AsyncTask.

任何人都可以建议我如何在AsyncTask中使用SQLiteOpenHelper执行数据库操作。

Thanks Siva

谢谢湿婆

2 个解决方案

#1


13  

In your Actvity add the following code, do the required changes,

在Actvity中添加以下代码,进行必要的更改,

private class GetContacts extends AsyncTask<Object, Object, Cursor> {
    DatabaseConnector dbConnector = new DatabaseConnector(
            getApplicationContext());

    @Override
    protected Cursor doInBackground(Object... params) {
        dbConnector.open();
        if (dbConnector.getAllValues() != null) {
            return dbConnector.getAllValues();
        } else
            return null;
    }

    @Override
    protected void onPostExecute(Cursor result) {
        if (result != null) {
            conAdapter.changeCursor(result); // set the adapter's Cursor
            dbConnector.close();
        }
    }
}

execute this by new GetContacts().execute((Object[]) null);

通过新的GetContacts()执行它.execute((Object [])null);

#2


0  

No, you can't extend a class from multiple classes as it violates the property of java because java doesn't support multiple inheritence so for your case you have to create a new class which will extend ASyncTask and override the abstract methods to perform all the database related operations. Thank you

不,你不能从多个类扩展一个类,因为它违反了java的属性,因为java不支持多重继承,所以对于你的情况,你必须创建一个新类,它将扩展ASyncTask并覆盖抽象方法来执行所有数据库相关的操作。谢谢

#1


13  

In your Actvity add the following code, do the required changes,

在Actvity中添加以下代码,进行必要的更改,

private class GetContacts extends AsyncTask<Object, Object, Cursor> {
    DatabaseConnector dbConnector = new DatabaseConnector(
            getApplicationContext());

    @Override
    protected Cursor doInBackground(Object... params) {
        dbConnector.open();
        if (dbConnector.getAllValues() != null) {
            return dbConnector.getAllValues();
        } else
            return null;
    }

    @Override
    protected void onPostExecute(Cursor result) {
        if (result != null) {
            conAdapter.changeCursor(result); // set the adapter's Cursor
            dbConnector.close();
        }
    }
}

execute this by new GetContacts().execute((Object[]) null);

通过新的GetContacts()执行它.execute((Object [])null);

#2


0  

No, you can't extend a class from multiple classes as it violates the property of java because java doesn't support multiple inheritence so for your case you have to create a new class which will extend ASyncTask and override the abstract methods to perform all the database related operations. Thank you

不,你不能从多个类扩展一个类,因为它违反了java的属性,因为java不支持多重继承,所以对于你的情况,你必须创建一个新类,它将扩展ASyncTask并覆盖抽象方法来执行所有数据库相关的操作。谢谢