How to perform database operations using Async Task

前端 未结 2 540
难免孤独
难免孤独 2020-12-15 06:15

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 block

相关标签:
2条回答
  • 2020-12-15 06:48

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

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

    0 讨论(0)
  • 2020-12-15 07:09

    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

    0 讨论(0)
提交回复
热议问题