При скроллинге сделал динамическую подгрузку контента, но старые данные удаляются и заменяются новыми, с чем это связано? И как поправить?
public class MainActivity extends AppCompatActivity {
private String URL_TO_HIT;
private ListView thumbList;
private ProgressDialog dialog;
boolean isLoading;
private int skip = 0;
private String debug = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Загрузка. Пожалуйста подождите...");
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
thumbList = (ListView)findViewById(R.id.thumbList);
// Добавление ProgressBar
ProgressBar footer = new ProgressBar(this);
thumbList.addFooterView(footer);
thumbList.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
//Log.d(debug, "scrollState = " + scrollState);
isLoading = false;
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if (lastInScreen == totalItemCount && ! isLoading) {
skip = lastInScreen == 0 ? 0 : lastInScreen-1;
URL_TO_HIT = "https://домен?limit=20&skip=" + skip;
Log.d(debug, "URL: " + URL_TO_HIT);
isLoading = true;
new JSONTask().execute(URL_TO_HIT);
}
}
});
//new JSONTask().execute(URL_TO_HIT);
}
public class JSONTask extends AsyncTask<String,String, List<ThumbModel> >{
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
@Override
protected List<ThumbModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
List<ThumbModel> thumbModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
ThumbModel thumbModel = gson.fromJson(finalObject.toString(), ThumbModel.class);
// adding the final object in the list
thumbModelList.add(thumbModel);
}
return thumbModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(final List<ThumbModel> result) {
super.onPostExecute(result);
dialog.dismiss();
if(result != null) {
ThumbAdapter adapter = new ThumbAdapter(getApplicationContext(), R.layout.row, result);
thumbList.setAdapter(adapter);
thumbList.setOnItemClickListener(new AdapterView.OnItemClickListener() { // list item click opens a new detailed activity
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ThumbModel thumbModel = result.get(position); // getting the model
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("thumbModel", new Gson().toJson(thumbModel)); // converting model json into string type and sending it via intent
startActivity(intent);
}
});
} else {
Toast.makeText(getApplicationContext(), "Не удалось получить данные с сервера, пожалуйста, проверьте URL-адрес.", Toast.LENGTH_SHORT).show();
}
}
}
private class ThumbAdapter extends ArrayAdapter{
private List<ThumbModel> thumbModelList;
private int resource;
private LayoutInflater inflater;
public ThumbAdapter(Context context, int resource, List<ThumbModel> objects) {
super(context, resource, objects);
thumbModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.thumbImage = (ImageView)convertView.findViewById(R.id.image);
//holder.catalog = (TextView)convertView.findViewById(R.id.catalog);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar = (ProgressBar)convertView.findViewById(R.id.progressBar);
// Then later, when you want to display image
final ViewHolder finalHolder = holder;
ImageLoader.getInstance().displayImage(thumbModelList.get(position).getImage("thumb"), holder.thumbImage, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
finalHolder.thumbImage.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
finalHolder.thumbImage.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
finalHolder.thumbImage.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
finalHolder.thumbImage.setVisibility(View.INVISIBLE);
}
});
/*holder.tvMovie.setText(thumbModelList.get(position).getMovie());
holder.tvTagline.setText(thumbModelList.get(position).getTagline());
holder.tvYear.setText("Year: " + thumbModelList.get(position).getYear());
holder.tvDuration.setText("Duration:" + thumbModelList.get(position).getDuration());
holder.tvDirector.setText("Director:" + thumbModelList.get(position).getDirector());*/
// rating bar
//holder.rbMovieRating.setRating(movieModelList.get(position).getRating()/2);
/*StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
stringBuffer.append(cast.getName() + ", ");
}
holder.tvCast.setText("Cast:" + stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());*/
return convertView;
}
class ViewHolder{
private ImageView thumbImage;
}
}
}