我知道这个问题被问了很多次,但我仍然无法弄清楚如何将一个凌空响应传递给外部变量。
让我向您展示一个我需要的简化示例:
MainFragment.java
List<String> grabbedMovies = new ArrayList<>();
MovieGrabber.getMovies("https://example.com/movies.json", getContext(), new MovieGrabber.MovieGrabberCallback() {
@Override
public void onSuccess(List<String> response_movies) {
grabbedMovies = response_movies;
}
});
// do some other fancy stuff with grabbedMovies
此代码产生一个错误,告诉我变量是从内部类中访问的,需要声明为final 。这就是我所做的,所以很明显grabbedMovies = response_movies
将不再起作用,因为它是最终的,所以我修改了代码如下:
final List<String> grabbedMovies = new ArrayList<>();
MovieGrabber.getMovies("https://example.com/movies.json", getContext(), new MovieGrabber.MovieGrabberCallback() {
@Override
public void onSuccess(List<String> response_movies) {
for(Iterator<String> i = response_movies.iterator(); i.hasNext();) {
String item = i.next();
grabbedMovies.add(item);
}
}
});
// do some other fancy stuff with grabbedMovies
但是......结果,grabbedMovies
仍然是空的。
我还尝试将grabbedMovies
定义为全局变量 - 在public class MainFragment extends BrowseFragment {
之后没有最终声明。
所以,请有人向我解释我在这里做错了什么?
MovieGrabber.java (为了完整起见)
public final class MovieGrabber {
public static void getMovies(String url, final Context context, final MovieGrabberCallback callback) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
List<String> movies = new ArrayList<>();
Pattern pattern = Pattern.compile("SOME_PATTERN");
Matcher matcher = pattern.matcher(response);
while(matcher.find()) {
movies.add(matcher.group());
}
callback.onSuccess(movies);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestSingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public interface MovieGrabberCallback{
void onSuccess(List<String> response_movies);
}
我在Android Studio中玩Android TV的标准项目。 setupMovies
中有一个功能MovieList.java
,其中包含硬编码的电影,我试图通过REST调用来扩展它。