Start a new topic

Issue on getting File Metadata

Hi,



I have create a method

String image_url="";

image_url=getImageURL(IMAGE_ID); to get url of file.



I am getting its url inside '**onsuccess**' block, but not outside.





public String getImageURL(String iMAGE_ID) {



mKinveyClient.file().downloadMetaData(iMAGE_ID, new KinveyClientCallback() {



@Override

public void onSuccess(FileMetaData arg0) {

image_url=arg0.getDownloadURL().toString();

System.out.println("image_url==>"+image_url);//Here it is displying url of file



}



@Override

public void onFailure(Throwable error) {}



});



System.out.println("image_url==>"+image_url);//Here it is returning blank string

return image_url;

}



Please Help.

Hey,



This is the nature of asynchronous code. What happens is the method will attempt to return `image_url` (and fail) before the network request has completed. The `OnSuccess` method is executed by the library once the request returns, which might take a while.



You might have to refactor your code a bit so that whatever code uses the `image_url` is only run after the callback to `OnSuccess`-- instead of having this method return the image_url, have this method call the next one in that `OnSuccess` method.
Thanx Edward,



will you explain it little more.
The idea is that when you make a network request, it can take a while. Maybe the person has a bad internet connection. So instead of making the computer wait for the response to come back, we let the computer keep doing other stuff-- and whenever that network request does comes back, we will deal with it then. So a network request could take ten seconds on a good connection or up to a minute with a poor network connection.



Does that make sense?



So, since we don't want the computer to just sit there idle waiting for the request to finish, we use the "callback pattern". The idea is that the original code will continue executing past the call to "save" or "get"-- even though those requests have not yet returned. The library handles this by creating a new `AsyncTask` for each request. The AsyncTask will make the request over the network, wait for the response to come back, and then finally call onSuccess or onFailure depending on what happened.



This means that if you have the following:



myClass.MyMethod1();

myClient.appdata(...).save(...);

myClass.MyMethod2();





MyMethod1() will run, the call to appdata.save will spawn a new Asynctask, running in the background, then MyMethod2() will run. Then, later on, maybe seconds or minutes later, the onSuccess method will be run.



So, you need to access the results of the request, put the code in the onSuccess block-- not where MyMethod2() is.



Let me know if that helps!



Login or Signup to post a comment