asd*_*005 7 java android hyperlink android-asynctask
我有一个叫做的方法hostPhoto(); 它基本上将图像上传到网站并检索链接.然后,我有另一种方法将链接发布到网站.
现在我使用这种方法的方式是这样的:
String link = hostPhoto(); //returns a link in string format
post(text+" "+link); // posts the text + a link.
Run Code Online (Sandbox Code Playgroud)
我的问题是... hostPhoto()上传和检索链接需要几秒钟,我的程序似乎不等待并继续发布,因此我留下链接为null,
无论如何,我可以让它首先获得链接...然后发布?喜欢某种onComplete?或类似的东西..我认为上面的方法可以工作,但通过做Log.i's似乎链接返回到一秒左右后的字符串.
更新:这是我的问题的更新进度,我使用AsyncTask作为通知,但Log.i的错误输出显示urlLink为空...这意味着从hostphoto请求的链接永远不会回来的时间为日志. .
更新2:最终工作!问题是hostPhoto()中的线程,是否有人可以为我提供一个探索,为什么该线程会导致这个?感谢所有回复的人.
private class myAsyncTask extends AsyncTask<Void, Void, Void> {
String urlLink;
String text;
public myAsyncTask(String txt){
text=txt;
}
@Override
protected Void doInBackground(Void... params) {
urlLink=hostPhoto();
//Log.i("Linked", urlLink);
return null;
}
@Override
protected void onPostExecute(Void result) {
try {
Log.i("Adding to status", urlLink);
mLin.updateStatus(text+" "+urlLink);
Log.i("Status:", urlLink);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
hostPhoto()执行此操作:
String link; new Thread(){
@Override
public void run(){
HostPhoto photo = new HostPhoto(); //create the host class
link= photo.post(filepath); // upload the photo and return the link
Log.i("link:",link);
}
}.start();
Run Code Online (Sandbox Code Playgroud)
Lal*_*ani 11
你可以在这里使用AsyncTask,
通过使用它你可以执行代码
hostPhoto()
在doInBackground()中然后执行代码
post(text+" "+link);
在onPostExecute()方法中,这将是您的最佳解决方案.
您可以使用此模式编写代码
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params) {
hostPhoto();
return null;
}
@Override
protected void onPostExecute(Void result) {
post(text+" "+link);
}
}
Run Code Online (Sandbox Code Playgroud)
并且可以使用它来执行它
new MyAsyncTask().execute();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31051 次 |
| 最近记录: |