以下是MainActivity的代码,我使用Async任务下载数据。但是数据没有显示出来。在onPostExecute方法中,movieList包含15个项目,但在onCreate方法中它显示为同一个变量的零项。
public class MainActivity extends AppCompatActivity {
public static final String YIFY_REQUEST_URL = "https://yts.am/api/v2/list_movies.json?limit=15&page=1";
RecyclerView recyclerView;
int k = 1;
private int previousTotal = 0;
private boolean loading = true;
private int visibleThreshold = 5;
int firstVisibleItem, visibleItemCount, totalItemCount;
MovieAdapter adapter;
List<Movie> movieList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YifyAsyncTask yifyAsyncTask = new YifyAsyncTask();
yifyAsyncTask.execute(YIFY_REQUEST_URL);
adapter = new MovieAdapter(movieList);
Log.v("Movie%count",movieList.size() +"");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
final GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
gridLayoutManager.setSpanCount(2);
recyclerView.setLayoutManager(gridLayoutManager);}
else
{ gridLayoutManager.setSpanCount(3);
recyclerView.setLayoutManager(gridLayoutManager);}
//recyclerView.setItemViewCacheSize(20);
//recyclerView.setDrawingCacheEnabled(true);
//recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
visibleItemCount = recyclerView.getChildCount();
totalItemCount = gridLayoutManager.getItemCount();
firstVisibleItem = gridLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading && (totalItemCount - visibleItemCount)
<= (firstVisibleItem + visibleThreshold)) {
// End has been reached
Log.v("Yaeye!", "end called");
int cur = adapter.getItemCount();
// Do something
new YifyAsyncTask().execute("https://yts.am/api/v2/list_movies.json?limit=15&page=" + (++k));
adapter.notifyItemRangeInserted(cur,15);
loading = true;
}
}
});
}
private class YifyAsyncTask extends AsyncTask<String,Void,List<Movie>>{
@Override
protected List<Movie> doInBackground(String... urls) {
URL url = createUrl(urls[0]);
String jsonresponse = "";
try{
jsonresponse = makeHttpRequest(url);
}
catch (IOException e){
}
return extractMovieFromJson(jsonresponse);
}
@Override
protected void onPostExecute(List<Movie> moviesList) {
//MovieAdapter adapter = new MovieAdapter(movieList);
//recyclerView.setAdapter(adapter);
//adapter.notifyItemRangeInserted(adapter.getItemCount(),15);
movieList.addAll(moviesList);
}
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
return null;
}
return url;
}
private String makeHttpRequest(URL url) throws IOException{
String jsonresponse = null;
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonresponse = readFromStream(inputStream);
}
catch (IOException e){
}
finally {
if(urlConnection != null)
urlConnection.disconnect();
if (inputStream != null)
inputStream.close();
}
return jsonresponse;
}
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader inputStreamReader = new InputStreamReader(inputStream , Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null){
output.append(line);
line = reader.readLine();
}
}
//Log.v("response",output.toString());
return output.toString();
}
private List<Movie> extractMovieFromJson(String movieJson){
List<Movie> movieList = new ArrayList<>();
if (TextUtils.isEmpty(movieJson))
return null;
try{
JSONObject basejsonresponse = new JSONObject(movieJson);
JSONObject data = basejsonresponse.getJSONObject("data");
JSONArray movieArray = data.getJSONArray("movies");
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
String movieName = movie.getString("title_long");
String movieUrl = movie.getString("url").replaceAll("\\\\","");
String movieImg = movie.getString("large_cover_image").replaceAll("\\\\","");
//Log.v("url",movieImg);
movieList.add(new Movie(movieName,movieUrl,movieImg));
}
return movieList;
}
catch (JSONException e){
}
return null;
}
}
}
之前我在onPostExecute方法中设置了适配器。但是后来我删除了它并在onCreate方法中设置它。但是如果我在onPostExecute电影中使用notifyDataSetChanged方法正在显示。如果我使用notifyItemRangeChanged方法,即使那时数据也没有显示。我无法理解我在哪里做错了。我是初学者,不介意我糟糕的编码风格。
答案 0 :(得分:1)
你不能按照你的方式调用notifyDataSetChanged()方法,应该在你的onPostExecute()或从它调用的方法上调用该方法。由于您正在执行异步请求,请参阅下文。您的下一行(adapter.notifyItemRangeInserted(cur,15);)无法保证/预期在下面的行之后调用。
new YifyAsyncTask().execute("https://yts.am/api/v2/list_movies.json?limit=15&page=" + (++k));