我有一个名为hostPhoto()的方法;它基本上将图像上传到网站并检索链接.
然后我有另一种方法将链接发布到网站.
然后我有另一种方法将链接发布到网站.
现在我使用这种方法的方式是这样的:
- String link = hostPhoto(); //returns a link in string format
- post(text+" "+link); // posts the text + a link.
我的问题是… hostPhoto()需要几秒钟来上传和检索链接,
我的程序似乎不等待并继续发布,因此我将链接保留为null,
无论如何,我可以让它首先获得链接…然后发布?
喜欢某种onComplete?或类似的东西..
我认为上面的方法可以工作,但通过做Log.i,似乎链接在一秒左右后返回到字符串.
更新:这是我的问题的更新进度,我使用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();
- }
- }
- }
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();
解决方法
你可以在这里使用AsyncTask,
通过使用它你可以执行代码
hostPhoto()
在onPostExecute()方法中,这将是您的最佳解决方案.
您可以使用此模式编写代码
- private class MyAsyncTask extends AsyncTask<Void,Void>
- {
- @Override
- protected Void doInBackground(Void... params) {
- hostPhoto();
- return null;
- }
- @Override
- protected void onPostExecute(Void result) {
- post(text+" "+link);
- }
- }
并且可以使用执行它
- new MyAsyncTask().execute();