GridView item position changing position dynamically while scrolling - android

I am using gridview layout for displaying multiple item and items are displaying fine, if I check on the big screen then all work done is fine because no scrolling is required.
But if I user small screen while scrolling it changing position dynamically.
** Example:**
If I display 50 items it working fine if I display 1000 items I need to scroll down, on that time selected items are changing their positions dynamically.
Adapter Code
public class EM_event_total_userseatsAdapter extends ArrayAdapter<EM_event_total_UserSeatsModel> implements View.OnClickListener {
ArrayList<EM_event_total_UserSeatsModel> dataSet;
public ArrayList<Integer> EMeventuserseatslist = new ArrayList<Integer>();
Context mContext;
ViewHolder holder;
String user_seats;
private int[] tagCollection;
private String[] mobileValues;
private String[] mobileValuesD;
private static class ViewHolder {
TextView TvEmUserSeats;
ImageView IvUsreSeats,available,selctedimag;
}
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();
SparseBooleanArray selectedItems;
public
EM_event_total_userseatsAdapter(ArrayList<EM_event_total_UserSeatsModel> data, Context context) {
super(context, R.layout.list_em_get_seats, data);
this.dataSet = data;
this.mContext=context;
selectedItems = new SparseBooleanArray();
}
public int getTagFromPosition(int position) {
return tagCollection[position];
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(tagCollection[position]);
EM_event_total_UserSeatsModel dataModel=(EM_event_total_UserSeatsModel)
object;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
EM_event_total_UserSeatsModel dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_em_get_seats, parent, false);
viewHolder.TvEmUserSeats = (TextView) convertView.findViewById(R.id.TvEmUserSeats);
viewHolder.IvUsreSeats = (ImageView) convertView.findViewById(R.id.IvUsreSeats);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
String blue_available = "seat3.png";
String red_booked = "seat1.png";
String get_seat = dataModel.getBookedStatus();
viewHolder.TvEmUserSeats.setText(dataModel.getSeatName());
//holder.imgSeatSelected.setVisibility(isSelected(position) ? View.VISIBLE : View.INVISIBLE);
if(Integer.parseInt(get_seat) == 1){
Picasso.with(mContext).load(main_url+"assets/admin/img/" + red_booked).into(viewHolder.IvUsreSeats);
}else
{
Picasso.with(mContext).load(main_url+"assets/admin/img/" + blue_available).into(viewHolder.IvUsreSeats);
}
return convertView;
}
public void toggleSelection(int position) {
if (selectedItems.get(position, false)) {
selectedItems.delete(position);
} else {
selectedItems.put(position, true);
}
notifyDataSetChanged();
}
public void clearSelections() {
selectedItems.clear();
notifyDataSetChanged();
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public String getSelectedItems() {
String items = "";
for (int i = 0; i < selectedItems.size(); i++) {
items += selectedItems.keyAt(i);
}
return items;
}
}

Related

android arraylist won't refresh on runnnig app

my app consist of a main activity with 3 fragments and I have an arraylist of boolean type in the second fragment of grid adapter to check the states of checkbox in every position so an action could be done in the first fragment.
the issue is that the arreylist never updates and it keeps the same data values
my code is below
public class GridAdapter extends BaseAdapter {
private ArrayList<GridWord> list;
private Context context;
private ArrayList<Boolean> checkBoxState;
public boolean status;
GridAdapter (Context context) {
this.context = context;
checkBoxState = new ArrayList<Boolean>();
for (int y = 0; y < 14; y++){
checkBoxState.add(y, false);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
class ViewHolder {
ImageView logoImage;
TextView textName;
CheckBox checkBox;
ViewHolder (View v){
logoImage = v.findViewById(R.id.grid_image);
textName = v.findViewById(R.id.grid_text);
checkBox = v.findViewById(R.id.grid_checbox);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.grid_item,parent,false);
holder = new ViewHolder(row);
row.setTag(holder);
}
else {
holder = (ViewHolder) row.getTag();
}
final GridWord temp = list.get(position);
holder.logoImage.setImageResource(temp.logo);
holder.textName.setText((CharSequence) temp.name);
final ViewHolder finalHolder = holder;
finalHolder.checkBox.setId(position);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
status = true;
if(((finalHolder.checkBox.isChecked()))) {
checkCheckBox(position, false);
finalHolder.checkBox.setChecked(checkBoxState.get(position));
}
else {
checkCheckBox(position, true);
finalHolder.checkBox.setChecked(checkBoxState.get(position));
}
}
});
finalHolder.checkBox.setChecked(checkBoxState.get(position));
return row;
}
public ArrayList<Boolean> getCheckBoxState(){
return checkBoxState;
}
public void checkCheckBox(int position, boolean value) {
if (value)
checkBoxState.set(position, true);
else
checkBoxState.set(position, false);
notifyDataSetChanged();
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isVisible = isVisibleToUser;
if (isVisible && isStarted) {
checkList.clear();
checkList = gridAdapter.getCheckBoxState();
for (int x = 0; x < checkList.size(); x++) {
if (checkList.get(x)) {
// some code
}
}
adapter.notifyDataSetChanged();
}
}
I would suggest you to have this arraylist in you activity holding this 3 fragments. Try updating this Arraylist from your Second fragment.
This way, whenever you want to read the values in First Fragment, you can read them from this global arraylist and hence so you have single instance of your arraylist.

ListView doesn't scroll smoothly when I add AdView as an item

I am implementing the Google Ads in my android app. Mostly I am interested in implementing the ads inside a ListView. For example every 10-th element I display an item containing the AdView. It will be only one Ad that it is displayed a various number of time. Below is my code. It works, the ads are displayed in the ListView, the app doesn't crash, but there is one small problem. When I scroll the list, the moment it comes to item displaying AdView, it seize for a bit, the scroll isn't so smoothly. I have tried the list without displaying ads and the scroll is fine.
NewsHomeAdapter(ArrayList<AdMobInterfaceList> items, Context context) {
this.items = items;
this.mContext = context;
// member variable
// iteron mbi objektet e bizneset dhe kontrollon cfare tipi eshte. Ne
// varesi te tipit theret adapterin e tij
for (AdMobInterfaceList item : items) {
if (item.getType() == 0) {
rows.add(new AdMobItemAdapter(LayoutInflater.from(mContext),
item, mContext));
}
if (item.getType() == 1) {
rows.add(new NewsItemAdapter(LayoutInflater.from(mContext),
item, mContext));
}
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public void updateNjoftimeList(ArrayList<AdMobInterfaceList> items) {
for (AdMobInterfaceList item : items) {
if (item.getType() == 0) {
rows.add(new AdMobItemAdapter(LayoutInflater.from(mContext),
item, mContext));
}
if (item.getType() == 1) {
rows.add(new NewsItemAdapter(LayoutInflater.from(mContext),
item, mContext));
}
}
this.notifyDataSetChanged();
}
public void updateNjoftimeFilterList(ArrayList<AdMobInterfaceList> items) {
//mNjoftime.clear();
//mNjoftime.addAll(newList);
rows.clear();
for (AdMobInterfaceList item : items) {
if (item.getType() == 0) {
rows.add(new AdMobItemAdapter(LayoutInflater.from(mContext),
item, mContext));
}
if (item.getType() == 1) {
rows.add(new NewsItemAdapter(LayoutInflater.from(mContext),
item, mContext));
}
}
this.notifyDataSetChanged();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
NewsItemAdapter.class
public class NewsItemAdapter implements ListsItemInterface {
final private AdMobInterfaceList item;
private LayoutInflater inflater;
private Context mContext;
public NewsItemAdapter(LayoutInflater inflater, AdMobInterfaceList item, Context context) {
this.item = item;
this.inflater = inflater;
this.mContext = context;
}
public View getView(View convertView) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.news_home_row, null);
holder = new ViewHolder();
holder.tittle = (TextView) convertView.findViewById(R.id.tittle);
holder.category = (TextView) convertView.findViewById(R.id.category);
holder.desc = (TextView) convertView.findViewById(R.id.desc);
holder.desc.setVisibility(View.GONE);
holder.published_time = (TextView) convertView.findViewById(R.id.published_time);
holder.news_image = (ImageView) convertView.findViewById(R.id.news_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Typeface typeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/Lato-Regular.ttf");
holder.tittle.setTypeface(typeFace);
holder.desc.setTypeface(typeFace);
holder.published_time.setTypeface(typeFace);
holder.category.setTypeface(typeFace);
holder.tittle.setText(((NewsItem) item).getTittle());
holder.desc.setText(((NewsItem) item).getDesc());
holder.published_time.setText(((NewsItem) item).getPublishedTimeString());
holder.category.setText(((NewsItem) item).getCategory());
//holder.news_image.getLayoutParams().width = 0;
if (!((NewsItem) item).getImageUrl().isEmpty()) {
UrlImageViewHelper.setUrlDrawable(holder.news_image, ((NewsItem) item).getImageUrl(), R.drawable.watermark_ikub);
} else {
holder.news_image.getLayoutParams().width = 0;
}
return convertView;
}
public int getViewType() {
return 1;
}
static class ViewHolder {
ImageView news_image=null;
TextView tittle;
TextView desc;
TextView published_time;
TextView category;
}
}
AdMobItemAdapter.class
public class AdMobItemAdapter implements ListsItemInterface {
final private AdMobInterfaceList item;
private LayoutInflater inflater;
private Context mContext;
public AdMobItemAdapter(LayoutInflater inflater, AdMobInterfaceList item, Context context) {
this.item = item;
this.inflater = inflater;
this.mContext = context;
}
public View getView(View convertView) {
ViewHolder holder;
//we have a don't have a converView so we'll have to create a new one
if (convertView == null) {
convertView = inflater.inflate(R.layout.add_mob_layout, null);
holder = new ViewHolder((AdView)convertView.findViewById(R.id.adView)) ;
convertView.setTag(holder);
} else {
//get the holder back out
holder = (ViewHolder)convertView.getTag();
}
holder.ad.setFocusable(false);
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("134BDAE1F7410A5CD779E89C5C8CBC20")
.build();
holder.ad.loadAd(((AdMobItem)item).getAdRequest());
return convertView;
}
public int getViewType() {
return 0;
}
public class ViewHolder {
public AdView ad;
public ViewHolder(AdView ad) {
this.ad = ad;
}
}
}
These is the code that I have used for the adapter of the ListView.I think the reason is that I load the ad for every item. But I don't know how to handle this. Any suggestions?

Android - Gridview, custom layout onclicklistener

I have a GridView with two TextViews inside it, When the GridView is populated, an OnClickListener is set which returns the position of the item that was selected. I want to trigger a method when one of the TextViews is selected.
Is this possible? If yes, how do I set this up?
EDIT 3:
Inside my activity whch populated the GridView: I retrieve a String-Array from my Strings.xml, a for loop examines each item inside the Array and searches for a condition based on the Item's name inside the SharedPreferences, this for loop is solely for counting how many "true" conditions there are, so it retrieves a int saved inside the count. Then a new String[] is created, this required an exact length to be given before items can be added to it, so I check count if it's more than 0, it will give the String[] a length of count and then another for loop will add each true to the String[] list that we just created. If count is 0 (no true conditions found in the first for loop) then only 1 Item is added to the String[] and is given the value "No Favourites Added".
Then you have the GridView's OnItemClickListener().
String s[] = getResources().getStringArray(R.array.FullList);
int count = 0;
for(int i = 0; i < s.length; i++) {
SharedPreferences sP = getActivity().getSharedPreferences("fav", MODE_PRIVATE);
Boolean b = sP.getBoolean(s[i], false);
if (b == true) {
count++;
}
}
String[] newList;
if (count > 0) {
newList = new String[count];
count = 0;
for(int i = 0; i < s.length; i++) {
SharedPreferences sP = getActivity().getSharedPreferences("fav", MODE_PRIVATE);
Boolean b = sP.getBoolean(s[i], false);
if (b == true) {
newList[count] = s[i];
count++;
}
}
} else {
newList = new String[1];
newList[0] = "No favourites added";
}
GridView FavGV = (GridView) getActivity().findViewById(R.id.sexp_fav);
FavGV.setAdapter(new Tab01_FavAdapter(getActivity(), newList));
FavGV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0,
View arg1, int position, long arg3) {
//Intent i = new Intent(getActivity(), PosPreview_Gestures.class);
//i.putExtra("position", position);
//startActivity(i);
}
});
So that's the code inside the Activity which populates the GridView. The Adapter in it's original, functioning form: This simply populates the GridView with Favourite Items (their names from the String[]) and adds a TextView with "Remove" which when pressed, shows a Toast: "Remove".
public class Tab01_FavAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflator;
String mEntries[];
public Tab01_FavAdapter (Context c, String[] entries) {
mContext = c;
mInflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mEntries = entries;
}
#Override
public int getCount() {
return mEntries.length;
}
#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) {
if(convertView == null) {
convertView = mInflator.inflate(R.layout.favitemlayout, parent, false);
}
TextView tx = (TextView) convertView.findViewById(R.id.favgridremoveitem);
OnClickListener oCL = new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext,"Remove",Toast.LENGTH_SHORT).show();
}
};
tx.setOnClickListener(oCL);
return convertView;
}
}
I am assuming that you are using a custom adapter for populating this GridView, and passing the Context as an argument to the constructor.
In the custom adapter, you should add onClickListeners to the TextViews. Using the context, you can call methods from your activity:
((CallingActivityName)context).methodYouWishToCall(parameters);
This would go inside the onClickListeners.
Edit: Added some code:
public class MyGridAdapter extends BaseAdapter {
private final List<MyObjectClass> mEntries;
private final LayoutInflater mInflater;
private final Context mContext;
public static class ViewHolder {
public TextView tx;
}
public MyGridAdapter(CallingActivityName context, List<MyObjectClass> entries) {
super();
mEntries = entries;
mContext = context;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mEntries.size();
}
#Override
public Object getItem(int position) {
return mEntries.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflator.inflate(R.layout.favitemlayout, parent, false);
holder = new ViewHolder();
holder.tx = (TextView) convertView
.findViewById(R.id.favgridremoveitem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final MyObjectClass info = mEntries.get(position);
holder.tx.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((CallingActivityName)mContext).favRemove(info);
notifyDataSetChanged();
}
});
return convertView;
}
}
So, CallingActivityName is the name of the Activity where you initiate the adapter and where the method you need to call resides. info is the object held at position position of the gridview. MyObjectClass is the class name of the objects in the List mEntries.

Custom ListView doesn't save it's state

I was using standart android ListView with simle_list_item_multiple_choice item layout and custom adapter. It saved it's stated on pause and restored on resume. But after few days of working on I've implemented SectionIndexer, StickyListHeadersAdapter interface within my adapter and changed ListView to StickyListHeadersListView from this library. Also there were other changes in application but these are only attached to ListView. However now when my application resumes working listview is coming scrolled to begining and with all items unchecked. I've tryed to remove SectionIndexer interface and sticky headers support but it had no effect. Maybe there is some hidden options of listview which I need to enable?
(tried saveState property - no effect)
public class WordAdapter extends ArrayAdapter<Word> implements SectionIndexer, StickyListHeadersAdapter{
// -----------------------------------------------------------------------
//
// Fields
//
// -----------------------------------------------------------------------
private int mResID;
private List<Word> mList;
private String[] mSectionNames;
private StickyListHeadersListView mListView;
private int[] mSectionIndexes;
private boolean mHeadersEnabled;
// -----------------------------------------------------------------------
//
// Constructor
//
// -----------------------------------------------------------------------
public WordAdapter(Context context, StickyListHeadersListView listView, int resID, List<Word> list, String[] sectionNames, int[] sectionIndexes, boolean enableHeaders) {
super(context, resID, list);
mResID = resID;
mList = list;
mListView = listView;
mSectionIndexes = sectionIndexes;
mSectionNames = sectionNames;
mHeadersEnabled = enableHeaders;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(mResID, parent, false);
holder = new ViewHolder();
holder.root = convertView;
holder.textView = (TextView) convertView.findViewById(android.R.id.text1);
holder.checkBox = (CheckBox) convertView.findViewById(android.R.id.checkbox);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
holder.textView.setText(getItem(position).getValue());
if(mListView.isItemChecked(position))
holder.root.setBackgroundColor(getContext().getResources().getColor(R.color.highlight));
else
holder.root.setBackgroundColor(getContext().getResources().getColor(android.R.color.transparent));
return convertView;
}
#Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
if(!mHeadersEnabled)
return new View(getContext());
HeaderViewHolder holder;
if (convertView == null) {
holder = new HeaderViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_header, parent, false);
holder.labelView = (TextView) convertView.findViewById(R.id.list_item_header_label);
convertView.setTag(holder);
} else {
holder = (HeaderViewHolder) convertView.getTag();
}
String label;
if(mSectionNames != null){
label = mSectionNames[getSectionForPosition(position)];
holder.labelView.setText(label);
}
return convertView;
}
#Override
public long getHeaderId(int position) {
long result = getSectionForPosition(position);
return result;
}
#Override
public int getPositionForSection(int section) {
return (mSectionIndexes == null || section < 0 ) ? 0 : (section == mSectionIndexes.length ? mList.size():mSectionIndexes[section]);
}
#Override
public int getSectionForPosition(int position) {
if(mSectionIndexes != null && position >= mSectionIndexes[0]) {
for(int i = 0; i < mSectionIndexes.length; ++i)
if(position < mSectionIndexes[i])
return i-1;
return (mSectionIndexes.length - 1);
}
return 0;
}
#Override
public Object[] getSections() {
return mSectionNames == null ? new Object[0] : mSectionNames;
}
// -------------------------------------------------------------------------------
//
// Internal classes
//
// -------------------------------------------------------------------------------
private static class ViewHolder {
public View root;
public TextView textView;
public CheckBox checkBox;
}
private static class HeaderViewHolder {
public TextView labelView;
}
Here is adapter code.

How to stop automatic checking of checkboxes in custom listview when scrolling the list?

I am making a custom listview having a checkbox.The problem is that when i scroll the list view,the items which are not checked become checked automatically.This is the code i am using:
public class ContactAdapterSetRule extends ArrayAdapter<String> {
public static ArrayList<String> s_itemsOfAdapterArrayList;
Context m_context;
public static ArrayList<String> s_checkedIds = new ArrayList<String>();
public ContactAdapterSetRule(Context context, int textViewResourceId, ArrayList<String> s_contactNameArrayListSplash) {
super(context, textViewResourceId, s_contactNameArrayListSplash);
this.s_itemsOfAdapterArrayList = s_contactNameArrayListSplash;
this.m_context = context;
s_checkedIds.clear(); //Clearing the list of Checked Ids
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View l_view = convertView;
if (l_view == null)
{
LayoutInflater l_vi = (LayoutInflater)m_context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
l_view = l_vi.inflate(R.layout.showthecontacts, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.l_nameCheckBox = (CheckBox) l_view.findViewById(R.id.checkBox);;
l_view.setTag(viewHolder);
}
String l_nameOfContact = s_itemsOfAdapterArrayList.get(position);
ViewHolder holder = (ViewHolder) l_view.getTag();
if (l_nameOfContact != null)
{
if (holder.l_nameCheckBox != null)
{
holder.l_nameCheckBox.setText(l_nameOfContact);
}
holder.l_nameCheckBox.setOnClickListener(new OnItemClickListener(position,holder.l_nameCheckBox.getText(),holder.l_nameCheckBox));
}
return l_view;
}
private class ViewHolder
{
CheckBox l_nameCheckBox;
}
private class OnItemClickListener implements OnClickListener
{
private int l_positionOfItemClicked;
private CharSequence l_text;
private CheckBox l_checkBox;
OnItemClickListener(int position, CharSequence text,CheckBox checkBox)
{
this.l_positionOfItemClicked = position;
this.l_text = text;
this.l_checkBox = checkBox;
}
#Override
public void onClick(View arg0)
{
if(l_checkBox.isChecked())
{
Log.v("","Checkbox is checked");
for(int i = 0;i < s_checkedIds.size();i++)
Log.v("",s_checkedIds.get(i));
if(!s_checkedIds.contains(l_text.toString()))
{
s_checkedIds.add( l_text.toString());
Log.e("",l_text.toString()+" is added to s_checkedIds");
}
}
else
{
Log.v("","Checkbox is Unchecked");
for(int i = 0;i < s_checkedIds.size();i++)
Log.v("",s_checkedIds.get(i));
if(s_checkedIds.contains(l_text.toString()))
{
s_checkedIds.remove( l_text.toString());
Log.e("",l_text.toString()+" is removed from s_checkedIds");
}
}
}
Please help me.I am not getting any idea about how to do it.Thanks in advance.

Categories

Resources