如何从 Android AsyncTask 获取字符串
我最近开发了一个姜饼应用程序。现在我想把它变成蜂窝状。 现在我的异步任务有问题。我想将信息(例如字符串)从 asynktask 类传递到我启动它的活动。 抱歉,这是我第一次使用 asynctasks,所以我还不太了解它。
I recently developed an app for gingerbread. Now I wanted to get it to honeycomb.
Now I have a problem with my asynctask. I want to pass information (a string for example) from the asynktask-class to the activity, I started it from.
I am sorry, this is the first time I am using asynctasks and so I don't know a lot about it yet.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,解决方案是使您的
AsynkTask
成为您的Activity
的内部类,并且通过将String
传递给Activity
code> 您的意思是您想要将TextView
的文本设置为该String
您可以在onPostExecute()
方法中执行此操作您的AsynkTask
。因此,假设您的 doInBackground() 方法进行了一些处理并构造了一个 String,然后返回该 String 并将其传递给
onPostExecute()
方法,该方法在UIThread
上运行,可以修改您的Activity
UI。Yes, the solution is to make your
AsynkTask
an inner class of yourActivity
and if by passing aString
to theActivity
you mean that you want for example to set aTextView
's text to thatString
you can do this in theonPostExecute()
method of yourAsynkTask
.So let say that your
doInBackground()
method does some processing and constructs aString
than it returns thatString
and passes it to theonPostExecute()
method, which runs on theUIThread
and can modify yourActivity
UI.使用AsyncTask作为内部类,并在调用AsyncTask的外部类中声明一个字符串。在asyncTask中,将外部类中声明的字符串的值赋值给外部类。
Use AsyncTask as an inner class and declare a string in the outer class that call AsyncTask.In asyncTask,assign the value of the string declared in outer class.
Rasel 建议这可以是一个解决方案,您也可以简单地使用 getter setter 方法,它的范围是整个项目,
像这样使用它,
并且为了获取其值,只需使用
它将返回最后更新的值。
Rasel suggested is can be a solution and you can also simply use the getter setter method also its scope is entire project
use it like this
and for getting its value simply use
that will return the last updated value.
我认为Rasel的报价是不可接受的。因为 Asynctask 有不同的线程,所以有时在 Asynctask 之后打印任何全局变量可以在 Asynctask 之前完成。所以它有时会得到空或不需要的结果。
I think the offer of Rasel is not acceptable. because Asynctask has different thread so sometimes printing any global variable after Asynctask can be done before Asynctask. so it gets sometimes null or unwanted result.
方法execute返回的是AynscTask本身,你需要调用方法AsynkTask.get()来获取任务的结果(当然如果结果类型是String;)):
The method execute returns the AynscTask itself, you need to call the method AsynkTask.get() so as to get the result of the task (of course if the result type is a String ;) ):