android中带有Endless Listview Scroll的AsynTask
Posted
技术标签:
【中文标题】android中带有Endless Listview Scroll的AsynTask【英文标题】:AsynTask with Endless Listview Scroll in android 【发布时间】:2013-12-14 12:12:25 【问题描述】:我正在创建一个需要无限滚动列表视图的应用程序。我不想在我的应用程序中使用任何库。我在网上看到了一些有助于实现此类列表视图的示例,但我的疑问是,当我的数据来自服务器并在 Asynctask 中被解析时,我怎么能拥有一个无穷无尽的列表视图。如何从滚动的异步任务中一次加载 10 个项目?我想知道在 asyntask 上实现一个无穷无尽的列表视图。 我是否在 onScroll() 中调用我的异步任务???
public class EndlessScrollExample extends ListActivity
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
public EventsBean eventsbean;
int counter = 0;
int currentPage = 0;
FetchEventValues fetchValues;
@Override
protected void onCreate(Bundle savedInstanceState)
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
else
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "my Url";
catch (NullPointerException e)
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
fetchValues = new FetchEventValues();
fetchValues.execute();
listview = getListView();
listview.setOnScrollListener(new EndlessScrollListener());
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Integer, Integer, Integer>
ProgressDialog progressdialog = new ProgressDialog(EndlessScrollExample.this);
@SuppressLint("SimpleDateFormat")
@SuppressWarnings("unchecked")
@Override
protected Integer doInBackground(Integer... params)
currentPage++;
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
//arrayEventsBeans.clear();
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
arrayEventsBeans = new ArrayList<EventsBean>();
// @SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext())
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray)
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
if ((today.compareTo(alldates) < 0 || (today.compareTo(alldates)== 0)))
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
String currentTimeStr = "7:04 PM";
Date userDate = new Date();
String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);
String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);
if (userDate.compareTo(currentDate) >= 0)
System.out.println(userDate + " is greater than or equal to " + currentDate);
else
System.out.println(userDate + " is less than " + currentDate);
JSONObject jsonobjname = jsonArray.getJSONObject(i);
EventsBean eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
if(!jsonobjname.isNull(Constants.COVER))
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
else
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
catch(Exception e)
Log.e(TAG , "Exception Occured:" + e.getMessage());
return null;
class CompareDate implements Comparator<DateBean>
@Override
public int compare(DateBean d1, DateBean d2)
return d1.getDate().compareTo(d2.getDate());
@Override
protected void onProgressUpdate(Integer... values)
// TODO Auto-generated method stub
super.onProgressUpdate(values);
@Override
protected void onPostExecute(Integer result)
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.progressdialog.isShowing())
this.progressdialog.dismiss();
if(adapter == null)
adapter = new SAmpleAdapter(EndlessScrollExample.this, 0, arrayEventsBeans);
listview.setAdapter(adapter);
else
adapter.notifyDataSetChanged();
//currentPage++;
@Override
protected void onPreExecute()
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
public int setPage(int currentPage)
return currentPage;
// TODO Auto-generated method stub
public class EndlessScrollListener implements OnScrollListener
private int visibleThreshold = 0;
private int currentPage = 0;
public EndlessScrollListener()
public EndlessScrollListener(int visibleThreshold)
this.visibleThreshold = visibleThreshold;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
@Override
public void onScrollStateChanged(AbsListView view, int scrollState)
if (scrollState == SCROLL_STATE_IDLE)
if (listview.getLastVisiblePosition() >= listview.getCount() - visibleThreshold)
currentPage++;
fetchValues.setPage(currentPage);
fetchValues.execute();
提前致谢。
【问题讨论】:
请解释一下,因为我很困惑你真正想要什么?圆形列表视图? 不,我想在我的项目中使用无限滚动列表视图,我无法实现它,因为我不知道如何将它与 asynctsk 一起使用。 我已经阅读了网上的例子,但他们没有展示如何在无尽的列表视图上使用 asynctask 好的,如果你想要无限滚动列表视图,那么试试这个链接github.com/commonsguy/cwac-endless 在那个项目中也有例子 是的,但我不必在我的项目中使用任何库。 【参考方案1】:ListView 已经支持 OnScrollListener,所以你必须重写它并检查条件(在 onScroll() 中),是否到达列表末尾或不是。如果是,则添加页脚(可选)并触发异步任务。收到结果后通知适配器。您可以在 link 上查看解决方案,它适用于相同的概念。
【讨论】:
【参考方案2】:以下是您正在寻找的几个示例: http://mobile.dzone.com/news/android-tutorial-dynamicaly https://github.com/johannilsson/android-pulltorefresh
【讨论】:
以上是关于android中带有Endless Listview Scroll的AsynTask的主要内容,如果未能解决你的问题,请参考以下文章
Android:为 Android Market 等 Endless List 实现进度条和“正在加载...”
Android:Endless Scrolling listview 内容错误和 NullpointerException
无尽跑酷3D (Endless Run 3D) 苹果安卓版免费下载|iOS|Android|iPhone版本免费下载 - 休闲 3D游戏 跑酷游戏 竞速游戏