如何使用异步任务

时间:2018-02-27 23:23:51

标签: android sqlite android-asynctask

我的应用程序在执行数据库操作时卡住了,我的问题是如何在这种情况下使用Async Task来消除用户界面的延迟。任何示例代码都会有所帮助! 我很多时候都在坚持这个问题,所以我依靠你们。

这是我的数据库类:

public class database extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "Contacts.database";
    private static final String TABLE_NAME = "Contacts";
    private static final String COLUMN_NAME = "contact_name";
    private static final String COLUMN_NUMBER = "contact_number";
    private Boolean exists = false;
    public database(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        //execute the create table query
        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + "(" +
                COLUMN_NAME + " TEXT, " +
                COLUMN_NUMBER + " TEXT " +
                ");");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

        onCreate(sqLiteDatabase);
    }

    //add row to database
    public void addContact( String ContactNumber, String ContactName){
        ContentValues values = new ContentValues();
            values.put(COLUMN_NAME, ContactName);
            values.put(COLUMN_NUMBER, ContactNumber);
            SQLiteDatabase db = getWritableDatabase();
            db.insert(TABLE_NAME, null, values);
            db.close();
            exists = true;
    }

    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase(); //create/open db for reading/writing
        Cursor res = db.rawQuery("SELECT * FROM " + TABLE_NAME , null);  //runs SQL query and returns cursor over result
        /*the second paramenter to rawQuery is cancellableSignal which signifies that what
        needs to be done when the operation is cancelled...
        in this case null signifies nothing...*/

        /*Cursor: A Cursor implementation exposes results from a query on a SQLiteDatabase*/
        return res;
    }

    public int tableExists(){
      //  boolean isTableExists(SQLiteDatabase db, String tableName)
       SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("SELECT  * FROM " + TABLE_NAME,null);
            int count = cursor.getCount();
            cursor.close();
            return count;

    }
}

这是我创建Methode的片段:

@Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            mRootView = inflater.inflate(R.layout.fragment_four, container, false);
            myDB = new database(getActivity());
            exist = myDB.tableExists();

            rvContacts = (RecyclerView) mRootView.findViewById(R.id.rvContacts);
            return mRootView;
        } 

0 个答案:

没有答案