我正在尝试从此方法返回Movie类型的Object。
public MovieParty getMovie(String id) {
public Movie movie;
//Create AsyncTask
connection = new getMovieTask(new RestObserver() {
@Override
public void downloadFinished(String result) {
try {
//parse the JSON string here and assign it to movie;
}
catch (JSONException e) {
e.printStackTrace();
}
}
});
connection.execute(id);
return movie
}
getMovieTask扩展了AsyncTask。
我在异步任务中的downloadFinihsed()
中运行onPostExecute
。我已经阅读了关于此事的所有内容,但我仍然无法弄清楚如何正确执行“return movie
”,因为它尚未分配。
答案 0 :(得分:0)
快速举例说明你可以做什么:
创建自定义侦听器:
interface MovieLoadListener{
void onMovieLoaded(Movie movie);
void onMovieLoadFailed(Exception e);
}
更改您的方法:
public void loadMovieAsync(String id,final MovieLoadListener listener) {
//Create AsyncTask
connection = new getMovieTask(new RestObserver() {
@Override
public void downloadFinished(String result) {
Movie movie;
try {
// do your parsing stuff
listener.onMovieLoadFailed(e);
}
catch (JSONException e) {
e.printStackTrace();
listener.onMovieLoadFailed(e);
}
}
});
connection.execute(id);
}
致电您的方法:
loadMovieAsync(id, new MovieLoadListener() {
@Override
public void onMovieLoaded(Movie movie) {
// do with your movie what you like here
}
@Override
public void onMovieLoadFailed(Exception e) {
// error handling
}
} );