
我目前正在使用asynctask.cancel(true)但我无法阻止数据库插入.
public class TalkToServer extends AsyncTask<String,String,String> { @OverrIDe protected voID onPreExecute() { super.onPreExecute(); // show progress dialog } @OverrIDe protected voID onProgressUpdate(String... values) { super.onProgressUpdate(values); } @OverrIDe protected String doInBackground(String... params) { //download data from the server return something; } @OverrIDe protected voID onPostExecute(String result) { super.onPostExecute(result); // dismiss dialog }}解决方法 最好的选择是在onPostExecute()中执行数据库插入 *** 作. 如果取消AsyncTask,则不会调用onPostExecute().
从The Documentation for AsyncTask.cancel()开始:
Calling this method will result in onCancelled(Object) being invoked
on the UI thread after doInBackground(Object[]) returns. Calling this
method guarantees that onPostExecute(Object) is never invoked. After
invoking this method,you should check the value returned by
isCancelled() periodically from doInBackground(Object[]) to finish the
task as early as possible.
您还可以在doInBackground()方法中添加对isCancelled()的检查.
@OverrIDe protected String doInBackground(String... params) { //download data from the server if (isCancelled()){ //Prevent data from being inserted in the database try { runOnUiThread(new Runnable() { @OverrIDe public voID run() { //dismiss ProgressDialog } }); } catch (InterruptedException e) { e.printstacktrace(); } } return something; } @OverrIDe protected voID onPostExecute(String result) { super.onPostExecute(result); // dismiss dialog //Insert data into database } 总结 以上是内存溢出为你收集整理的android – 使用AsyncTask将数据插入数据库的正确方法是什么全部内容,希望文章能够帮你解决android – 使用AsyncTask将数据插入数据库的正确方法是什么所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)