How can I run my process of insert into database i

2019-08-12 00:26发布

How can I run my process of insert into database in background when my application is running? I want to run the process of insert query of the database in background.

Please can you give suggestion or a sample code?

Thanks in advance.

1条回答
贼婆χ
2楼-- · 2019-08-12 01:17

You use a class that extends AsynTask... Please refer this link for that.

Inside ur doInBackground() call ur method for doing insertion.

More Explanation:

Create an inner class InsertTask inside ur activity like:

private class InsertTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(String... params) {

            Boolean success = false;

            try {
                //place insert code here
                success = true;
            } catch (Exception e) {
                if(e.getMessage()!=null)
                    e.printStackTrace();
            }
            return success;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            super.onPostExecute(success);
        }
    }

Inside ur onCreate() give:

new InsertTask.execute();  //this calls the doInBackground method of InsertTask

By doing this, when ur activity is called, the things written inside doInBackground() runs, there by inserting ur values.

查看更多
登录 后发表回答