Updating the GridView inside the ViewPager using the PagerAdapter - android

I have used GridView inside the ViewPager, and when I try to update the GridView using the gridViewAdapter.notifydatasetchanged(), it doesn't updates. But when I scroll through all the pages and comes back to the original page, it shows the updated view. Im cluless, please help me someone how to deal with this.
I don't want to use the viewPager.notifydatsetchanged() as it reloads all the page items.
public class ViewPagerAdapter extends PagerAdapter {
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "FTICKERS";
case 1:
return "QUOTES";
case 2:
return "MEMES";
case 3:
return "MOVIES";
}
return null;
}
Context activity;
public ViewPagerAdapter(Context act) {
activity = act;
}
public int getCount() {
return 4;
}
#Override
public int getItemPosition(Object object) {
//return super.getItemPosition(object);
return POSITION_NONE;
}
public Object instantiateItem(View collection, final int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Context context = cont;
view0 = inflater.inflate(R.layout.fragment_f, null);
//send=view0;
gridview0 = (GridView) view0.findViewById(R.id.gridview_stickers_f);
imageAdapter0 = new ImageAdapter(context,"fticker");
gridview0.setAdapter(imageAdapter0);
view1 = inflater.inflate(R.layout.fragment_quotes, null);
//send=view0;
gridview1 = (GridView) view1.findViewById(R.id.gridview_stickers_quotes);
imageAdapter1 = new ImageAdapter(context,"quotes");
gridview1.setAdapter(imageAdapter1);
view2 = inflater.inflate(R.layout.fragment_memes, null);
//send=view0;
gridview2 = (GridView) view2.findViewById(R.id.gridview_stickers_memes);
imageAdapter2 = new ImageAdapter(context,"memes");
gridview2.setAdapter(imageAdapter2);
view3 = inflater.inflate(R.layout.fragment_movies, null);
//send=view0;
gridview3 = (GridView) view3.findViewById(R.id.gridview_stickers_movies);
imageAdapter3 = new ImageAdapter(context,"movies");
gridview3.setAdapter(imageAdapter3);
if(position==0)
{
send=view0;
folder="fticker";
Log.e("Folder Name is::",folder);
urlSet = new HashSet<String>();
imgUri = new HashSet<Uri>();
imgName = new HashSet<String>();
display = dialog.getWindow().getWindowManager().getDefaultDisplay();
metrics = new DisplayMetrics();
if(instFlag0==0) {
addDatatoAdapter(pg, null, "fticker");
instFlag0=1;
//Toast.makeText(cont,"Hola", Toast.LENGTH_SHORT).show();
}
gridview0.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
private LinearLayout lBelow;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
/** To do code here*/
//Toast.makeText(cont, "Scrolled down", Toast.LENGTH_SHORT).show();
Toast.makeText(cont, "0", Toast.LENGTH_SHORT).show();
pg++;
addDatatoAdapter(pg, null, "fticker");
//viewPagerAdapter.notifyDataSetChanged();
}
}
});
gridview0.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
ChatWidgetService.onShare(imageAdapter0.getUri(position));
}
});
gridview0.setTag(0);
((ViewPager) collection).addView(view0, 0);
return view0;
}

Related

android - PageAdapter's addView method raises exception "The specified child already has a parent."

I have a Custom PageAdapter that is dynamic and lets you add and remove views. I found the code from this answer.
MainPagerAdapter
public class MainPagerAdapter extends PagerAdapter {
private ArrayList<View> views = new ArrayList<View>();
#Override
public int getItemPosition(Object object) {
int index = views.indexOf(object);
if (index == -1)
return POSITION_NONE;
else
return index;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View v = views.get(position);
container.addView(v);
return v;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(views.get(position));
}
#Override
public int getCount() {
return views.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public int addView(View v) {
return addView(v, views.size());
}
public int addView(View v, int position) {
views.add(position, v);
return position;
}
public int removeView(ViewPager pager, View v) {
for (int i = 0; i < views.size(); i++) {
if (views.get(i).getTag().equals(v.getTag()))
return removeView(pager, i);
}
return -1;
}
public int removeView(ViewPager pager, int position) {
pager.setAdapter(null);
views.remove(position);
pager.setAdapter(this);
return position;
}
public View getView(int position) {
return views.get(position);
}
}
Basically I have the PopupHandlerclass which calls showDialog once, for the first alert, and after that it calls AddView to add more pages, and removeView to remove a page.
Every time the PopupHandler gets an alert, it checks some conditions and either adds another view or remove an existing one.
The problem I have is : sometimes when pages are added and I slide between the pages, the app crashes, saying
The specified child already has a parent. You must call removeView()
on the child's parent first.
I cant say exactly when it happens, sometimes I am able to re-create the error, but the log shows the error is in this method, in the line container.addView(v);
#Override
public Object instantiateItem(ViewGroup container, int position) {
View v = views.get(position);
container.addView(v); // here is the crash
return v;
}
Also, here is the PopupHandler (class populating the ViewPager and adding views):
public class PopupHandler {
private Context context;
private boolean isPopUpShowing;
private List<AlarmType> alarmTypeList;
private ViewPager pager = null;
private MainPagerAdapter pagerAdapter = null;
private View verticalLineSeperator;
private TextView alertNumber;
private AlertDialog alertDialog;
public PopupHandler(Context context) {
this.context = context;
...
}
public void handleAlert(IAlarmInfo alarmInfo) {
// checking some conidtions
if (newAlarm) {
alarmTypeList.add(alarmInfo.getAlarmType());
if (...) {
// first time creating dialog and adding view
showDiaog(alarmInfo.getTitle(), alarmInfo.getSummary(), alarmInfo.getAlarmIconResource(), alarmInfo.getAlarmType());
isPopUpShowing = true;
} else {
// adding view
View v = setUpView(alarmInfo.getTitle(), alarmInfo.getSummary(), alarmInfo.getAlarmIconResource(), alarmInfo.getAlarmType());
addView(v);
}
} else {
if (alarmTypeList.contains(alarmInfo.getAlarmType())) {
//remove view
alarmTypeList.remove(alarmInfo.getAlarmType());
View v = setUpView(alarmInfo.getTitle(), alarmInfo.getSummary(), alarmInfo.getAlarmIconResource(), alarmInfo.getAlarmType());
removeView(v);
if (alarmTypeList.size() == 0 && alertDialog.isShowing()) {
// if list empty dismiss dialog
alertDialog.dismiss();
isPopUpShowing = false;
}
}
}
}
private void showDiaog(final String title, final String summary, final int icon, AlarmType alarmType) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(context, R.style.myDialog));
dialogBuilder.setCancelable(false);
LayoutInflater inflater = LayoutInflater.from(context);
View dialogView = inflater.inflate(R.layout.popups_container, null);
ButterKnife.bind(this, dialogView);
pager = (ViewPager) dialogView.findViewById(R.id.popup_view_pager);
pager.setAdapter(pagerAdapter);
pager.setOffscreenPageLimit(5);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.i("testing", "onPageSelected " + position);
alertNumber.setText((position + 1) + " of " + pagerAdapter.getCount());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
alertNumber = (TextView) dialogView.findViewById(R.id.popup_alert_number);
alertNumber.setText((alarmTypeList.indexOf(alarmType) + 1) + " of " + alarmTypeList.size());
verticalLineSeperator = dialogView.findViewById(R.id.popup_vertical_seperator);
verticalLineSeperator.setBackgroundColor(alertNumber.getTextColors().getDefaultColor());
View v = setUpView(title, summary, icon, alarmType);
pagerAdapter.addView(v, 0);
pagerAdapter.notifyDataSetChanged();
dialogBuilder.setView(dialogView);
alertDialog = dialogBuilder.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
private View setUpView(String title, String summary, int icon, AlarmType alarmType) {
View v1 = LayoutInflater.from(context).inflate(R.layout.popup, null);
TextView titleText = (TextView) v1.findViewById(R.id.popup_title);
TextView summaryText = (TextView) v1.findViewById(R.id.popup_summary);
ImageView iconText = (ImageView) v1.findViewById(R.id.popup_alert_icon);
titleText.setText(title);
summaryText.setText(summary);
iconText.setImageResource(icon);
v1.setTag(alarmType);
return v1;
}
public void addView(View newPage) {
int pageIndex = pagerAdapter.addView(newPage);
pagerAdapter.notifyDataSetChanged();
pager.setCurrentItem(pageIndex, true);
}
public void removeView(View defunctPage) {
int pageIndex = pagerAdapter.removeView(pager, defunctPage);
// You might want to choose what page to display, if the current page was "defunctPage".
if (pageIndex == -1)
return;
if (pageIndex == pagerAdapter.getCount())
pageIndex--;
pager.setCurrentItem(pageIndex);
alertNumber.setText((pageIndex + 1) + " of " + alarmTypeList.size());
}
public View getCurrentPage() {
return pagerAdapter.getView(pager.getCurrentItem());
}
public void setCurrentPage(View pageToShow) {
pager.setCurrentItem(pagerAdapter.getItemPosition(pageToShow), true);
}
public void hidePopup() {
if (alertDialog != null)
if (alertDialog.isShowing()) {
alertDialog.dismiss();
alarmTypeList.clear();
}
}
}

i am getting image url from json and they are loading successfully in grid view but after then scroll previous image replace by below images

one problem in there after the scroll gridview previous image replace by below images and again scroll up its again load i want its load one time and never be change on scroll.my app url is https://play.google.com/store/apps/details?id=com.vaibhavtech.mbmovies
public class NewMovie extends Activity {
private GridView lv;
private Vibrator vibrator;
private ArrayList<DataDemo> mDemoDataAl;
private ProgressDialog progressDialog;
private String mStringURL = "";
private ImageLoader mImageLoader = null;
protected static final int SHOW_PROGRESS_DIALOG = 0;
protected static final int STOP_PROGRESS_DIALOG = 1;
protected static final int NETWORK_FAILURE = 2;
protected static final int PROBLEM_IN_CONNECTING_SERVER = 3;
protected static final int SET_ADAPTER = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.new_movie);
setProgressBarIndeterminateVisibility(true);
setProgressBarIndeterminateVisibility(false);
super.onCreate(savedInstanceState);
mDemoDataAl = new ArrayList<DataDemo>();
mImageLoader = ImageLoader.getInstance();
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
lv = (GridView) findViewById(R.id.grid_view);
mStringURL = "http://vaibhavtech.com/work/android/movie_list.php?category="
+ MainActivity.movie_Category + "&sub_category=new";
Log.d("The Url is ", " URL : " + mStringURL);
lv.setOnScrollListener(new EndlessScrollListener());
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// // TODO Auto-generated method stub
vibrator.vibrate(40);
MainActivity.movie_Id = ((TextView) arg1
.findViewById(R.id.tv_girdview_content_id)).getText()
.toString();
startActivity(new Intent(NewMovie.this, MovieDescription.class));
}
});
new GetDemoData().execute();
}
private class GetDemoData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
JSONObject json = JSONfunctions.getJSONfromURL(mStringURL,
NewMovie.this);
if (json != null) {
JSONArray MoviesArray = json.getJSONArray("Demo");
for (int i = 0; i < MoviesArray.length(); i++) {
DataDemo mDemoData = new DataDemo();
mDemoData.setmDemoId(MoviesArray.getJSONObject(i)
.getString("id"));
mDemoData.setmDemoTitle(MoviesArray.getJSONObject(i)
.getString("title"));
mDemoData.setmDemoYear(MoviesArray.getJSONObject(i)
.getString("year"));
mDemoData.setmDemoDuration(MoviesArray.getJSONObject(i)
.getString("duration"));
mDemoData.setmDemoPoster(MoviesArray.getJSONObject(i)
.getString("poster"));
mDemoDataAl.add(mDemoData);
}
} else {
mHandler.sendEmptyMessage(PROBLEM_IN_CONNECTING_SERVER);
}
} catch (Exception e) {
Log.d("Exceptions",
" The Xception messages are " + e.getMessage());
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);
mDemoDataAl.clear();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mHandler.sendEmptyMessage(SET_ADAPTER);
mHandler.sendEmptyMessage(STOP_PROGRESS_DIALOG);
}
}
public class NewMoviesAdapter extends BaseAdapter {
private LayoutInflater mInflater = null;
public NewMoviesAdapter() {
mInflater = LayoutInflater.from(NewMovie.this);
}
public int getCount() {
return mDemoDataAl.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_view_content,
null);
holder = new ViewHolder();
holder.txtMovieId = (TextView) convertView
.findViewById(R.id.tv_girdview_content_id);
holder.txtMovieDuration = (TextView) convertView
.findViewById(R.id.tv_girdview_content_listner);
holder.txtMovieName = (TextView) convertView
.findViewById(R.id.tv_girdview_content_name);
holder.txtMovieYear = (TextView) convertView
.findViewById(R.id.tv_girdview_content_like);
holder.imgMovie = (ImageView) convertView
.findViewById(R.id.iv_girdview_content_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.txtMovieId.setText(Utils
.asUpperCaseFirstChar(mDemoDataAl.get(position)
.getmDemoId()));
holder.txtMovieDuration.setText(mDemoDataAl.get(position)
.getmDemoDuration());
holder.txtMovieName.setText(Utils
.asUpperCaseFirstChar(mDemoDataAl.get(position)
.getmDemoTitle()));
holder.txtMovieYear.setText(mDemoDataAl.get(position)
.getmDemoYear());
mImageLoader.displayImage(
"http://vaibhavtech.com/work/android/admin/upload/"
+ mDemoDataAl.get(position).getmDemoPoster(),
holder.imgMovie);
} catch (Exception e) {
}
return convertView;
}
class ViewHolder {
public TextView txtMovieId;
public TextView txtMovieDuration;
public TextView txtMovieName;
public TextView txtMovieYear;
public ImageView imgMovie;
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 5;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
// new do.execute(currentPage + 1);
loading = true;
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SHOW_PROGRESS_DIALOG:
if (progressDialog == null) {
progressDialog = Utils.createProgressDialog(NewMovie.this);
progressDialog.setMessage("Loding...");
progressDialog.show();
} else {
progressDialog.show();
}
mHandler.removeMessages(SHOW_PROGRESS_DIALOG);
break;
case STOP_PROGRESS_DIALOG:
progressDialog.dismiss();
mHandler.removeMessages(STOP_PROGRESS_DIALOG);
break;
case NETWORK_FAILURE:
Utils.displayToast(NewMovie.this,
Constant.NO_NETWORK_CONNECTION);
mHandler.removeMessages(NETWORK_FAILURE);
break;
case PROBLEM_IN_CONNECTING_SERVER:
Utils.displayToast(NewMovie.this,
Constant.PROBLEM_IN_CONNECTING_SERVER);
mHandler.removeMessages(PROBLEM_IN_CONNECTING_SERVER);
break;
case SET_ADAPTER:
lv.setAdapter(new NewMoviesAdapter());
mHandler.removeMessages(SET_ADAPTER);
break;
default:
break;
}
};
};
}
newmovie.xml**************************
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:orientation="vertical" >
<GridView
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="377dp"
android:horizontalSpacing="10dp"
android:numColumns="2"
android:verticalSpacing="10dp" >
</GridView>
</LinearLayout>
mainactivity.java
public class MyApplication extends Application {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
It should help you: Universal Image Loader for Android. I was tried it and I can say that it's simple and practical.

How to put n intent on a gridview to lauch another activity in android?

I doing a grid view for my android layout but I don't know how to put an intent on the grid view. is there any way where I can put an intent to launch another activity? I been trying for few days already but i cant seem to figure out how to do it.
public class PregnancyStages extends Activity implements OnItemClickListener {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private ImageAdapter imageAdapter;
// Some items to add to the GRID
private static final String[] CONTENT = new String[] { "Pregnancy Stages", "Complications", "Diet And Fitness", "Myths And Facts",
"FAQ's", "Helplines" };
private static final int[] ICONS = new int[] { R.drawable.baby1, R.drawable.baby2,
R.drawable.baby3, R.drawable.baby4, R.drawable.baby5, R.drawable.baby6 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get the photo size and spacing
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing = getResources().getDimensionPixelSize(R.dimen.photo_spacing);
// initialize image adapter
imageAdapter = new ImageAdapter();
photoGrid = (GridView) findViewById(R.id.albumGrid);
// set image adapter to the GridView
photoGrid.setAdapter(imageAdapter);
// get the view tree observer of the grid and set the height and numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(photoGrid.getWidth() / (mPhotoSize + mPhotoSpacing));
if (numColumns > 0) {
final int columnWidth = (photoGrid.getWidth() / numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
}
// ///////// ImageAdapter class /////////////////
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mItemHeight = 0;
private int mNumColumns = 0;
private RelativeLayout.LayoutParams mImageViewLayoutParams;
public ImageAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
}
public int getCount() {
return CONTENT.length;
}
// set numcols
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
// set photo item height
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
notifyDataSetChanged();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
if (view == null)
view = mInflater.inflate(R.layout.photo_item, null);
ImageView cover = (ImageView) view.findViewById(R.id.cover);
TextView title = (TextView) view.findViewById(R.id.title);
cover.setLayoutParams(mImageViewLayoutParams);
// Check the height matches our calculated column width
if (cover.getLayoutParams().height != mItemHeight) {
cover.setLayoutParams(mImageViewLayoutParams);
}
cover.setImageResource(ICONS[position % ICONS.length]);
title.setText(CONTENT[position % CONTENT.length]);
return view;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
Intent myIntent = null;
if(position == 0){
myIntent = new Intent(v.getContext(), PregnancyStagesGrid1.class);
}
if(position == 1){
myIntent = new Intent(v.getContext(), PregnancyStagesGrid2.class);
}
startActivity(myIntent);
}}
anyone know where can i put this source code?
GridView gridview = (GridView) findViewById (R.id.albumGrid);
gridview.setAdapter (new ImageAdapter());
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
Intent myIntent = null;
if(position == 0){
myIntent = new Intent(v.getContext(), PregnancyStagesGrid1.class);
}
if(position == 1){
myIntent = new Intent(v.getContext(), PregnancyStagesGrid2.class);
}
startActivity(myIntent);
}
});
}
You forgot to add setOnItemClickListener listner
photoGrid.setOnItemClickListener(this);

ListView does not render all items until interacted with

I have a very strange problem while using my ListView.
Only a part of my adapter items are renderd in the listview on screen but when I interact with the listview (ie tries to scroll it) all items are renderd properly.
This fenonemon only occurs if i have less items than the screen can show. Take a look at these screenshots below.
Before interaction:
After interaction:
Source code of activity where adding items:
String[] jRests = getResources().getStringArray(R.array.j_restaurants);
String[] lRests = getResources().getStringArray(R.array.l_restaurants);
items = new ArrayList<Object>();
items.add(getString(R.string.campus_j));
for(String item : jRests){
String[] val = item.split(",,,");
items.add(new FoodSectionListItem(new Restaurant(val[0], val[1], val[2], "")));
}
items.add(getString(R.string.campus_l));
for(String item : lRests){
String[] val = item.split(",,,");
items.add(new FoodSectionListItem(new Restaurant(val[0], val[1], val[2], "")));
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
adapter = new BaseSectionAdapter(this, R.layout.list_item_fragment_header);
if(!isTabletView()){
adapter.setSelectedItem(-1);
}
adapter.setItems(items);
Code of adapter:
public class BaseSectionAdapter extends AmazingAdapter {
private LayoutInflater inflater;
private int selectedItem = 0;
private List<Object> items;
private List<SectionItem> sections = new ArrayList<SectionItem>(10);
private List<Class> itemTypes = new ArrayList<Class>();
private List<Integer> sectionPositions = new ArrayList<Integer>();
private int listHeaderLayoutId;
private View headerView;
public static interface ISectionListItem {
public void setProps(View convertView, int position, int selectedItem);
public View getLayout(LayoutInflater inflater);
}
private class SectionItem implements Serializable {
private static final long serialVersionUID = -8930010937740160935L;
String text;
int position;
public SectionItem(String text, int position) {
this.text = text;
this.position = position;
}
}
public BaseSectionAdapter(Context context, int listHeaderLayoutId) {
this.listHeaderLayoutId = listHeaderLayoutId;
init(context);
}
public BaseSectionAdapter(Context context, int listHeaderLayoutId, List<Object> listItems) {
this.listHeaderLayoutId = listHeaderLayoutId;
init(context);
initListItems(listItems);
}
private void init(Context context) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setSelectedItem(int position) {
selectedItem = position;
}
// public List<ListItem> getItems() {
// return items;
// }
private void initListItems(List<Object> itemList) {
int curSection = -1;
//int curPosition = 0;
//curSection = 0;
this.items = itemList;
itemTypes.clear();
sections.clear();
sectionPositions.clear();
int listSize = itemList.size();
for(int i = 0; i < listSize; i++){
Object currentItem = items.get(i);
if(currentItem instanceof String){
sections.add(new SectionItem((String) currentItem,i));
curSection++;
}
if(!itemTypes.contains(currentItem.getClass())){
itemTypes.add(currentItem.getClass());
}
sectionPositions.add(curSection);
}
Log.d("test", "No of items = "+items.size());
Log.d("test", "No of itemtypes = "+itemTypes.size());
Log.d("test", "View type count = "+getViewTypeCount());
}
public void setItems(List<Object> itemList) {
initListItems(itemList);
}
public int getCount() {
return items==null?0:items.size();
}
#Override
public int getViewTypeCount(){
return (itemTypes.size() == 0)?1:itemTypes.size();
}
#Override
public int getItemViewType(int position){
return itemTypes.indexOf(items.get(position).getClass());
}
#Override
public boolean isEnabled(int position){
return !(items.get(position) instanceof String || items.get(position) instanceof EmptySectionListItem);
}
#Override
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
// TODO Auto-generated method stub
}
#Override
protected void bindSectionHeader(View view, int position,
boolean displaySectionHeader) {
// TextView lSectionTitle = (TextView) view
// .findViewById(R.id.txt_list_header);
// if (displaySectionHeader) {
// lSectionTitle.setVisibility(View.VISIBLE);
// lSectionTitle
// .setText(getSections()[getSectionForPosition(position)]);
// } else {
// lSectionTitle.setVisibility(View.GONE);
// }
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
Object curItemObject = items.get(position);
boolean isHeader = (curItemObject instanceof String);
if(convertView == null){
if(isHeader && headerView != null){
convertView = headerView;
}else if(isHeader){
convertView = inflater.inflate(listHeaderLayoutId, null);
headerView = convertView;
}else{
convertView = ((ISectionListItem) curItemObject).getLayout(inflater);
}
}
if(isHeader){
TextView header = ((TextView)convertView.findViewById(R.id.txt_list_header));
header.setText((String)curItemObject);
}else{
((ISectionListItem)curItemObject).setProps(convertView, position, selectedItem);
}
return convertView;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
TextView textView = ((TextView)header.findViewById(R.id.txt_list_header));
textView.setText(getSections()[getSectionForPosition(position)]);
}
#Override
public int getPositionForSection(int section) {
if(section >= sections.size()){
return 0;
}
return sections.get(section).position;
}
#Override
public int getSectionForPosition(int position) {
return sectionPositions.get(position);
}
#Override
public String[] getSections() {
String[] res = new String[sections.size()];
for (int i = 0; i < res.length; i++) {
res[i] = sections.get(i).text;
}
return res;
}
}
Code of layout:
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
FrameLayout listLayout = new FrameLayout(this);
LinearLayout.LayoutParams listParams = new LinearLayout.LayoutParams(0, FrameLayout.LayoutParams.MATCH_PARENT);
listParams.weight = 1;
listLayout.setId(LIST_FRAGMENT_VIEW_ID);
FrameLayout detailLayout = new FrameLayout(this);
LinearLayout.LayoutParams detailParams = new LinearLayout.LayoutParams(0, FrameLayout.LayoutParams.MATCH_PARENT);
detailParams.weight = 2;
detailLayout.setId(DETAIL_FRAGMENT_VIEW_ID);
layout.addView(listLayout, listParams);
layout.addView(detailLayout, detailParams);
if(savedInstanceState == null){
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(listLayout.getId(), (Fragment) listFragment, TWO_PANEL_LIST_FRAGMENT_TAG);
ft.add(detailLayout.getId(), detailFragment);
ft.commit();
}
setContentView(layout);
try calling notifyDataSetChanged() in runOnUIThread() method like I have shown below and it will work like a charm. :)
runOnUiThread(new Runnable() {
#Override
public void run() {
messageAdapter.notifyDataSetChanged();
}
});
i dont know what causes the problem, but if you don't find a logical solution to it you could try something like this:
trigger an onTouchEvent() programmatically whenever you launch the ListView.
scroll down and back up programmatically as soon as the ListView is launched.
etc..
Add ListView widget to layout.xml and add content of list to that. Do not use FrameLayout as it probably is the cause of the problem. It is updating content after touch so the Layout it is on is no implementing the correct onCreate() setup as the ListView widget has.
Are you calling the method notifyDataSetChanged() on your adapter after adding new items? This causes the listview to refresh its view when the underlying dataset is changed.
If it still doesn't work, try notifyDataSetInvalidated() that causes the listview to redraw completely.
Solved it!!!
Problem was with the adapter trying to reuse the same section item. Not good!!!
Changed it to inflate the section item each time we hit a section!

Display images in grid view of View pager

I am working on image gallery for which i have made use of ViewPager addon api. I am loading images from a specific folder in sdcard. My goal is to display only 9 images per screen in ViewPager, which i am not able to achieve. The below code is the mainactivity.
public class AndroidSwipeGalleryActivity extends Activity {
private int size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.image_gallery);
File file = new File(Environment.getExternalStorageDirectory()+"/xxxxxxx/images");
if (file.exists()) {
size = file.listFiles().length;
System.out.println("=====File exists====Length is====="+size);
double quo = (double)size/9;
System.out.println("====Dividing by 9====" + quo);
size = (int) Math.ceil(quo);
System.out.println("===Math===== "+size);
} else {
System.out.println("======File does not exists====");
}
MyPagerAdapter adapter = new MyPagerAdapter(this);
adapter.setScrCount(size);
ViewPager myPager = (ViewPager) findViewById(R.id.viewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
}
The Pager Adapter and Image adapter are in the below class:
public class MyPagerAdapter extends PagerAdapter {
private TextView tv;
private GridView gv;
private int scrCount;
private int count;
public int imageCount;
private Cursor cursor;
private int columnIndex;
private Activity act;
public MyPagerAdapter(Activity act) {
this.act = act;
}
public int getCount() {
return getScrCount();
}
public Object instantiateItem(View collection, int position) {
// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Create the cursor pointing to the SDCard
String uri = MediaStore.Images.Media.DATA;
String condition = uri + " like '%/beverlyhills/images%'";
cursor = act.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, condition, null, null);
count = cursor.getCount();
System.out.println("Cursor count::::"+count);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
for (int i = 0; i < getScrCount() ; i++) {
if (count > 9) {
if (position == i) {
int num = 0;
num = count - 9;
count = num;
imageCount = 9;
}
} else {
imageCount = count;
}
}
resId = R.layout.number_one;
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
tv = (TextView) collection.findViewById(R.id.swipeTitleTextView);
tv.setText("Swipe Gallery");
gv = (GridView) collection.findViewById(R.id.galleryGridView);
ImageAdapter imageAdapter = new ImageAdapter(collection.getContext(), imageCount);
gv.setAdapter(imageAdapter);
// Set up a click listener
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(#SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
// Get the data location of the image
String[] projection = {MediaStore.Images.Media.DATA};
cursor = act.managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
// Get image filename
String imagePath = cursor.getString(columnIndex);
// Use this path to do further processing, i.e. full screen display
System.out.println("=====Image Path:::::"+imagePath);
}
});
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub
}
#Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub
}
public int getScrCount() {
return scrCount;
}
public void setScrCount(int scrCount) {
this.scrCount = scrCount;
}
private class ImageAdapter extends BaseAdapter {
private int count;
public ImageAdapter(Context ctx, int count) {
this.count = count;
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(act);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
}
The problem is I am able to load the images and display them on screen but not able to display exactly 9 images per screen. Please go through the code, it's not complex.
i have create the other demo example of view pager to manage the page and also load images. follow the steps wise, its perfectly works..
its a Pager adapter and mDataHolder(List of images) and
Set the property of gridview android:numColumns="3"
private int size;
private int start;
private int end;
private int MATRIX = 9;
public int getCount() {
int size = 0;
if (mDataHolder != null)
modular = mDataHolder.get_Listholder().size() % MATRIX;
if (modular != 0)
size++;
return ((mDataHolder.get_Listholder().size()) / MATRIX) + size;
}
#Override
public Object instantiateItem(ViewGroup container, final int pageIndex) {
mRelativeLayoutInflater = (RelativeLayout) mMasterFragmentActivity.getLayoutInflater().inflate(R.layout.member_pager_adapter, container, false);
mGridView = (GridView) mRelativeLayoutInflater.findViewById(R.id.member_gridView_list);
Calculation of pages<
size = MATRIX;
start = pageIndex * MATRIX;
end = 0;
int temp = 0;
if ((start + MATRIX) < mDataHolder.get_Listholder().size()) {
end = start + MATRIX;
} else {
temp = mDataHolder.get_Listholder().size() - start;
end = start + temp;
size = temp;
}
... and then pass the variable to gridview adapter to set other content in pager.
mAdapterMember = new AdapterMember(mContext, start, end, size);
mGridView.setAdapter(mAdapterMember);
((ViewPager) container).addView(mRelativeLayoutInflater);
return mRelativeLayoutInflater;
}
Below Manage pages variables also use the Gridview adapter to set the postion.
when the set page content position to be like (start + position)
private class AdapterMember extends BaseAdapter {
private ViewHolder mViewHolder;
private Context mContext;
private int start;
private int end;
private int size;
private AdapterMember(Context mContext, int start, int end, int size) {
this.mContext = mContext;
this.start = start;
this.end = end;
this.size = size;
}
#Override
public int getCount() {
if (size > 0)
return size;
else
return 0;
}
#Override
public Object getItem(int position) {
if (mMemberListVO.getMember().size() > 0)
return mMemberListVO.getMember().get(position);
else
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((Activity) mContext).getLayoutInflater().inflate(R.layout.row_member_list, null);
mViewHolder = new ViewHolder();
mViewHolder.mImageViewMemberPhoto = (NetworkImageView) convertView .findViewById(R.id.row_member_list_imageView_person);
mViewHolder.mTextViewMemberName = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_name);
mViewHolder.mTextViewMemberDesignation = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_designation);
mViewHolder.mTextViewMemberAddress = (TextView) convertView .findViewById(R.id.row_member_list_textview_person_address);
mViewHolder.mTextViewMemberNotification = (TextView) convertView .findViewById(R.id.row_member_list_imageview_msg_notification);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
mViewHolder.mTextViewMemberName.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_First_Name)
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder(). get(start + position).get(DBHelper.mFieldMember_Last_Name));
mViewHolder.mTextViewMemberDesignation.setText(mDataHolder.get_Listholder().get(start + position)
.get(DBHelper.mFieldMember_Occupation));
mViewHolder.mTextViewMemberAddress.setText(mDataHolder.get_Listholder().get(start + position) .get(DBHelper.mFieldMember_Block_No)
+ "," + getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_House_No) + ","
+ getString(R.string.double_quate_with_space)
+ mDataHolder.get_Listholder().get(start + position).get(DBHelper.mFieldMember_Home_Address) + ".");
return convertView;
}
private class ViewHolder {
private NetworkImageView mImageViewMemberPhoto;
private TextView mTextViewMemberName, mTextViewMemberDesignation, mTextViewMemberAddress,
mTextViewMemberNotification;
}
}
its perfectly Working with your requirement...
The problem is solve to load the images and display them on screen its display exactly 9 images per screen.

Categories

Resources