Android 新闻应用程序 - 不要一次下载所有 json
Android News App - do not download all json at once
我正在开发 android 新闻应用。移动客户端应用程序通过 HttpRequest
和 'HttpResponse` 从 Web 服务器获取新闻。
我在 this article 的帮助下使用 Volley 异步加载图像。
问题是如果新闻在一段时间内变得太多,使用文章中的示例代码会发生什么。由于它在响应上有一个循环,它似乎一次下载所有 json
s。
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
避免一次下载所有 json 的最佳方法是什么?
您需要为服务器添加分页。您绝对不想从中下载所有新闻文章。您需要限制服务器发送给客户端的数据量。每次客户端需要更多数据时,都需要使用当前偏移量对服务器进行额外调用。
假设您到达了终点 http://news.com/api which returns 25 articles. When the user consumes those 25 articles ( you probably want to do it before they consume all 25, so there's no lag), you make another call to the server telling it to send you 25 articles with an offset of 25: http://news.com/api?limit=25&offset=25
您不能限制服务器的响应客户端。这必须在服务器上实现。
我正在开发 android 新闻应用。移动客户端应用程序通过 HttpRequest
和 'HttpResponse` 从 Web 服务器获取新闻。
我在 this article 的帮助下使用 Volley 异步加载图像。
问题是如果新闻在一段时间内变得太多,使用文章中的示例代码会发生什么。由于它在响应上有一个循环,它似乎一次下载所有 json
s。
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setYear(obj.getInt("releaseYear"));
// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
避免一次下载所有 json 的最佳方法是什么?
您需要为服务器添加分页。您绝对不想从中下载所有新闻文章。您需要限制服务器发送给客户端的数据量。每次客户端需要更多数据时,都需要使用当前偏移量对服务器进行额外调用。
假设您到达了终点 http://news.com/api which returns 25 articles. When the user consumes those 25 articles ( you probably want to do it before they consume all 25, so there's no lag), you make another call to the server telling it to send you 25 articles with an offset of 25: http://news.com/api?limit=25&offset=25
您不能限制服务器的响应客户端。这必须在服务器上实现。