好的,所以我有一个通过从网络上提取 JSON 数据来填充的列表视图。我将项目包装在 SwypeRefreshLayout 中。发生的事情是当我下拉时,它获取数据,清除 Arraylist,重建它,然后通知适配器数据集更改。但是我没有立即看到新数据。为了在顶部看到新项目,我需要向下滚动以使其不在视野范围内,然后再返回。
这是我用来刷新列表的代码。
swipelists.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() {
@Override public void onRefresh() {
if(getArguments().getInt(ARG_SECTION_NUMBER) == 3 ) {
recentArrayList.clear();
long totalSize = 0;
recadapter = new ArrayAdapter(ctx,android.R.layout.simple_list_item_1, recentArrayList);
new updatetheRecent().execute(ctx);
}
else {
swipelists.setRefreshing(false);
}
}});
这是被调用来重建列表的函数
private class updatetheRecent extends AsyncTask<Context, Integer, Long> {
protected Long doInBackground(Context... urls) {
int count = urls.length;
long totalSize = 0;
try {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet("http://test.net/pltxtrec.php");
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
JSONArray json = new JSONArray(resString);
for (int i = 0; i < json.length(); i++) {
JSONObject json_data = json.getJSONObject(i);
String jsonvalues = json_data.getString("title");
if (!jsonvalues.equals("")) {
recentArrayList.add(json_data.getString("artist") + " - " + json_data.getString("title"));
// .. get all value here
}
}
if (recentArrayList.isEmpty()) {
recentArrayList.add("No items currently in queue");
}
is.close(); // Close the stream
getActivity().runOnUiThread(new Runnable() {
public void run() {
recadapter.notifyDataSetChanged();
swipelists.setRefreshing(false);
}
});
}
catch (Exception e) {
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
if (recentlist != null) {
// Tried adding this is but its never called
recentlist.smoothScrollToPosition(0);
}
}
}