Gourav Sharma Gourav Sharma - 2 months ago 14
Android Question

notifyDataSetChanged() makes the list refresh and scroll jumps back to the top of list

This is the main class. When I scroll down for more data and call the adapter, the list refreshes and scrolling jumps back to the top of list. I tried this for two days, but the issue remains.

I want the same position of list when scrolling down position.

public class MainActivity extends AppCompatActivity {

private ProgressDialog pDialog;

ArrayList<String> home_youmay_filepath = new ArrayList<String>();


ListView listViewyoumay;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);

listViewyoumay = (ListView) findViewById(R.id.lvItems);
// Attach the listener to the AdapterView onCreate
listViewyoumay.setOnScrollListener(new EndlessScrollListener() {
@Override
public boolean onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to your AdapterView
youmaylike(page);

// or customLoadMoreDataFromApi(totalItemsCount);
return true; // ONLY if more data is actually being loaded; false otherwise.

}
});

youmaylike(1);


}

private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}

private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}

private void youmaylike(int a) {

showpDialog();

Log.d("Starta", "Start" + a);

String url = "http://v2.picsdream.com/api/v1/galleries/abstract?page=" + a;


JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {
Log.d("cmsResponce", response.toString());

try {


JSONObject cards = response.getJSONObject("cards");


JSONArray data = cards.getJSONArray("data");

for (int i = 0; i < data.length(); i++) {

JSONObject person = (JSONObject) data
.get(i);


String filepath = person.getString("filepath");


home_youmay_filepath.add(filepath);


}

PhotofargmentAdapteryoumay adapter3 = new PhotofargmentAdapteryoumay(MainActivity.this, home_youmay_filepath);
listViewyoumay.setAdapter(adapter3);
adapter3.notifyDataSetChanged();


} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("LoginError", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
hidepDialog();
}
});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}


public class PhotofargmentAdapteryoumay extends BaseAdapter {


ArrayList<String> home_youmay_filepath = new ArrayList<String>();



private LayoutInflater layoutInflater;
Context context;

public PhotofargmentAdapteryoumay(Context Time_table, ArrayList<String> home_youmay_filepath) {

this.context = Time_table;

this.home_youmay_filepath = home_youmay_filepath;


layoutInflater = LayoutInflater.from(Time_table);

}


@Override
public int getCount() {

return home_youmay_filepath.size();
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.photoadapter_layout, null);
holder = new ViewHolder();
// holder.month = (TextView) convertView.findViewById(R.id.tvtext);
holder.img = (ImageView) convertView.findViewById(R.id.img_nature);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// holder.month.setText(listData.get(position).getMonth());

String image = home_youmay_filepath.get(position);


Log.d("Image", image);


try {


Picasso.with(context)
.load(image).noFade()
.into(holder.img);

// ImageLoader imgLoader = new ImageLoader(HomeActivity.this);
//
// imgLoader.DisplayImage(image, holder.img);

} catch (Exception e) {
e.printStackTrace();
}


return convertView;
}

class ViewHolder {
// TextView month;
ImageView img;
}
}


public abstract class EndlessScrollListener implements AbsListView.OnScrollListener {
// The minimum number of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 50;
// The current offset index of data you have loaded
private int currentPage = 1;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 50;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 1;

public EndlessScrollListener() {
}

public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}

public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
// this.startingPageIndex = startPage;
this.currentPage = startPage;
}


@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state


if (totalItemCount < previousTotalItemCount) {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0) {
this.loading = true;
}
}


// If it's still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
currentPage++;
}

// If it isn't currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
if (!loading && (firstVisibleItem + visibleItemCount + visibleThreshold) >= totalItemCount) {
loading = onLoadMore(currentPage + 1, totalItemCount);
}
}

// Defines the process for actually loading more data based on page
// Returns true if more data is being loaded; returns false if there is no more data to load.
public abstract boolean onLoadMore(int page, int totalItemsCount);

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}


}

Answer
PhotofargmentAdapteryoumay adapter3 = new PhotofargmentAdapteryoumay(MainActivity.this, home_youmay_filepath);
                            listViewyoumay.setAdapter(adapter3);

Remove this lines