开发者

How can I run my process of insert into database in background when my app is runing?

开发者 https://www.devze.com 2023-02-15 10:33 出处:网络
How can I run my process of ins开发者_JAVA技巧ert into database in background when my application is running? I want to run the process of insert query of the database in background.

How can I run my process of ins开发者_JAVA技巧ert 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消