如何从UI线程访问SQLite数据库,如果我在AsyncTask的线程插入数据? [英] How to access SQLite database from UI thread if I'm inserting data in AsyncTask thread?

查看:223
本文介绍了如何从UI线程访问SQLite数据库,如果我在AsyncTask的线程插入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Andr​​oid应用程序的一类,称为Main.java,用于验证数据的用户登录信息(用户名+密码)在我的服务器。起初,我成功了;我用了一个线程的AsyncTask做到这一点加上它处理HTTP连接库,调用HttpPostAux.java(其实,我发现图书馆的code这里在这个论坛)。在的AsyncTask的onPostExecute方法,我创建并启动新的活动,而不是修改当前之一,它的工作。

I have a class in my Android app, called Main.java, to validate a user login (user name + password) against the data in my server. At first, I succeeded; I used an AsyncTask thread to do it plus a library which handles the Http connection, call HttpPostAux.java (in fact, I found the library's code here in this forum). In the onPostExecute method of AsyncTask, I was creating and starting a new activity instead of modifying the current one and it worked.

但现在我想要做的事情不同。我想经过验证的数据(用户名+密码)保存到一个SQLite表中的AsyncTask的线程,然后在UI线程,恢复数据,并用它来打开提到的活动。发生插入,但是当我试图从UI线程访问数据库:它说,该表是空的。所以,我看着在logcat中,我发现UI线程的AsyncTask线程之前执行。

But now I want to do things different. I want to save the validated data (user name + password) into a SQLite table in the AsyncTask thread and then in the UI thread, recover that data and use it to open the mentioned activity. The insertion occurs but when I'm trying to access the database from UI thread: it says that the table is empty. So I looked in the logcat and I found that UI thread executes before AsyncTask thread.

所以我的问题是如何在AsyncTask的线程插入数据,然后恢复它UI线程里面呢?大家能否帮助吗?我有点失去了!

So my question is how to insert data in the AsyncTask thread and then recover it inside UI thread? Can anybody help here? I'm kind of lost!

我将AP preciate一个code例子!提前致谢!
来自委内瑞拉的问候!

I will appreciate a code example! Thanks in advance! Greetings from Venezuela!

推荐答案

UI线程应用程序的主线程。当您在一个单独的线程创建一个的AsyncTask ,你很长一段时间回吐任务将被执行(在 doInBackground 功能) 。当 doInBackground 完成后, onPostExecute()将从UI线程调用。所以,你只需要执行您的UI线程任务(=恢复数据,并用它来打开提到的活动)从里面 onPostExecute()

UI thread is your applications main thread. When you create an AsyncTask, your long time-taking task will be executed(inside doInBackground function) on a separate thread. When doInBackground completes, onPostExecute() will be called from the UI thread. So you simply need to execute your UI thread task(="recover that data and use it to open the mentioned activity") from inside onPostExecute().

这篇关于如何从UI线程访问SQLite数据库,如果我在AsyncTask的线程插入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆