我有一个GridView显示图像。我创建了一个setOnScrollListener来检查用户何时到达gridview的底部。 然后我需要将新图像附加到gridview。 (就像无穷无尽的adpter)。
但我无法找到更新我的附件的方法。请你帮个忙。非常感谢:
这是我正在研究的方法:
public void customLoadMoreDataFromApi(int offset) { ...... SEE BELOW ...... }
GridView活动
//This Activity Loads the Get Images Thumnail in a GridView
public class GalleryInGridViewCallfromAPI extends Activity {
public static final String TAG = GalleryInGridViewCallfromAPI.class.getSimpleName();
//View v;
GridView gridview;
AlbumPhotosAdapter adapter;
ProgressDialog dialog;
String album_id;
ImageLoader imageLoader;
RelativeLayout overlay;
ArrayList<String> stringArrayList = new ArrayList<String>(); //Big Image
ArrayList<String> stringArrayListTitle = new ArrayList<String>(); //Title of big image
ArrayList<String> stringArrayList_thumb = new ArrayList<String>(); //ThumbNail
//VarController vc;
APICall api;
//Global Json obj for GetBigImageUrl();
public static JSONObject mJsonobject; //GetBigImageUrl
public static JSONArray mJsonarray; //GetBigImageUrl
//Get Data From Home Activity
Intent intent;
Bundle bundle;
String mGetAlbumCategory;
//Global to set new paginated data
//Page Number
public static int mPageNumberInt = 1;
public static String mPageNumber = Integer.toString(mPageNumberInt);
//Items Limit
public static int mItemLimitInt = 30;
public static String mItemLimit = Integer.toString(mItemLimitInt);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_photo_list);
intent = this.getIntent();
bundle = intent.getExtras();
mGetAlbumCategory = bundle.getString("category");
//vc = new VarController(MyApplication.getAppContext());
api = new APICall(MyApplication.getAppContext());
imageLoader = new ImageLoader(this);
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter = new AlbumPhotosAdapter());
// ONSCROLLLISTENER
// Attach the listener to the AdapterView onCreate
gridview.setOnScrollListener(new EndlessScrollListener() {
@Override
public void 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
customLoadMoreDataFromApi(page);
// or customLoadMoreDataFromApi(totalItemsCount);
Toast.makeText(getApplicationContext(), "EndlessScrollListener", Toast.LENGTH_SHORT).show();
}
});
// ONCLICK
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Log.w("view pager", "111: " + position);
Toast.makeText(getApplicationContext(), "setOnItemClickListener" + position, Toast.LENGTH_LONG).show();
//startImagePagerActivity(position);
String[] mImages = stringArrayList.toArray(new String[stringArrayList.size()]);
String[] mImagesTiles = stringArrayListTitle.toArray(new String[stringArrayListTitle.size()]);
String[] mThumbImages = stringArrayList_thumb.toArray(new String[stringArrayList_thumb.size()]);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putStringArray("photo_list", mImages);
bundle.putStringArray("url_title", mImagesTiles);
bundle.putStringArray("thumb_list", mThumbImages);
bundle.putInt("pos", position);
intent.putExtras(bundle);
//intent.setClass(getApplicationContext(), ImageGallery_ViewPager_from_GambaPanas.class);//trying out
intent.setClass(getApplicationContext(), ImageGallery.class);//works without Panigation
startActivity(intent);
}
});
return ;
}
// Append more data into the adapter
public void customLoadMoreDataFromApi(int offset) {
// This method probably sends out a network request and appends new data items to your adapter.
// Use the offset value and add it as a parameter to your API request to retrieve paginated data.
// Deserialize API response and then construct new objects to append to the adapter
mPageNumberInt = 2;
//Call get new date
//gridview.setAdapter(adapter = new AlbumPhotosAdapter());
adapter.notifyDataSetChanged();
gridview.setAdapter(adapter);
}
//New Adapter
public class AlbumPhotosAdapter extends BaseAdapter {
List<AlbumPhotosDataStruct> list = new ArrayList<AlbumPhotosDataStruct>();
public AlbumPhotosAdapter() {
/** call server retrieve photos by album id **/
GetBigImageUrl();
getPhotosList();
Collections.reverse(list);
}
public int getCount() {
return list.size();
}
public AlbumPhotosDataStruct getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
v = getLayoutInflater().inflate(R.layout.photo_grid_item, parent, false);
} else {
v = (View) convertView;
}
AlbumPhotosDataStruct z = getItem(position);
String thumb_url = z.thumb_url;
ImageView imgView =(ImageView) v.findViewById(R.id.img_photo);
imageLoader.DisplayImage(thumb_url, imgView, true);
return v;
}
protected void getPhotosList(){
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void...params) {
if (isCancelled())
return "";
String result = "";
APICall api = new APICall(MyApplication.getAppContext());
Log.i("getPhotosList *******************", "mPageNumber : " + mPageNumber);
api.setAPIurl(getString(R.string.api_url));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("c", "getlist"));
nameValuePairs.add(new BasicNameValuePair("category", mGetAlbumCategory));
nameValuePairs.add(new BasicNameValuePair("page", mPageNumber));
nameValuePairs.add(new BasicNameValuePair("limit", mItemLimit));
result = api.getAPIContents(nameValuePairs);
return result;
}
@Override
protected void onPostExecute(String result) {
//Log.d("toppaidTest","processing2");
if (!result.equals("")) {
try {
JSONObject jObject = new JSONObject(result);
String status = jObject.getString("status");
if (status.equals("success")) {
// Log.e("status",status);
JSONArray jArray_data = new JSONArray(jObject.getString("data"));
//loop album Thumb
if(jArray_data.length() > 0){
for (int i = 0; i<jArray_data.length(); i++) {
//String thumb_url = jArray_data.getJSONObject(i).getString("link").toString();
String thumb_url = jArray_data.getString(i);
Log.v("Loop thumb_url", "thumb_url: " + thumb_url);
AlbumPhotosDataStruct newData = new AlbumPhotosDataStruct(thumb_url);
list.add(newData);
//stringArrayList.add(thumb_url); //add to arraylist
stringArrayList_thumb.add(thumb_url);
}
Log.i("After loop - stringArrayList_thumb", "stringArrayList_thumb: " + stringArrayList_thumb);
}
}
else{
//show default album
showDefaultPhoto();
}
} catch (JSONException e) {
e.printStackTrace();
//show default album
showDefaultPhoto();
}
}
else{
//show default album
showDefaultPhoto();
}
//dialog.dismiss();
notifyDataSetChanged();
}
}.execute();
}
//---- Get Actual Image ******************************************************************************************
protected void GetBigImageUrl(){
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void...params) {
if (isCancelled())
return "";
String result = "";
APICall api = new APICall(MyApplication.getAppContext());
api.setAPIurl(getString(R.string.api_url));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("c", "getimages"));
nameValuePairs.add(new BasicNameValuePair("category", mGetAlbumCategory));
nameValuePairs.add(new BasicNameValuePair("page", mPageNumber));
nameValuePairs.add(new BasicNameValuePair("limit", mItemLimit));
result = api.getAPIContents(nameValuePairs);
return result;
}
@Override
protected void onPostExecute(String result) {
//Log.d("toppaidTest","processing2");
if (!result.equals("")) {
try {
mJsonobject = new JSONObject(result);
String status = mJsonobject.getString("status");
if (status.equals("success")) {
// Log.e("status",status);
mJsonarray = new JSONArray(mJsonobject.getString("data"));
//loop API 2 Full Image
if(mJsonarray.length() > 0){
for (int i = 0; i<mJsonarray.length(); i++) {
String url_title = mJsonarray.getJSONObject(i).getString("title").toString();
String actual_url = mJsonarray.getJSONObject(i).getString("link").toString();
//AlbumPhotosDataStruct newData = new AlbumPhotosDataStruct(url_title, actual_url);
//list.add(newData);
stringArrayListTitle.add(url_title); //add to arraylistTitle
stringArrayList.add(actual_url); //add to arraylist
}
Log.v("After loop - stringArrayList", "stringArrayList: " + stringArrayList);
Log.v("After loop - stringArrayListTitle", "stringArrayListTitle: " + stringArrayListTitle);
}
}
else{
//show default album
//showDefaultPhoto();
}
} catch (JSONException e) {
e.printStackTrace();
//show default album
//showDefaultPhoto();
}
}
else{
//show default album
//showDefaultPhoto();
}
//dialog.dismiss();
//notifyDataSetChanged();
}
}.execute();
}
//--------------------------------------------------------------------end get actual image
private void showDefaultPhoto(){
Log.e("showDefaultPhoto", "show default photo");
}
public class AlbumPhotosDataStruct {
public String thumb_url;
public AlbumPhotosDataStruct(String thumb_url) {
this.thumb_url = thumb_url;
}
}
}
//end new adaptor
@Override
public void onPause() {
super.onPause();
Log.e("onPause","leavenow: " + adapter.getCount());
}
//-------------------------------------------------------------------------------------------------------------------------------
public abstract class EndlessScrollListener implements OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// 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 = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
public EndlessScrollListener(int visibleThreshold, int startPage) {
this.visibleThreshold = visibleThreshold;
this.startingPageIndex = startPage;
this.currentPage = startPage;
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
@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 && (totalItemCount - visibleItemCount)<=(firstVisibleItem + visibleThreshold)) {
onLoadMore(currentPage + 1, totalItemCount);
loading = true;
}
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount);
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// Don't take any action on changed
}
}
//-------------------------------------------------------------------------------------------------------------------------------------
}//------body
答案 0 :(得分:0)
在customLoadMoreDataFromApi()方法中,您已经说过“可能发出网络请求并附加新数据项”,因此应该异步完成。所以你应该在异步任务完成后调用adapter.notifyDataSetChanged()。验证它,并且不要重新初始化适配器只需将项添加到列表并调用adapter.notifyDataSetChanged()。同时保留您的图像列表(列表列表)作为“GalleryInGridViewCallfromAPI”类的全局变量。并将其对“AlbumPhotosAdapter”类的引用作为constructer参数传递,否则调用adapter.notifyDataSetChanged()时没有意义。
我的意思是下面的内容
public class GalleryInGridViewCallfromAPI extends Activity {
List<AlbumPhotosDataStruct> list;
public void onCreate(Bundle savedInstanceState) {
list = new ArrayList<AlbumPhotosDataStruct>();
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter = new AlbumPhotosAdapter());
}
public void customLoadMoreDataFromApi(int offset) {
mPageNumberInt = 2;
/*in here call async task and get image from server as list and update global list like below*/
/*and following should be in asyn task completed function*/
list.addAll(retrivedNewList);
/*and then call notifyDataSetChanged*/
adapter.notifyDataSetChanged();
}
...
public class AlbumPhotosAdapter extends BaseAdapter {
List<AlbumPhotosDataStruct> imageList;
public AlbumPhotosAdapter(List<AlbumPhotosDataStruct> imageList) {
this.imageList = imageList;
/** use this locale image list i.e imageList withing this adapter **/
GetBigImageUrl();
getPhotosList();
Collections.reverse(imageList);
}
...
}
}