Android AlphabetIndexer English and Hebrew(Unicode) togather - android

Following is my listview adapter classes using AlphabetIndexer.
It does not work when I add unicode chars (for hebrew) togather with the english.
I get exception in: getSectionForPosition. getting to index -1....
Tries it with 2 entries in the DB - 1 starting with hebrew char (unicode) and one with english. The first char for AlphabetIndexer was the unicode char.
Really really need help in this one....
public abstract class RecipeListViewAdapter extends SimpleCursorAdapter implements SectionIndexer
{
protected Context mContext;
protected Cursor mCursor;
private LayoutInflater mInflater;
public static final int TYPE_HEADER = 1;
public static final int TYPE_NORMAL = 0;
private static final int TYPE_COUNT = 2;
private AlphabetIndexer indexer;
private int[] usedSectionNumbers;
private Map<Integer, Integer> sectionToOffset;
private Map<Integer, Integer> sectionToPosition;
protected ImageLoader mImageLoader = new ImageLoader( MyApp.Instance() );
public RecipeListViewAdapter( Context context,
int layout,
Cursor c,
String[] from,
int[] to )
{
super(context, layout, c, from, to);
mContext = context;
mCursor = c;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
indexer = new AlphabetIndexer(c, c.getColumnIndexOrThrow("NAME"), "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
sectionToPosition = new TreeMap<Integer, Integer>();
sectionToOffset = new HashMap<Integer, Integer>();
final int count = super.getCount();
int i;
for( i = count - 1 ; i >= 0; i-- )
{
sectionToPosition.put(indexer.getSectionForPosition(i), i);
}
i = 0;
usedSectionNumbers = new int[sectionToPosition.keySet().size()];
for( Integer section : sectionToPosition.keySet() )
{
sectionToOffset.put(section, i);
usedSectionNumbers[i] = section;
i++;
}
for(Integer section: sectionToPosition.keySet())
{
sectionToPosition.put(section, sectionToPosition.get(section) + sectionToOffset.get(section));
}
}
#Override
public int getCount()
{
if( super.getCount() != 0 )
{
return super.getCount() + usedSectionNumbers.length;
}
return 0;
}
#Override
public Object getItem(int position)
{
if (getItemViewType(position) == TYPE_NORMAL) //we define this function later
{
return super.getItem( GetItemPosition( position ) );
}
return null;
}
public int GetItemPosition( final int position )
{
return position - sectionToOffset.get(getSectionForPosition(position)) - 1;
}
public int getPositionForSection(int section) {
if (! sectionToOffset.containsKey(section)){
int i = 0;
int maxLength = usedSectionNumbers.length;
while (i < maxLength && section > usedSectionNumbers[i]){
i++;
}
if (i == maxLength) return getCount();
return indexer.getPositionForSection(usedSectionNumbers[i]) + sectionToOffset.get(usedSectionNumbers[i]);
}
return indexer.getPositionForSection(section) + sectionToOffset.get(section);
}
public int getSectionForPosition(int position) {
int i = 0;
int maxLength = usedSectionNumbers.length;
while (i < maxLength && position >= sectionToPosition.get(usedSectionNumbers[i])){
i++;
}
return usedSectionNumbers[i-1];
}
public Object[] getSections() {
return indexer.getSections();
}
//nothing much to this: headers have positions that the sectionIndexer manages.
#Override
public int getItemViewType(int position) {
if (position == getPositionForSection(getSectionForPosition(position))){
return TYPE_HEADER;
} return TYPE_NORMAL;
}
#Override
public int getViewTypeCount() {
return TYPE_COUNT;
}
#Override
public View getView( int position,
View convertView,
ViewGroup parent )
{
final int type = getItemViewType(position);
if (type == TYPE_HEADER)
{
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.header, parent, false);
}
((TextView)convertView.findViewById(R.id.header)).setText((String)getSections()[getSectionForPosition(position)]);
return convertView;
}
else
{
ViewHolder holder = new ViewHolder();
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.recipes_list_view_entry, null);
holder.name = (TextView) convertView.findViewById( R.id.name_entry );
holder.author = (TextView) convertView.findViewById( R.id.username_entry );
holder.ratingBar = (RatingBar) convertView.findViewById( R.id.list_RatingBarId );
holder.userRatingBar = (RatingBar) convertView.findViewById( R.id.list_userRatingBarId );
holder.diffculty = (ImageView) convertView.findViewById( R.id.list_DifficultyImageViewId );
holder.preparationTime = (ImageView) convertView.findViewById( R.id.list_TimeImageViewId );
holder.recipePic = new DisplayableImageView( (ImageView) convertView.findViewById( R.id.list_RecipeImageViewId ) );
holder.name.setTypeface( MyApp.Fonts.ARIAL );
holder.name.setTextSize( MyApp.Fonts.RUNNING_TEXT_SIZE );
holder.name.setTextColor( Color.BLACK );
}
else
{
holder = (ViewHolder) convertView.getTag();
}
if( super.getItem( GetItemPosition(position) ) != null )
{
// Check if single
if( getCount() == position+1 && position == 1 )
{
convertView.setBackgroundResource( R.drawable.list_single );
}
else if( getItemViewType(position-1) == TYPE_HEADER )
{
// Check if single item in the middle of the list
if( getItemViewType(position+1) == TYPE_HEADER )
{
convertView.setBackgroundResource( R.drawable.list_single );
}
else if( position == getCount() - 1 )
{
convertView.setBackgroundResource( R.drawable.list_single );
}
else
{
convertView.setBackgroundResource( R.drawable.list_up );
}
}
else
{
// Middle or bottom
convertView.setBackgroundResource( R.drawable.list_middle );
//If not last
if( getCount() != position + 1 )
{
// Check if middle or down
if( getItemViewType(position+1) == TYPE_HEADER )
{
convertView.setBackgroundResource( R.drawable.list_down );
}
else
{
convertView.setBackgroundResource( R.drawable.list_middle );
}
}
else
{
// If it is last - use list_down
convertView.setBackgroundResource( R.drawable.list_down );
}
}
FillRecipeDataToHolder( GetItemPosition(position), holder );
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
return convertView;
}
}
//these two methods just disable the headers
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if (getItemViewType(position) == TYPE_HEADER){
return false;
}
return true;
}
protected abstract void FillRecipeDataToHolder(int position, ViewHolder holder);
static class ViewHolder
{
TextView separator;
DisplayableImageView recipePic;
TextView name;
TextView author;
RatingBar ratingBar;
RatingBar userRatingBar;
ImageView diffculty;
ImageView preparationTime;
TextView serveCount;
}
}

Related

How to get listview items both visible and invisible child values

This loop return only visible position values.However I need the values of child items that are invisible.
for (int i = 0; i < material_issue_list.getCount(); i++) {
View layout = materialIssueAdapter.getViewByPositio(i, material_issue_list);
LinearLayout listItem = (LinearLayout) materialIssueAdapter.getViewByPositio(i, material_issue_list);
String batchSTR = ((AutoCompleteTextView) listItem.findViewById(R.id.batch_AutoComplete)).getText().toString();
String qtySTR = ((EditText) listItem.findViewById(R.id.issue_qty_ETD)).getText().toString();}
My full adapter class,Some one help me suggest to get the correct output.My problem I'm getting null values from the views that are invisible.
Only the visible values are being updated to arraylist.
Thanks in advance.
public class IssueMaterialAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList Dummylist;
private static LayoutInflater inflater = null;
public Resources res;
public static ArrayList<BatchNav> batchNavs_Arr;
static ArrayList<String> batch_Arr;
public static ArrayList<String> batch_data;
public static ArrayList<String> issue_qty;
LinkedHashSet<String> hashSet;
public static ArrayList<BatchModel> batchModels = new ArrayList<BatchModel>();
public static HashMap<ViewHolder, String> batch_map;
public static HashMap<ViewHolder, String> qty_map;
HashMap<String, String> mValues = new HashMap<String, String>();
ArrayList<SaveDataModel> saveDataModels;
public IssueMaterialAdapter(Activity a, ArrayList dummy) {
activity = a;
Dummylist = dummy;
loadBatch();
this.batch_map = new HashMap<>();
inflater = (LayoutInflater) activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (Dummylist.size() <= 0)
return 1;
return Dummylist.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.material_issue_details_list, null);
holder = new ViewHolder();
holder.batch = (AutoCompleteTextView) vi.findViewById(R.id.batch_AutoComplete);
holder.issue = (EditText) vi.findViewById(R.id.issue_qty_ET);
holder.material_descrption = (TextView) vi.findViewById(R.id.material_desc);
holder.unit_issue = (EditText) vi.findViewById(R.id.unit_issue_ET);
holder.matnr = (TextView) vi.findViewById(R.id.matnr);
holder.prdgrp = (TextView) vi.findViewById(R.id.prod_grp);
vi.setTag(holder);
batch_map.put(holder, "");
FilterWithSpaceAdapter<String> farmer_co_no_adapter = new FilterWithSpaceAdapter<String>(activity,
R.layout.custom_items, batch_Arr);
holder.batch.setAdapter(farmer_co_no_adapter);
holder.batch.setThreshold(1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Dummylist.size() == AgriDistributionActivity.get_materials.size()) {
holder.material_descrption.setText(AgriDistributionActivity.get_materials.get(position));
holder.matnr.setText(AgriDistributionActivity.get_matnr.get(position));
holder.prdgrp.setText(AgriDistributionActivity.selected_prdgrp.get(position));
}
try {
if (saveDataArr.size() > 0) {
holder.batch.setText(saveDataArr.get(position).getBatch());
holder.issue.setText(saveDataArr.get(position).getQty());
holder.unit_issue.setText(saveDataArr.get(position).getQty_uom());
}
} catch (Exception e) {
}
return vi;
}
public static class ViewHolder {
public EditText issue, unit_issue;
public AutoCompleteTextView batch;
public TextView material_descrption, matnr,prdgrp;
}
private void loadBatch() {
batch_Arr = new ArrayList<String>();
batchNavs_Arr = new ArrayList<BatchNav>();
hashSet = new LinkedHashSet<>();
BatchNavEntityCollection batchNavEntityCollection = BatchNavEntityCollection.getInstance();
batchNavs_Arr = batchNavEntityCollection.getBatchOutVal();
for (int i = 0; i < batchNavs_Arr.size(); i++) {
String batch = batchNavs_Arr.get(i).getCharg();
batch_Arr.add(batch);
hashSet.addAll(batch_Arr);
batch_Arr.clear();
batch_Arr.addAll(hashSet);
}
}
public View getViewByPositio(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition) {
return listView.getAdapter().getView(position, null, listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
}
You have saveDataArr list which holds all your data.
You can add a getter if you want to do it from an activity , add something like this to your adapter :
private SaveDataModelsendLog(int position) {
return saveDataArr(position);
}
That should do the trick , having said all that you should also look at the difference between static and non-static variables ,
it seems like you have to many of them ,
Enjoy.

RecyclerView Horizontal Scroll Data changes randomly

I am facing a issue in a horizontal recyclerview adapter.My adapter contains a imageview in postion 0 and remainings postion are empty.
When I do scroll from left to right, my images reappear from position 1 to 4 and 7.If I keeps on scrolling from left to right my imageview appears in all postion here is my adapter class.I have placed this Horizontal Recyclerview Adapter in a Vertical Recyclerview Adapter.
HomeBannerAdapter.Java
public class HomeBannerAdapter extends RecyclerView.Adapter {
private List<HomePageList> mHomepageList;
private Context mContext;
public HomeBannerAdapter(Context context, List<HomePageList> mHomepageList) {
this.mHomepageList = mHomepageList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, viewGroup, false);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
final HomePageList singleItem = mHomepageList.get(position);
holder.mTitle.setText(singleItem.getTitle());
if (!singleItem.getBannerUrl().isEmpty()) {
Glide.with(mContext).load(singleItem.getBannerUrl().get(0)).placeholder(R.drawable.placeholder).dontAnimate().into(holder.itemImage);
Log.e("Homebanner not empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
} else {
Log.e("Homebanner url empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
}
}
#Override
public int getItemCount() {
return (null != mHomepageList ? mHomepageList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
public ImageView itemImage;
//int position = getAdapterPosition();
public TextView mTitle;
public HomePageList mHomePageList;
public SingleItemRowHolder(View view) {
super(view);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
this.mTitle = (TextView) view.findViewById(R.id.tvTitle);
// mHomePageList = albumList.get(getPosition());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), mTitle.getText().toString() + " position " + getPosition() + "getAdapterPosition" + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Here is my Vertical Recyclerview Adapter
HomeDataAdapter.Java
public class HomeDataAdapter extends RecyclerView.Adapter {
private List<FormList> formList;
private Context mContext;
private List<HomePage> homePageList;
private List<ResourceType> resourceList;
final int VIEW_TYPE_HOMEPAGE = 0;
final int VIEW_TYPE_FORMPAGE = 1;
final int VIEW_TYPE_RESOURCEPAGE = 2;
public HomeDataAdapter(Context context, List<HomePage> homePageList) {
this.homePageList = homePageList;
this.mContext = context;
}
public HomeDataAdapter(Context context, List<HomePage> homePageList, List<FormList> formList) {
this.formList = formList;
this.homePageList = homePageList;
this.mContext = context;
}
public HomeDataAdapter(Context context, List<HomePage> homePageList, List<FormList> formList, List<ResourceType> resourceList) {
this.resourceList = resourceList;
this.formList = formList;
this.homePageList = homePageList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
switch (position) {
case VIEW_TYPE_HOMEPAGE:
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder homeView = new ViewHolder(v);
return homeView;
case VIEW_TYPE_FORMPAGE:
View v1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder formView = new ViewHolder(v1);
return formView;
case VIEW_TYPE_RESOURCEPAGE:
View v2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder resourceView = new ViewHolder(v2);
return resourceView;
}
return null;
}
#Override
public void onBindViewHolder(final ViewHolder itemRowHolder, int position) {
if (position == VIEW_TYPE_HOMEPAGE) {
HomePage mHomePage = homePageList.get(position);
Log.e("albumList", "albumList" + homePageList.get(position).toString() + "position" + position);
itemRowHolder.itemTitle.setText(mHomePage.getHeaderTitle());
HomeBannerAdapter itemListDataAdapter = new HomeBannerAdapter(mContext, mHomePage.getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.getLayoutManager().scrollToPosition(position);
itemRowHolder.mRecyclerview.getHorizontalOffset();
//itemRowHolder.mRecyclerview.scrollToPositionWithOffset(2, 20);
// itemRowHolder.mRecyclerview.getLayoutManager().smoothScrollToPosition(itemRowHolder.mRecyclerview, null, recyclerAdapter.getItemCount() - 1);
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
} else if (position == VIEW_TYPE_FORMPAGE) {
position = position - 1;
FormList mFormPage = formList.get(position);
itemRowHolder.itemTitle.setText(formList.get(position).getHeaderTitle());
JobBannerAdapter itemListDataAdapter = new JobBannerAdapter(mContext, mFormPage.getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
} else if (position == VIEW_TYPE_RESOURCEPAGE) {
position = position - 2;
ResourceType mResourceType = resourceList.get(position);
itemRowHolder.itemTitle.setText(mResourceType.getHeaderTitle());
ResourceBannerAdapter itemListDataAdapter = new ResourceBannerAdapter(mContext, resourceList.get(position).getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
}
}
#Override
public int getItemCount() {
int homePageListSize = 0;
int formPageListSize = 0;
int resourcePageListSize = 0;
if (homePageList == null && formList == null && resourceList == null) return 0;
if (resourceList != null)
resourcePageListSize = resourceList.size();
if (formList != null)
formPageListSize = formList.size();
if (homePageList != null)
homePageListSize = homePageList.size();
if (resourcePageListSize > 0 && formPageListSize > 0 && homePageListSize > 0)
return homePageListSize + formPageListSize + resourcePageListSize; // albumlist+formlist+resourceList
if (formPageListSize > 0 && homePageListSize > 0)
return homePageListSize + formPageListSize; // albumlist+formlist
else if (resourcePageListSize > 0 && homePageListSize == 0 && formPageListSize == 0)
return resourcePageListSize; // resourceList
else if (formPageListSize > 0 && homePageListSize == 0)
return formPageListSize; // formlist
else if (formPageListSize == 0 && homePageListSize > 0)
return homePageListSize; // albumlist
else return 0;
// return (null != albumList ? albumList.size()+mFormList.size() : 0);
}
#Override
public int getItemViewType(int position) {
int homePageListSize = 0;
int formPageListSize = 0;
int resourcePageListSize = 0;
if (homePageList == null && formList == null && resourceList == null)
return super.getItemViewType(position);
if (homePageList != null)
homePageListSize = homePageList.size();
if (formList != null)
formPageListSize = formList.size();
if (resourceList != null)
resourcePageListSize = resourceList.size();
if (formPageListSize > 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else if (position == formPageListSize)
return VIEW_TYPE_FORMPAGE;
} else if (formPageListSize == 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else return VIEW_TYPE_FORMPAGE;
} else if (resourcePageListSize > 0 && formPageListSize > 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else if (position == 1)
return VIEW_TYPE_FORMPAGE;
else if (position == 2)
return VIEW_TYPE_RESOURCEPAGE;
}
return super.getItemViewType(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemTitle;
public CustomRecyclerView mRecyclerview;
public ViewHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.itemTitle);
this.mRecyclerview = (CustomRecyclerView) view.findViewById(R.id.recycler_view_list);
}
}
}
I think some of your items bannerUrls is empty. So if they're empty you do not set a default empty image with Glide or manually. Here i modified your code a little. I think this'll help.
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
final HomePageList singleItem = mHomepageList.get(position);
holder.mTitle.setText(singleItem.getTitle());
if (!TextUtils.isEmpty(singleItem.getBannerUrl())) {
Glide.with(mContext).load(singleItem.getBannerUrl().get(0)).placeholder(R.drawable.placeholder).dontAnimate().into(holder.itemImage);
Log.e("Homebanner not empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
} else {
holder.itemImage.setImageResource(R.drawable.your_place_holder_for_empty_url);
}
}
Note: Also it's a better choice to use TextUtils.isEmpty(string) to instead of string.isEmpty() to avoid Null Pointer Exception.
Edit:
Also you can let Glide to put placeholder to your ImageView by removing the if statement.
if (!TextUtils.isEmpty(singleItem.getBannerUrl()))
I think this solution'll work you for too. If you choose this way do not forget to set an empty image to Glide for your empty or null urls.

RecyclerView with different layouts

when i use this
#Override
public int getItemViewType(int position) {
return position;
}
my RecyclerView work without problem
now i want to use multi layout on it i use this
#Override
public int getItemViewType(int position) {
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
//return position;
}
the problem when i used it's and scroll to top and back to bottom or just scrolling
its reorder item in RecyclerView like make the first item on it the last one or on middle or every where not i the correct position
just if i back to the first code of getItemViewType its work without
problem but i cant use multi layout
my full code
public class MessageAdapter1 extends RecyclerView.Adapter<MessageAdapter1.ViewHolder> {
private List<MessageList> mMessages;
private int[] mUsernameColors;
private Context context;
public MessageAdapter1(Context context, List<MessageList> messages) {
mMessages = messages;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
switch (viewType) {
case 0:
layout = R.layout.right_message;
break;
case 1:
layout = R.layout.left_message;
break;
case 2:
layout = R.layout.message_left;
break;
}
View v = LayoutInflater.from(parent.getContext()).inflate(layout , parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
MessageList message = mMessages.get(position);
//viewHolder.setMessage(message.getMessage());
//viewHolder.setUsername(message.getUsername());
viewHolder.setGroupMessage(message);
}
#Override
public int getItemCount() {
return mMessages.size();
}
#Override
public int getItemViewType(int position) {
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
//return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout groupMessage;
//private ImageView typing;
public ViewHolder(View itemView) {
super(itemView);
groupMessage = (LinearLayout)itemView.findViewById(R.id.messages);
}
public void setGroupMessage(MessageList m) {
if (null == groupMessage) return;
int i = 0;
if(m.getMessageStatus() == false){
m.setMessageStatus(true);
for (String message : m.getMessageList()) {
//TextView text = new TextView(activity);
TextView text = new MyTextView(context);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.setMargins(0, 0, 0, 2);
if (m.getDir().equals("left")) {
text.setTextColor(Color.BLACK);
p.gravity = Gravity.LEFT;
if(m.getMessageList().size() == 1){
text.setBackgroundResource(R.drawable.message_left_default);
}
else if (i == 0) {
text.setBackgroundResource(R.drawable.message_left_first);
} else if (i + 1 == m.getMessageList().size()) {
text.setBackgroundResource(R.drawable.message_left_last);
} else {
text.setBackgroundResource(R.drawable.message_left);
}
} else{
p.gravity = Gravity.RIGHT;
text.setTextColor(Color.WHITE);
if(m.getMessageList().size() == 1){
text.setBackgroundResource(R.drawable.message_right_default);
}
else if (i == 0) {
text.setBackgroundResource(R.drawable.message_right_first);
} else if (i + 1 == m.getMessageList().size()) {
text.setBackgroundResource(R.drawable.message_right_last);
} else {
text.setBackgroundResource(R.drawable.message_right);
}
}
text.setLayoutParams(p);
text.setText(message);
text.setPadding(8, 8, 8, 8);
text.setTextSize(18f);
//text.setTextAppearance(context, android.R.style.TextAppearance_Large);
groupMessage.addView(text);
i++;
}
}
}
}
}
I solve it by remove
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
from
getItemViewType
and return position
and put the first code
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
in onCreateViewHolder and use viewType as the current position

Adapter-Showing view only when there is a change in a value

Below is my complete adapter class of sendbird chatting.Currently date with time is displayed with every message.viewHolder.getView("left_time") and viewHolder.getView("right_time") are views for displaying date with time and it is calculated in method getDisplayDateTime.I want date with time to be displayed only when there is a change in date.For example if there is set of messages dated 23rd june then date with time should be displayed only for the first message with date 23rd june.
I tried doing that by detecting whenever there is a change in date by storing date in xyz variable and comparing it with date of every message and whenever they are unequal then making date view of that message visible and assigning the new date to xyz variable for comparison with future messages.But this approach fails when i scroll down and scroll up list.
What is the ideal approach for achieving this?
public class SendBirdMessagingAdapter extends BaseAdapter {
private static final int TYPE_UNSUPPORTED = 0;
private static final int TYPE_MESSAGE = 1;
private static final int TYPE_SYSTEM_MESSAGE = 2;
private static final int TYPE_FILELINK = 3;
private static final int TYPE_BROADCAST_MESSAGE = 4;
private static final int TYPE_TYPING_INDICATOR = 5;
private final Context mContext;
private final LayoutInflater mInflater;
private final ArrayList<Object> mItemList;
private Hashtable<String, Long> mReadStatus;
private Hashtable<String, Long> mTypeStatus;
private List<MessagingChannel.Member> mMembers;
private long mMaxMessageTimestamp = Long.MIN_VALUE;
private long mMinMessageTimestamp = Long.MAX_VALUE;
public SendBirdMessagingAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mItemList = new ArrayList<Object>();
mReadStatus = new Hashtable<String, Long>();
mTypeStatus = new Hashtable<String, Long>();
}
#Override
public int getCount() {
return mItemList.size() + ((mTypeStatus.size() <= 0) ? 0 : 1);
}
#Override
public Object getItem(int position) {
if (position >= mItemList.size()) {
ArrayList<String> names = new ArrayList<String>();
for (MessagingChannel.Member member : mMembers) {
if (mTypeStatus.containsKey(member.getId())) {
names.add(member.getName());
}
}
return names;
}
return mItemList.get(position);
}
public void delete(Object object) {
mItemList.remove(object);
}
public void clear() {
mMaxMessageTimestamp = Long.MIN_VALUE;
mMinMessageTimestamp = Long.MAX_VALUE;
mReadStatus.clear();
mTypeStatus.clear();
mItemList.clear();
}
public void resetReadStatus(Hashtable<String, Long> readStatus) {
mReadStatus = readStatus;
}
public void setReadStatus(String userId, long timestamp) {
if (mReadStatus.get(userId) == null || mReadStatus.get(userId) < timestamp) {
mReadStatus.put(userId, timestamp);
}
}
public void setTypeStatus(String userId, long timestamp) {
if (userId.equals(SendBird.getUserId())) {
return;
}
if (timestamp <= 0) {
mTypeStatus.remove(userId);
} else {
mTypeStatus.put(userId, timestamp);
}
}
#Override
public long getItemId(int position) {
return position;
}
public void addMessageModel(MessageModel messageModel) {
if (messageModel.isPast()) {
mItemList.add(0, messageModel);
} else {
mItemList.add(messageModel);
}
updateMessageTimestamp(messageModel);
}
private void updateMessageTimestamp(MessageModel model) {
mMaxMessageTimestamp = mMaxMessageTimestamp < model.getTimestamp() ? model.getTimestamp() : mMaxMessageTimestamp;
mMinMessageTimestamp = mMinMessageTimestamp > model.getTimestamp() ? model.getTimestamp() : mMinMessageTimestamp;
}
public long getMaxMessageTimestamp() {
return mMaxMessageTimestamp == Long.MIN_VALUE ? Long.MAX_VALUE : mMaxMessageTimestamp;
}
public long getMinMessageTimestamp() {
return mMinMessageTimestamp == Long.MAX_VALUE ? Long.MIN_VALUE : mMinMessageTimestamp;
}
public void setMembers(List<MessagingChannel.Member> members) {
mMembers = members;
}
#Override
public int getItemViewType(int position) {
if (position >= mItemList.size()) {
return TYPE_TYPING_INDICATOR;
}
Object item = mItemList.get(position);
if (item instanceof Message) {
return TYPE_MESSAGE;
} else if (item instanceof FileLink) {
return TYPE_FILELINK;
} else if (item instanceof SystemMessage) {
return TYPE_SYSTEM_MESSAGE;
} else if (item instanceof BroadcastMessage) {
return TYPE_BROADCAST_MESSAGE;
}
return TYPE_UNSUPPORTED;
}
#Override
public int getViewTypeCount() {
return 6;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
final Object item = getItem(position);
if (convertView == null || ((ViewHolder) convertView.getTag()).getViewType() != getItemViewType(position)) {
viewHolder = new ViewHolder();
viewHolder.setViewType(getItemViewType(position));
switch (getItemViewType(position)) {
case TYPE_UNSUPPORTED:
convertView = new View(mInflater.getContext());
convertView.setTag(viewHolder);
break;
case TYPE_MESSAGE: {
TextView tv;
CircularImageView iv;
View v;
convertView = mInflater.inflate(R.layout.sendbird_view_messaging_message, parent, false);
v = convertView.findViewById(R.id.left_container);
viewHolder.setView("left_container", v);
iv = (CircularImageView) convertView.findViewById(R.id.img_left_thumbnail);
viewHolder.setView("left_thumbnail", iv);
tv = (TextView) convertView.findViewById(R.id.txt_left);
viewHolder.setView("left_message", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_name);
viewHolder.setView("left_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_time);
viewHolder.setView("left_time", tv);
v = convertView.findViewById(R.id.right_container);
viewHolder.setView("right_container", v);
iv = (CircularImageView) convertView.findViewById(R.id.img_right_thumbnail);
viewHolder.setView("right_thumbnail", iv);
tv = (TextView) convertView.findViewById(R.id.txt_right);
viewHolder.setView("right_message", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_name);
viewHolder.setView("right_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_time);
viewHolder.setView("right_time", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_status);
viewHolder.setView("right_status", tv);
convertView.setTag(viewHolder);
break;
}
case TYPE_SYSTEM_MESSAGE: {
convertView = mInflater.inflate(R.layout.sendbird_view_system_message, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
case TYPE_BROADCAST_MESSAGE: {
convertView = mInflater.inflate(R.layout.sendbird_view_system_message, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
case TYPE_FILELINK: {
TextView tv;
CircularImageView civ;
ImageView iv;
View v;
convertView = mInflater.inflate(R.layout.sendbird_view_messaging_filelink, parent, false);
v = convertView.findViewById(R.id.left_container);
viewHolder.setView("left_container", v);
civ = (CircularImageView) convertView.findViewById(R.id.img_left_thumbnail);
viewHolder.setView("left_thumbnail", civ);
iv = (ImageView) convertView.findViewById(R.id.img_left);
viewHolder.setView("left_image", iv);
tv = (TextView) convertView.findViewById(R.id.txt_left_name);
viewHolder.setView("left_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_left_time);
viewHolder.setView("left_time", tv);
v = convertView.findViewById(R.id.right_container);
viewHolder.setView("right_container", v);
civ = (CircularImageView) convertView.findViewById(R.id.img_right_thumbnail);
viewHolder.setView("right_thumbnail", civ);
iv = (ImageView) convertView.findViewById(R.id.img_right);
viewHolder.setView("right_image", iv);
tv = (TextView) convertView.findViewById(R.id.txt_right_name);
viewHolder.setView("right_name", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_time);
viewHolder.setView("right_time", tv);
tv = (TextView) convertView.findViewById(R.id.txt_right_status);
viewHolder.setView("right_status", tv);
convertView.setTag(viewHolder);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(mContext)
.setTitle("Foodvite")
.setMessage("Do you want to download this file?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
downloadUrl((FileLink) item, mContext);
} catch (IOException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
}
});
break;
}
case TYPE_TYPING_INDICATOR: {
convertView = mInflater.inflate(R.layout.sendbird_view_typing_indicator, parent, false);
viewHolder.setView("message", convertView.findViewById(R.id.txt_message));
convertView.setTag(viewHolder);
break;
}
}
}
viewHolder = (ViewHolder) convertView.getTag();
switch (getItemViewType(position)) {
case TYPE_UNSUPPORTED:
break;
case TYPE_MESSAGE:
Message message = (Message) item;
if (message.getSenderId().equals(SendBird.getUserId())) {
viewHolder.getView("left_container", View.class).setVisibility(View.GONE);
viewHolder.getView("right_container", View.class).setVisibility(View.VISIBLE);
displayUrlImage(viewHolder.getView("right_thumbnail", CircularImageView.class), message.getSenderImageUrl(), true);
viewHolder.getView("right_name", TextView.class).setText(message.getSenderName());
viewHolder.getView("right_message", TextView.class).setText(message.getMessage());
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp()));
int readCount = 0;
for (String key : mReadStatus.keySet()) {
if (key.equals(message.getSenderId())) {
readCount += 1;
continue;
}
if (mReadStatus.get(key) >= message.getTimestamp()) {
readCount += 1;
}
}
if (readCount < mReadStatus.size()) {
if (mReadStatus.size() - readCount > 1) {
viewHolder.getView("right_status", TextView.class).setText("Unread " + (mReadStatus.size() - readCount));
} else {
viewHolder.getView("right_status", TextView.class).setText("Unread");
}
} else {
viewHolder.getView("right_status", TextView.class).setText("");
}
viewHolder.getView("right_container").setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(mContext)
.setTitle("Foodvite")
.setMessage("Do you want to delete a message?")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SendBird.deleteMessage(((Message) item).getMessageId(), new DeleteMessageHandler() {
#Override
public void onError(SendBirdException e) {
e.printStackTrace();
}
#Override
public void onSuccess(long messageId) {
mSendBirdMessagingAdapter.delete(item);
mSendBirdMessagingAdapter.notifyDataSetChanged();
Toast.makeText(mContext, "Message has been deleted.", Toast.LENGTH_SHORT).show();
}
});
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create()
.show();
return true;
}
});
} else {
viewHolder.getView("left_container", View.class).setVisibility(View.VISIBLE);
viewHolder.getView("right_container", View.class).setVisibility(View.GONE);
displayUrlImage(viewHolder.getView("left_thumbnail", CircularImageView.class), message.getSenderImageUrl(), true);
viewHolder.getView("left_name", TextView.class).setText(message.getSenderName());
viewHolder.getView("left_message", TextView.class).setText(message.getMessage());
viewHolder.getView("left_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp()));
if(isGroupChat)
viewHolder.getView("left_name", TextView.class).setVisibility(View.VISIBLE);
else
viewHolder.getView("left_name", TextView.class).setVisibility(View.GONE);
}
break;
case TYPE_SYSTEM_MESSAGE:
SystemMessage systemMessage = (SystemMessage) item;
viewHolder.getView("message", TextView.class).setText(Html.fromHtml(systemMessage.getMessage()));
break;
case TYPE_BROADCAST_MESSAGE:
BroadcastMessage broadcastMessage = (BroadcastMessage) item;
viewHolder.getView("message", TextView.class).setText(Html.fromHtml(broadcastMessage.getMessage()));
break;
case TYPE_FILELINK:
FileLink fileLink = (FileLink) item;
if (fileLink.getSenderId().equals(SendBird.getUserId())) {
viewHolder.getView("left_container", View.class).setVisibility(View.GONE);
viewHolder.getView("right_container", View.class).setVisibility(View.VISIBLE);
displayUrlImage(viewHolder.getView("right_thumbnail", ImageView.class), fileLink.getSenderImageUrl(), true);
viewHolder.getView("right_name", TextView.class).setText(fileLink.getSenderName());
if (fileLink.getFileInfo().getType().toLowerCase().startsWith("image")) {
displayUrlImage(viewHolder.getView("right_image", ImageView.class), fileLink.getFileInfo().getUrl());
} else {
viewHolder.getView("right_image", CircularImageView.class).setImageResource(R.drawable.sendbird_icon_file);
}
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, fileLink.getTimestamp()));
int readCount = 0;
for (String key : mReadStatus.keySet()) {
if (key.equals(fileLink.getSenderId())) {
continue;
}
if (mReadStatus.get(key) < fileLink.getTimestamp()) {
readCount += 1;
}
}
if (readCount < mReadStatus.size() - 1) {
viewHolder.getView("right_status", TextView.class).setText("Unread");
} else {
viewHolder.getView("right_status", TextView.class).setText("");
}
} else {
viewHolder.getView("left_container", View.class).setVisibility(View.VISIBLE);
viewHolder.getView("right_container", View.class).setVisibility(View.GONE);
displayUrlImage(viewHolder.getView("left_thumbnail", ImageView.class), fileLink.getSenderImageUrl(), true);
viewHolder.getView("left_name", TextView.class).setText(fileLink.getSenderName());
if (fileLink.getFileInfo().getType().toLowerCase().startsWith("image")) {
displayUrlImage(viewHolder.getView("left_image", ImageView.class), fileLink.getFileInfo().getUrl());
} else {
viewHolder.getView("left_image", CircularImageView.class).setImageResource(R.drawable.sendbird_icon_file);
}
if(isGroupChat)
viewHolder.getView("left_name", TextView.class).setVisibility(View.VISIBLE);
else
viewHolder.getView("left_name", TextView.class).setVisibility(View.GONE);
viewHolder.getView("left_time", TextView.class).setText(getDisplayDateTime(mContext, fileLink.getTimestamp()));
}
break;
case TYPE_TYPING_INDICATOR: {
int itemCount = ((List) item).size();
String typeMsg = ((List) item).get(0)
+ ((itemCount > 1) ? " +" + (itemCount - 1) : "")
+ ((itemCount > 1) ? " are " : " is ")
+ "typing...";
viewHolder.getView("message", TextView.class).setText(typeMsg);
break;
}
}
return convertView;
}
public boolean checkTypeStatus() {
/**
* Clear an old type status.
*/
for (String key : mTypeStatus.keySet()) {
Long ts = mTypeStatus.get(key);
if (System.currentTimeMillis() - ts > 10 * 1000L) {
mTypeStatus.remove(key);
return true;
}
}
return false;
}
private class ViewHolder {
private Hashtable<String, View> holder = new Hashtable<String, View>();
private int type;
public int getViewType() {
return this.type;
}
public void setViewType(int type) {
this.type = type;
}
public void setView(String k, View v) {
holder.put(k, v);
}
public View getView(String k) {
return holder.get(k);
}
public <T> T getView(String k, Class<T> type) {
return type.cast(getView(k));
}
}
}
private static String getDisplayDateTime(Context context, long milli) {
Date date = new Date(milli);
if (System.currentTimeMillis() - milli < 60 * 60 * 24 * 1000l) {
return DateFormat.getTimeFormat(context).format(date);
}
return DateFormat.getDateFormat(context).format(date) + " " + DateFormat.getTimeFormat(context).format(date);
}
Try below code for your method,
private static String getDisplayDateTime(Context context, long milli, long milli2)
{
Date date = new Date(milli);
Date previousDate = new Date(milli2);
String strCurrentDate = "", strPreviousDate = "";
if (System.currentTimeMillis() - milli < 60 * 60 * 24 * 1000l)
{
strCurrentDate = DateFormat.getTimeFormat(context).format(date);
if(milli2 != -1)
strPreviousDate = DateFormat.getTimeFormat(context).format(previousDate);
//return strCurrentDate.equals(strPreviousDate) ? "" : strCurrentDate;
}
else
{
strCurrentDate = DateFormat.getDateFormat(context).format(date) + " " + DateFormat.getTimeFormat(context).format(date);
if(milli2 != -1)
strPreviousDate = DateFormat.getDateFormat(context).format(strPreviousDate) + " " + DateFormat.getTimeFormat(context).format(strPreviousDate);
}
return strCurrentDate.equals(strPreviousDate) ? "" : strCurrentDate;
}
Now call your methods like below
if(position > 0)
{
final Object previousItem = getItem(position - 1);
Message previousMessage = (Message) previousItem;
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp(), previousMessage.getTimestamp()));
}
else
{
viewHolder.getView("right_time", TextView.class).setText(getDisplayDateTime(mContext, message.getTimestamp(), -1));
}
I had a similar problem (ref this SO Question) few months ago and nothing worked except extending from ArrayAdapter<MyObject> instead of BaseAdapter.
So, change the base class of your adapter to ArrayAdapter<MyObject> and implement the prompted method of the abstract class. you might need to move some you your existing code to these overridden methods for better performance.
You can force the system to redraw all items by calling BaseAdapter.notifyDataSetChanged()

Sectioned GridView in android

I am following this https://github.com/madhu314/sectionedgridview for sectioned gridview.
In data_item.xml I have checkbox instead of imagebutton. I want to check multiple items and then send the checked item to another activity.
The problem that I am facing is, that when i scroll the listview up or down, the checkboxes that are checked get unchecked and different checkboxes are checked.
I need help regarding this. Any help will be greatly appreciated.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = null;
boolean isSectionheader = isSectionHeader(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (isSectionheader) {
v = inflater.inflate(R.layout.section_header, null);
} else {
LinearLayout ll = (LinearLayout) inflater.inflate(
R.layout.list_row, null);
v = ll;
ll = (LinearLayout) ll.findViewById(R.id.row_item);
// add childrenCount to this
for (int i = 0; i < numberOfChildrenInRow; i++) {
// add a child
View child = inflater.inflate(R.layout.data_item, null);
ll.addView(child, new LinearLayout.LayoutParams(
gridItemSize, gridItemSize));
if (i < numberOfChildrenInRow - 1) {
// now add space view
View spaceItem = new View(mContext);
ll.addView(spaceItem, new LinearLayout.LayoutParams(
childrenSpacing[i], ll.getHeight()));
}
}
}
} else {
v = convertView;
}
String sectionName = whichSection(position);
if (isSectionheader) {
TextView tv = (TextView) v;
tv.setText(sectionName);
} else {
LinearLayout ll = (LinearLayout) v;
LinearLayout rowPanel = (LinearLayout) ll.findViewById(R.id.row_item);
View divider = ll.findViewById(R.id.row_item_divider);
divider.setVisibility(View.VISIBLE);
// check if this position corresponds to last row
boolean isLastRowInSection = isLastRowInSection(position);
int positionInSection = positionInSection(position);
Cursor c = sectionCursors.get(sectionName);
// --
int cursorStartAt = numberOfChildrenInRow * positionInSection;
// set all children visible first
for (int i = 0; i < 2 * numberOfChildrenInRow - 1; i++) {
// we need to hide grid item and gap
View child = rowPanel.getChildAt(i);
child.setVisibility(View.VISIBLE);
// leave alternate
if (i % 2 == 0) {
// its not gap
if (c.moveToPosition(cursorStartAt)) {
String dataName = c.getString(0);
TextView tv = (TextView) child
.findViewById(R.id.data_item_text);
tv.setText(dataName);
}
// set listener on image button
checkbox = (CheckBox) child
.findViewById(R.id.data_item_image);
ButtonViewHolder holder = new ButtonViewHolder();
holder.sectionName = sectionName;
holder.positionInSection = cursorStartAt;
holder.parent = child;
holder.position = position;
checkbox.setTag(holder);
checkbox.setOnCheckedChangeListener(this);
cursorStartAt++;
}
}
checkbox.setChecked(mSparseBooleanArray.get(position));
if (isLastRowInSection) {
divider.setVisibility(View.INVISIBLE);
// check how many items needs to be hidden in last row
int sectionCount = sectionCursors.get(sectionName).getCount();
int childrenInLastRow = sectionCount % numberOfChildrenInRow;
if (childrenInLastRow > 0) {
int gaps = childrenInLastRow - 1;
for (int i = childrenInLastRow + gaps; i < rowPanel
.getChildCount(); i++) {
// we need to hide grid item and gap
View child = rowPanel.getChildAt(i);
child.setVisibility(View.INVISIBLE);
}
}
}
}
return v;
}
As per your question, you need to select the multiple images and after that you need to do an action (like coping selected images, delete / upload etc). So for that you need to hold the selection image positions as well as you need to change the selection color too..
For that i simply created an adapter, it having the multiple image selection and various methods to get the selected images and select all/ de select all options.. In this i controlled all the possibilities think so.. If it is the same means, change your adapter class like this..
Here is my adapter class:
public class LocalFilesUploadAdapter extends BaseAdapter
{
private final HashMap<Integer, Boolean> myChecked = new HashMap<Integer, Boolean>();
private final Activity _activity;
private ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
ArrayList<String> listPaths;
ArrayList<String> listNames;
private LayoutInflater inflater = null;
public LocalFilesUploadAdapter( Context context,
Activity activity,
ArrayList<String> filePaths,
ArrayList<String> fileNames,
ArrayList<Bitmap> bitmaps )
{
this._activity = activity;
this.listPaths = filePaths;
this.listNames = fileNames;
this.bitmaps = bitmaps;
inflater = LayoutInflater.from( context );
for( int i = 0; i < filePaths.size(); i++ )
{
myChecked.put( i,
false );
}
}
public void toggleChecked( int position )
{
if( myChecked.get( position ) )
{
myChecked.put( position,
false );
}
else
{
myChecked.put( position,
true );
}
notifyDataSetChanged();
}
public void selectAllItems( int position )
{
myChecked.put( position,
true );
notifyDataSetChanged();
}
public void deSelectAllItems( int position )
{
myChecked.put( position,
false );
notifyDataSetChanged();
}
public List<Integer> getCheckedItemPositions()
{
List<Integer> checkedItemPositions = new ArrayList<Integer>();
for( int i = 0; i < myChecked.size(); i++ )
{
if( myChecked.get( i ) )
{
( checkedItemPositions ).add( i );
}
}
return checkedItemPositions;
}
public ArrayList<String> getCheckedItems()
{
ArrayList<String> checkedItems = new ArrayList<String>();
// ArrayList<HashMap<String, String>> checkedItems = new ArrayList<HashMap<String, String>>();
for( int i = 0; i < myChecked.size(); i++ )
{
if( myChecked.get( i ) )
{
String pathName = listPaths.get( i );
( checkedItems ).add( pathName );
}
}
return checkedItems;
}
public ArrayList<String> getCheckedItemNames()
{
ArrayList<String> checkedItems = new ArrayList<String>();
// ArrayList<HashMap<String, String>> checkedItems = new ArrayList<HashMap<String, String>>();
for( int i = 0; i < myChecked.size(); i++ )
{
if( myChecked.get( i ) )
{
String imageName = listNames.get( i );
( checkedItems ).add( imageName );
}
}
return checkedItems;
}
public boolean selectAll()
{
for( int i = 0; i < listPaths.size(); i++ )
{
selectAllItems( i );
}
return false;
}
public boolean deSelectAll()
{
for( int i = 0; i < listPaths.size(); i++ )
{
deSelectAllItems( i );
}
return false;
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
if( 0 == listPaths.size() )
{
return 0;
}
return this.listPaths.size();
}
#Override
public Object getItem( int position )
{
// TODO Auto-generated method stub
return this.listPaths.get( position );
}
#Override
public long getItemId( int position )
{
// TODO Auto-generated method stub
return position;
}
#Override
public View getView( final int position,
View convertView,
ViewGroup parent )
{
View row = convertView;
if( row == null )
{
row = inflater.inflate( R.layout.gridview_item,
null );
}
Log.d( "debug",
"position" + position );
ImageView imageView = (ImageView) row.findViewById( R.id.grid_image );
CheckBox checkbox = (CheckBox) row.findViewById( R.id.img_checkBox );
imageView.setImageBitmap( bitmaps.get( position ) );
checkbox.setOnClickListener( new OnClickListener()
{
#Override
public void onClick( View v )
{
// TODO Auto-generated method stub
toggleChecked( position );
}
} );
Boolean checked = myChecked.get( position );
if( checked != null )
{
checkbox.setChecked( checked );
}
imageView.setOnClickListener( new OnImageClickListener( position ) );
return row;
}
class OnImageClickListener implements OnClickListener
{
int _postion;
// constructor
public OnImageClickListener( int position )
{
this._postion = position;
}
#Override
public void onClick( View v )
{
// on selecting grid view image
// launch full screen activity
toggleChecked( _postion );
}
}
}
Hope it vll help's you

Categories

Resources