简体   繁体   中英

When scrolling Listview and stops at any item, it moves to top position android

I am getting items based on pagination.All items are displaying but problem is that when i stop scrolling at any position, it moves to top. Please help me to solve this. I have issue in onscrolllistener in listview .

My code is as follows:

int pagesize = 1;

private class MovieTop extends AsyncTask {

@Override
protected ArrayList<HashMap<String, String>> doInBackground(
        Object... params) {
    try {
        return displayTopMovies();
    } catch (IOException e) {
        return null;
    }
}


public ArrayList<HashMap<String, String>> displayTopMovies()
        throws IOException {

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder
            .append("https://movie.org/movie/popular?");
    stringBuilder.append("?api_key=" + "c68"+"&&page="+pagesize); //getting page increment
    URL url = new URL(stringBuilder.toString());
    InputStream stream = null;
    try {
        // Establish a connection
        HttpURLConnection conn = (HttpURLConnection) url
                .openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("Accept", "application/json");              conn.setDoInput(true);
        conn.connect();
        int responseCode = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response code is: " + responseCode + " "
                + conn.getResponseMessage());

        stream = conn.getInputStream();
        return parseTopMovies(stringify(stream));
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
  parsing been done here..
private ArrayList<HashMap<String, String>> parseTopMovies(String result) {
    String streamAsString = result;
    ArrayList<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
    try {
        JSONObject jsonObject = new JSONObject(streamAsString);
        JSONArray array = (JSONArray) jsonObject.get("results");
        for (int i = 0; i < array.length(); i++) {
            HashMap<String, String> map = new HashMap<String, String>();
            JSONObject jsonMovieObject = array.getJSONObject(i);
            map.put(KEY_TITLE,
                    jsonMovieObject.getString("original_title"));
            results.add(map);
        }
    } catch (JSONException e) {
        System.err.println(e);
        Log.d(DEBUG_TAG, "Error parsing JSON. String was: "
                + streamAsString);
    }
    return results;
}

}
   @Override
  protected void onPostExecute(Object result) {
    update2((ArrayList<HashMap<String, String>>) result);
    };


   //Here i am displaying result
   public void update2(ArrayList<HashMap<String, String>> result) {
   this.result.addAll(result);
   ListView listView =(ListView)findViewById(R.id.container);

   // Add results to listView.
   adapter = new UpcomingMovieAdapters(this, R.layout.upcoming,result);
   listView.setAdapter(adapter);
   // here i am using notifyDatasetchanged.
   adapter.notifyDataSetChanged();
    try {

        listView.setOnScrollListener(new OnScrollListener() {
            public void onScroll(AbsListView view, int firstVisibleItem,
                    int visibleItemCount, int totalItemCount) {

                // TODO Auto-generated method stub
            }

            public void onScrollStateChanged(AbsListView view,
                    int scrollState) {
                // TODO Auto-generated method stub
                if (scrollState == 0) {
                    // Log.i("a", "scrolling stopped...");
                    if (pagesize <= 30) {
          Toast.makeText(getApplicationContext(),"Moving to top when scroll stopped at any item position..", 1000).show();
                        pagesize = pagesize + 1;

                            new MovieTop().execute();
                    }
                }
            }

        });
    } catch (Exception e) {
        System.out.println(e);
    }

}

as you create Adapter in each incoming data, your list scroll to first position, for handling this issue you need create your adapter just once then use adapter.notifyDataSetChanged(); for refreshing data.

in onCreate method use

 adapter = new UpcomingMovieAdapters(this, R.layout.upcoming,result);
 listView.setAdapter(adapter);

then in async class use following code.

 public void update2(ArrayList<HashMap<String, String>> result) {
   this.result.addAll(result);

   // just use this line 
   adapter.notifyDataSetChanged();

The problem is you're setting the adapter to the list repeatedly. You should only do this once, every time you set it the list view is reset to the top. Instead you need to have one instance of the adapter to update then call notifyDataSetChanged() to tell the list view to update itself.

I think, that problem is in calling new MovieTop().execute(); onScroll stopped, because data are parsed for next page, but Adapter is created again in onPostExecute .

If this.result is ArrayList with all results, try to use:

if(adapter == null) {
    adapter = new UpcomingMovieAdapters(this, R.layout.upcoming,result);
    listView.setAdapter(adapter);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM