Display list user with gridview android studio - java

I'm having trouble removing the "parent channel shortcut" even though I already have it hidden (view2.setvisiblity(view.GONE)). I'm using gridview android:numColumns="3".The list user display starts from the left side, If I want to remove it, how do I do that?
#Override
public int getCount() {
int count = currentusers.size() + subchannels.size() + stickychannels.size();
if ((curchannel != null) && (curchannel.nParentID > 0)) {
count++; // include parent channel shortcut
}
return count;
}
#Override
public Object getItem(int position) {
if (position < stickychannels.size()) {
return stickychannels.get(position);
}
// sticky channels are first so subtract these
position -= stickychannels.size();
if (position < currentusers.size()) {
return currentusers.get(position);
}
// users are first so subtract these
position -= currentusers.size();
if ((curchannel != null) && (curchannel.nParentID > 0)) {
if(position == 0) {
Channel parent = ttservice.getChannels().get(curchannel.nParentID);
if(parent != null)
return parent;
return new Channel();
}
position--; // subtract parent channel shortcut
}
return subchannels.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
if (position < stickychannels.size())
return INFO_VIEW_TYPE;
// sticky channels are first so subtract these
position -= stickychannels.size();
if (position < currentusers.size())
return USER_VIEW_TYPE;
// users are first so subtract these
position -= currentusers.size();
if ((curchannel != null) && (curchannel.nParentID > 0)) {
if (position == 0) {
return PARENT_CHANNEL_VIEW_TYPE;
}
position--; // subtract parent channel shortcut
}
return CHANNEL_VIEW_TYPE;
}
#Override
public int getViewTypeCount() {
return VIEW_TYPE_COUNT;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Object item = getItem(position);
if(item instanceof Channel) {
final Channel channel = (Channel) item;
switch (getItemViewType(position)) {
case PARENT_CHANNEL_VIEW_TYPE :
// show parent channel shortcut
if (convertView == null ||
convertView.findViewById(R.id.parentname) == null)
convertView = inflater.inflate(R.layout.item_channel_back, parent, false);
convertView.setVisibility(view.GONE)
break;
case CHANNEL_VIEW_TYPE :
if (convertView == null ||
convertView.findViewById(R.id.channelname) == null)
convertView = inflater.inflate(R.layout.item_channel, parent, false);
ImageView chanicon = convertView.findViewById(R.id.channelicon);
TextView name = convertView.findViewById(R.id.channelname);
TextView topic = convertView.findViewById(R.id.chantopic);
Button join = convertView.findViewById(R.id.join_btn);
int icon_resource = R.drawable.channel_orange;
if(channel.bPassword) {
icon_resource = R.drawable.channel_pink;
chanicon.setContentDescription(getString(R.string.text_passwdprot));
chanicon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
else {
chanicon.setContentDescription(null);
chanicon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
}
chanicon.setImageResource(icon_resource);
if(channel.nParentID == 0) {
// show server name as channel name for root channel
ServerProperties srvprop = new ServerProperties();
ttclient.getServerProperties(srvprop);
name.setText(srvprop.szServerName);
}
else {
name.setText(channel.szName);
}
topic.setText(channel.szTopic);
OnClickListener listener = v -> {
if (v.getId() == R.id.join_btn) {
joinChannel(channel);
}
};
join.setOnClickListener(listener);
join.setAccessibilityDelegate(accessibilityAssistant);
join.setEnabled(channel.nChannelID != ttclient.getMyChannelID());
if (channel.nMaxUsers > 0) {
int population = Utils.getUsers(channel.nChannelID, ttservice.getUsers()).size();
((TextView)convertView.findViewById(R.id.population)).setText((population > 0) ? String.format("(%d)", population) : "");
}
break;
case INFO_VIEW_TYPE :
if (convertView == null ||
convertView.findViewById(R.id.titletext) == null)
convertView = inflater.inflate(R.layout.item_info, parent, false);
TextView title = convertView.findViewById(R.id.titletext);
TextView details = convertView.findViewById(R.id.infodetails);
title.setText(channel.szName);
details.setText(channel.szTopic);
break;
}
}
else if(item instanceof User) {
if (convertView == null ||
convertView.findViewById(R.id.nickname) == null)
convertView = inflater.inflate(R.layout.item_user, parent, false);
ImageView usericon = convertView.findViewById(R.id.usericon);
TextView nickname = convertView.findViewById(R.id.nickname);
TextView status = convertView.findViewById(R.id.status);
final User user = (User) item;
String name = Utils.getDisplayName(getBaseContext(), user);
nickname.setText(name);
status.setText(user.szStatusMsg);
boolean talking = (user.uUserState & UserState.USERSTATE_VOICE) != 0;
boolean female = (user.nStatusMode & TeamTalkConstants.STATUSMODE_FEMALE) != 0;
boolean away = (user.nStatusMode & TeamTalkConstants.STATUSMODE_AWAY) != 0;
int icon_resource;
if(user.nUserID == ttservice.getTTInstance().getMyUserID()) {
talking = ttservice.isVoiceTransmitting();
}
if(talking) {
if(female) {
icon_resource = R.drawable.woman_green;
nickname.setContentDescription(getString(R.string.user_state_now_speaking, name) + " 👩");
}
else {
icon_resource = R.drawable.man_green;
nickname.setContentDescription(getString(R.string.user_state_now_speaking, name) + " 👨");
}
}
else {
if(female) {
icon_resource = away? R.drawable.woman_orange : R.drawable.woman_blue;
nickname.setContentDescription(name + " 👩");
}
else {
icon_resource = away? R.drawable.man_orange : R.drawable.man_blue;
nickname.setContentDescription(name + " 👨");
}
}
status.setContentDescription(away ? getString(R.string.user_state_away) : null);
usericon.setImageResource(icon_resource);
usericon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
Button sndmsg = convertView.findViewById(R.id.msg_btn);
OnClickListener listener = v -> {
if (v.getId() == R.id.msg_btn) {
Intent intent = new Intent(MainActivity.this, TextMessageActivity.class);
startActivity(intent.putExtra(TextMessageActivity.EXTRA_USERID, user.nUserID));
}
};
sndmsg.setOnClickListener(listener);
sndmsg.setAccessibilityDelegate(accessibilityAssistant);
}
convertView.setAccessibilityDelegate(accessibilityAssistant);
return convertView;
}
The list user display starts from the left side

Related

OnbindViewHolder holder not returning exact position when more data are added

I'm having this problem when ever more data is added to the recycleview the total number of of item to be be displayed reduces by 1 or 2 depending on the number of items in the recycleview or it will return full size sometimes
Here is my code
private static final int MENU_ITEM_VIEW_TYPE= 0;
// The Native Express ad view type.
private static final int NATIVE_AD_VIEW_TYPE = 1;
private static final int ITEM_FEED_COUNT = 6;
private final Activity activity;
Keystore stopAdsPref;
Boolean isStopAd;
public AdapterPosts(Context context, Activity activity, List<ModelPost> postList) {
this.context = context;
this.postList = postList;
this.activity = activity;
myUid = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid();
likeRef = FirebaseDatabase.getInstance().getReference().child("Likes");
postsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
stopAdsPref = Keystore.getInstance(context);
isStopAd = stopAdsPref.getBoolean(STOP_ADS);
}
public void setItems(ArrayList<ModelPost> emp) {
postList.addAll(emp);
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == MENU_ITEM_VIEW_TYPE) {
View view = LayoutInflater.from(context).inflate(R.layout.row_posts, parent, false);
return new AdapterPosts.MyHolder(view);
} else if (viewType == NATIVE_AD_VIEW_TYPE) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_ad, parent, false);
return new AdapterPosts.MyHolder(view);
} else {
return null;
}
}
I think the problem is after int pos = position - Math.round(position / ITEM_FEED_COUNT);
#Override
public void onBindViewHolder(#NonNull
MyHolder holder, int position) {
Log.e(TAG, "onBindViewHolder: step 1 " + position);
if (holder.getItemViewType() == MENU_ITEM_VIEW_TYPE) {
int pos = position - Math.round(position / ITEM_FEED_COUNT);
Log.e(TAG, "onBindViewHolder: step 2: " + pos);
((AdapterPosts.MyHolder) holder).bindData(postList.get(pos), pos, holder);
} else if (holder.getItemViewType() == NATIVE_AD_VIEW_TYPE) {
if (isStopAd.equals(true)) {
Log.e(TAG, "AD stop");
} else {
((AdapterPosts.MyHolder) holder).bindAdData();
}
}
requestQueue = Volley.newRequestQueue(context);
}
#Override
public int getItemCount() {
if (postList.size() > 0) {
return postList.size() + Math.round(postList.size() / ITEM_FEED_COUNT);
}
return postList.size();
}
#Override
public int getItemViewType(int position{
if ((position + 1) % ITEM_FEED_COUNT== 0) {
return NATIVE_AD_VIEW_TYPE;
}
return MENU_ITEM_VIEW_TYPE;
}
I was able to solve this it might be helpful to someone in the future code below
Answer from here
#Override
public int getItemCount() {
int additionalContent = 0;
if (data.size() > 0 && LIST_AD_DELTA > 0 && data.size() > LIST_AD_DELTA) {
additionalContent = data.size() / LIST_AD_DELTA;
}
return data.size() + additionalContent;
}
#Override
public void onBindViewHolder(BaseRecyclerHolder baseHolder, int position) {
if (getItemViewType(position) == CONTENT) {
ContentRecyclerHolder holder = (ContentRecyclerHolder) baseHolder;
Content content = data.get(getRealPosition(position));
} else {
AdRecyclerHolder holder = (AdRecyclerHolder) baseHolder;
AdRequest adRequest = new AdRequest.Builder().build();
if (adRequest != null && holder.adView != null){
holder.adView.loadAd(adRequest);
}
}
}

How to get the Position of an item's child view?

In list View I created Programmatically Image view and added in Linear Layout inside of ListView item.Below code I use for add Images in Adapter. Then how to get That image position.
Below I added my getView() method. I'm getting multiple Images in "String[] childDocument". using for loop I Sepreted Images from String[] and add in Linear Layout.
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
final ApproveReimbBin item = getItem(position);
FoldingCell cell = (FoldingCell) convertView;
final ViewHolder viewHolder;
String date = item.getStr_startDate();
String[] splitDate = date.split("To");
String profileName = item.getStr_name();
String profileEmpId = item.getStr_empId();
String profileType = item.getStr_type();
String profileAmount = item.getStr_amount();
final String[] childDocument = item.getStr_documents();
if (cell == null) {
viewHolder = new ViewHolder();
LayoutInflater vi = LayoutInflater.from(getContext());
cell = (FoldingCell) vi.inflate(R.layout.adapter_approvereimburs, parent, false);
// binding view parts to view holder
viewHolder.imag_listProfileImage = cell.findViewById(R.id.list_image);
viewHolder.txt_listName = cell.findViewById(R.id.list_profileName);
viewHolder.txt_listEmpId = cell.findViewById(R.id.list_profileEmpId);
viewHolder.txt_listType = cell.findViewById(R.id.list_profileType);
viewHolder.image_childProfileImage = cell.findViewById(R.id.child_profile_img);
viewHolder.txt_name = cell.findViewById(R.id.txt_profile_name);
viewHolder.txt_empId = cell.findViewById(R.id.txt_profile_id);
viewHolder.txt_type = cell.findViewById(R.id.txt_profile_type);
viewHolder.txt_frmDate = cell.findViewById(R.id.txt_from_date);
viewHolder.txt_toDate = cell.findViewById(R.id.txt_to_date);
viewHolder.txt_amount = cell.findViewById(R.id.txt_amount);
viewHolder.btn_reject = cell.findViewById(R.id.btn_reject);
viewHolder.btn_approve = cell.findViewById(R.id.btn_approve);
viewHolder.linearLayout = cell.findViewById(R.id.linearLayout_Image);
cell.setTag(viewHolder);
} else {
if (unfoldedIndexes.contains(position)) {
cell.unfold(true);
Log.e("suraj", "unfold call");
} else {
cell.fold(true);
Log.e("suraj", "fold call");
}
viewHolder = (ViewHolder) cell.getTag();
}
if (null == item)
return cell;
String ImageUrl = ServerUrls.Web.IMAGE_URL + profileEmpId.trim() + ".jpg";
ImageView image;
if (viewHolder.linearLayout.getChildCount() > 0) {
viewHolder.linearLayout.removeAllViews();
}
for (int i = 0; i < childDocument.length; i++) {
String doc = childDocument[i].replace("~", "");
doc = doc.replace("\\", "/");
doc = doc.replace(",", "");
image = new ImageView(mContext);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(100, 100));
image.setMaxHeight(100);
image.setMaxWidth(100);
Log.e("surajjj", "for loop use " + imageDocument.trim() + doc);
Picasso.with(mContext)
.load(imageDocument.trim() + doc)
.error(R.drawable.doc_img)
.into(image);
viewHolder.linearLayout.addView(image);
int lent = childDocument.length;
Log.e("surajj", "docu " + imageDocument.trim() + doc + " position " + i + " lenth " + lent);
}
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int sr = viewHolder.linearLayout.indexOfChild(view);
Toast.makeText(mContext, "Postition is "+ sr, Toast.LENGTH_SHORT).show();
}
});
viewHolder.linearLayout.getChildAt(position).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, childDocument.toString(), Toast.LENGTH_SHORT).show();
}
});
Picasso.with(mContext)
.load(ImageUrl.trim())
.error(R.drawable.ic_user)
.into(viewHolder.imag_listProfileImage);
Picasso.with(mContext)
.load(ImageUrl.trim())
.error(R.drawable.ic_user)
.into(viewHolder.image_childProfileImage);
if (profileName != null || !profileName.equals(" ")) {
viewHolder.txt_listName.setText(profileName);
viewHolder.txt_name.setText(profileName);
}
if (profileEmpId != null || !profileEmpId.equals(" ")) {
viewHolder.txt_listEmpId.setText(profileEmpId);
viewHolder.txt_empId.setText(profileEmpId);
}
if (profileType != null || !profileType.equals(" ")) {
viewHolder.txt_listType.setText(profileType);
viewHolder.txt_type.setText(profileType);
}
if (profileAmount != null || !profileAmount.equals(" ")) {
viewHolder.txt_amount.setText(profileAmount);
}
if (splitDate != null || !splitDate.equals(" ")) {
if (splitDate.length == 2) {
Log.d("suraj1", "fromDate " + splitDate[0] + " toDate " + splitDate[1]);
viewHolder.txt_frmDate.setText(splitDate[0]);
viewHolder.txt_toDate.setText(splitDate[1]);
} else {
Log.d("suraj1", "onlyfromDate " + splitDate[0]);
viewHolder.txt_frmDate.setText(splitDate[0]);
}
}
viewHolder.btn_approve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestId = item.getStr_requestId();
reimbursmentId = item.getStr_reimbursementid();
action = "Approved";
Methods.showProgressDialog(mContext);
unfoldedIndexes.clear();
new asyncSendRequest().execute();
}
});
viewHolder.btn_reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestId = item.getStr_requestId();
reimbursmentId = item.getStr_reimbursementid();
action = "Rejected";
Methods.showProgressDialog(mContext);
unfoldedIndexes.clear();
new asyncSendRequest().execute();
}
});
return cell;
}
In this Image I'm dynamically added images. I want this perticular image position.

Android ListView Adapter getView() method calls more than one times [duplicate]

This question already has answers here:
custom listview adapter getView method being called multiple times, and in no coherent order
(12 answers)
Closed 6 years ago.
Java code
public class ContentListAdapter extends ArrayAdapter<Content> implements Filterable {
//private static final String TAG = ContentListAdapter.class.getCanonicalName();
private static final LogTracer LOG_TRACER = LogTracer.instance(ContentListAdapter.class);
private Context mContext;
private LayoutInflater mInflater;
private List<Content> mContents;
private List<Content> mContentsFiltered;
private int lastPosition = -1;
private boolean multiselectMode = false;
private Customer mCustomer = null;
private AdapterView.OnItemClickListener mOnItemClickListener;
private AdapterView.OnItemLongClickListener mOnItemLongClickListener;
PatientRatingDAO patientRatingDAO;
int completeVisiblePosition=0;
public int totalScrollCount= 0;
private boolean isFromHomeSearch;
private ListView mListView;
public View helpView;
public ContentListAdapter(Context context, List<Content> contents, ListView listView) {
super(context, R.layout.list_content, contents);
mContext = context;
mContents = contents;
mListView = listView;
mContentsFiltered = contents;
mInflater = LayoutInflater.from(mContext);
mCustomer = new CustomerDAO(context).getCurrentCustomer();
patientRatingDAO = new PatientRatingDAO(getContext());
}
private class ViewHolder {
View listContent;
ImageButton contentThumbnail, contentThumbnailNew,typeofarticle;
LinearLayout contentRightSec;
LinearLayout contentRightSecBottom;
TextView fileSize;
LinearLayout tagsView;
TextView contentPostTime;
TextView contentDescription;
TextView contentSource;
LinearLayout rateCountSec;
LinearLayout rateBarLayout;
TextView rateCount;
TextView likeCount;
TextView likeText;
ImageView likeImage,likeCountImage,rateCountImage,readtick;
RatingBar ratingBar;
RatingBar disabledRatingBar;
RelativeLayout patienteducation;
//int isLiked;
//int currentUserRateCount;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
// assign the view we are converting to a local variable
View v = convertView;
LOG_TRACER.d("parm getView " + position + " " + convertView);
// Calculating Scroll Count
if(getCompleteVisiblePosition() == 0){
if(v != null && mListView != null){
this.setCompleteVisiblePosition(calculateCompletelyVisibleListItems(v));
LOG_TRACER.d("parm completeVisiblePosition" + completeVisiblePosition);
}
}
if(getCompleteVisiblePosition() > 0){
if(position % getCompleteVisiblePosition() == 0){
totalScrollCount++;
LOG_TRACER.d("parm totalScrollCount" + totalScrollCount);
}
}
// first check to see if the view is null. if so, we have to inflate it.
// to inflate it basically means to render, or show, the view.
if (v == null) {
//LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//v = inflater.inflate(mLayout, null);
v = LayoutInflater.from(mContext).inflate(R.layout.list_content, parent, false);
ViewHolder holder = new ViewHolder();
holder.rateCount = (TextView) v.findViewById(R.id.rateCount);
holder.likeCount = (TextView) v.findViewById(R.id.likeCount);
holder.likeCountImage = (ImageView) v.findViewById(R.id.likeCountImage);
holder.rateCountImage = (ImageView) v.findViewById(R.id.rateCountImage);
holder.likeText = (TextView) v.findViewById(R.id.like_text);
holder.likeImage = (ImageView) v.findViewById(R.id.like_image);
holder.ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
holder.disabledRatingBar = (RatingBar) v.findViewById(R.id.disabled_rating_bar);
holder.typeofarticle = (ImageButton) v.findViewById(R.id.typeofarticle);
holder.patienteducation = (RelativeLayout) v.findViewById(R.id.patient_education);
v.setTag(holder);
}
final Content content = getItem(position);
final ViewHolder viewHolder = (ViewHolder) v.getTag();
if(viewHolder.listContent != null) {
if(content.getIs_Read() == Constants.INT_FLAG_YES) {
viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_grey);
viewHolder.readtick.setVisibility(View.VISIBLE);
} else {
viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_white);
viewHolder.readtick.setVisibility(View.GONE);
}
if(viewHolder.contentThumbnailNew != null){
Ion.with(viewHolder.contentThumbnailNew).fitXY().placeholder(R.drawable.imagethumbnail).fitXY().error(R.drawable.imagethumbnail).fitXY().load(
(!TextUtils.isEmpty(content.getDA_Thumbnail_Url()))?content.getDA_Thumbnail_Url().replaceAll(" ","%20") : content.getDA_Thumbnail_Url());
}
if(viewHolder.contentThumbnail != null) {
viewHolder.contentThumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
if (multiselectMode) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
} else {
if (mOnItemLongClickListener != null)
mOnItemLongClickListener.onItemLongClick(null, v, position, position);
}
} else {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
}
}
});
viewHolder.contentThumbnailNew.setOnTouchListener(new TouchExtendedClickListener(mContext, new TouchExtendedClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view) {
if (mOnItemClickListener != null) mOnItemClickListener.onItemClick(null, convertView, position, position);
}
}));
viewHolder.contentThumbnailNew.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
if (multiselectMode) {
if (mOnItemClickListener != null)
mOnItemClickListener.onItemClick(null, v, position, position);
} else {
if (mOnItemLongClickListener != null)
mOnItemLongClickListener.onItemLongClick(null, v, position, position);
}
}
return true;
}
});
}
}
}
//To Set Ratings
if (viewHolder.rateCount != null) {
//Calculate rate count by (totalratigs/numberofusersrated)
if(content.getTotalRatings() == 0 || content.getTotalRatedCount()==0){
viewHolder.rateCount.setText("0");
}else if(content.getTotalRatedCount() != 0){
viewHolder.rateCount.setText(String.valueOf(Math.round(content.getTotalRatings()/content.getTotalRatedCount())));
}
}
//To Set Likes
if (viewHolder.likeCount != null) {
viewHolder.likeCount.setText(String.valueOf(content.getLikes()));
}
//if viewHolder.isLiked == 0 then user not yet liked else if viewHolder.isLiked == 1 the user liked
//viewHolder.isLiked = content.getIsLiked();
//viewHolder.currentUserRateCount = content.getCurrentUserRateCount();
//Add Like Listeners
if (viewHolder.likeText != null && viewHolder.likeImage != null) {
if(content.getIsLiked() == 0){
//Set liked image and text
viewHolder.likeText.setText("Like");
viewHolder.likeImage.setImageResource(R.drawable.ic_like_grey_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_grey_24dp);
}else{
//Set liked image and text
//viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);
}
viewHolder.likeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (content.getIsLiked() == 0) {
content.setIsLiked(1);
//To insert/update user likes to local database
PatientRating patientRating = patientRatingDAO.getByDACodeAndType(content.getDA_Code(),content.getContent_Type());
if(patientRating != null){
patientRating.setIsLiked(content.getIsLiked());
patientRatingDAO.update(patientRating);
}else{
patientRating = new PatientRating();
patientRating.setIsLiked(1);
patientRating.setContent_Type(content.getContent_Type());
patientRating.setDA_Code(content.getDA_Code());
patientRatingDAO.insert(patientRating);
}
//viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);
//Increase like counts
int likes = 1 + Integer.parseInt(viewHolder.likeCount.getText().toString());
viewHolder.likeCount.setText(String.valueOf(likes));
viewHolder.rateBarLayout.setVisibility(View.VISIBLE);
Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.like_animation);
viewHolder.likeImage.startAnimation(animation);
//Toast.makeText(mContext, "Liked", Toast.LENGTH_SHORT).show();
return v;
}
#Override
public int getCount() {
return mContentsFiltered.size();
}
#Override
public Content getItem(int position) {
return mContentsFiltered.get(position);
}
public Filter getFilter(FilterOption filterOption) {
return getFilter();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase().trim();
FilterResults results = new FilterResults();
final List<Content> list = mContents;
int count = list.size() - 1;
List<Content> nlist = new ArrayList<Content>(list.size());
Content filterableContent;
for (int i = 0; i <= count; i++) {
filterableContent = list.get(i);
if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
} else if (!TextUtils.isEmpty(filterableContent.getTags())
&& filterableContent.getTags().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
}else if (!TextUtils.isEmpty(filterableContent.getCompany_Name())
&& filterableContent.getCompany_Name().toLowerCase().contains(filterString)) {
nlist.add(filterableContent);
}
}
/*List<Integer> companyIds = StaticVariableUtils.getFilterOption().getFilterCompanyIds();
for (int i = 0; i < count; i++) {
filterableContent = list.get(i);
if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
// if company ids are selected, check if
// the filtered content has slected company id
if(companyIds != null && companyIds.size() >= 1) {
if(companyIds.indexOf(filterableContent.getCompany_Id()) >= 0) {
nlist.add(filterableContent);
}
} else {
nlist.add(filterableContent);
}
}
}
List<Content> tmpList = new ArrayList<>(nlist.size());
if(nlist != null) {
// sort by datetime
Collections.sort(nlist, new Comparator<Content>() {
#Override
public int compare(Content lhs, Content rhs) {
if(StaticVariableUtils.getFilterOption().getSortingOrder() == R.string.sortingOrderLatest) {
return (lhs.getUploaded_Date().getTime()>rhs.getUploaded_Date().getTime()
? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
} else {
return (lhs.getUploaded_Date().getTime()<rhs.getUploaded_Date().getTime()
? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
}
}
});
}
FilterOption filterOption = StaticVariableUtils.getFilterOption();
if(filterOption.getShowByDate() == R.string.showByDateToday) {
nlist = filterByToday(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateLastWeek) {
nlist = filterByLastWeek(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateTwoWeeks) {
nlist = filterByTwoWeeks(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateThreeWeeks) {
nlist = filterByThreeWeeks(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateLastMonth) {
nlist = filterByLastMonth(nlist);
} else if(filterOption.getShowByDate() == R.string.showByDateOlder) {
nlist = filterByOlder(nlist);
}
if(filterOption.getShowByStatus() != R.string.showByStatusAll) {
nlist = getReadOrUnread(nlist, filterOption.getShowByStatus());
}*/
results.values = nlist;
results.count = nlist.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mContentsFiltered = (ArrayList<Content>) results.values;
notifyDataSetChanged();
}
};
}
my xml file
<ListView
android:id="#+id/lvContent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e2e2e2"
android:clipToPadding="false"
android:divider="#null"
android:dividerHeight="0dp"
android:fadingEdge="none"
android:smoothScrollbar="true"
android:fitsSystemWindows="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:scrollbarStyle="insideOverlay">
</ListView>
getView method in Adapter of list view call multiple time at postion 0
So it is Taking a more time to Load this Activity.This codes are i am using....i don't know why getview() calls more than one time.and my working code is above.. how to Resolve this issue.
I Resolve this issuee...... Because i added list from three different methods and also set notifydatasetchange. so my get view called more than one time....

Cannot set value to textview in runonuithread

public class PerformanceDashboard extends MotherActivity {
String dashboardData;
int SELECTED_PAGE, SEARCH_TYPE, TRAY_TYPE;
List<String[]> cachedCounterUpdates = new ArrayList<String[]>();
List<DasDetails> docList = new ArrayList<DasDetails>();
ListView listViewDashboard;
DataAdapter dataAdap = new DataAdapter();
TextView noOfItems, userCount, totalLoginTime;
int itemsTotal = 0, userTotal = 0, totalTime = 0;
String KEYWORD = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (App.isTestVersion) {
Log.e("actName", "StoreOut");
}
if (bgVariableIsNull()) {
this.finish();
return;
}
setContentView(R.layout.dashboard);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setProgressBarIndeterminateVisibility(false);
lytBlocker = (LinearLayout) findViewById(R.id.lyt_blocker);
listViewDashboard = (ListView) findViewById(R.id.dashboard_listview);
noOfItems = ((TextView) findViewById(R.id.noOfItems));
userCount = ((TextView) findViewById(R.id.userCount));
totalLoginTime = ((TextView) findViewById(R.id.totalLoginTime));
new DataLoader().start();
listViewDashboard.setAdapter(dataAdap);
System.out.println("PerformanceDashboard. onCreate processOutData() -- item total " + itemsTotal); //0 i am not getting that adapter value i.e. 6
System.out.println("PerformanceDashboard. onCreate processOutData() -- user total " + userTotal); //0 i am not getting that adapter value i.e. 4
System.out.println("PerformanceDashboard. onCreate processOutData() -- total total " + totalTime); //0 i am not getting that adapter value i.e. 310
}
private class DataAdapter extends BaseAdapter {
#Override
public int getCount() {
return docList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.dashboard_item, null);
final DasDetails item = docList.get(position);
((TextView) convertView.findViewById(R.id.cMode))
.setText(item.cMode);
((TextView) convertView.findViewById(R.id.noOfItems))
.setText(item.totPickItemCount);
((TextView) convertView.findViewById(R.id.userCount))
.setText(item.userCount);
((TextView) convertView.findViewById(R.id.totalLoginTime))
.setText(item.totLoginTime);
TextView textView = ((TextView) convertView
.findViewById(R.id.avgSpeed));
Double s = Double.parseDouble(item.avgPickingSpeed);
textView.setText(String.format("%.2f", s));
if (position == 0 || position == 2 || position == 4) {
convertView.setBackgroundColor(getResources().getColor(
R.color.hot_pink));
} else if (position == 1 || position == 3 || position == 5) {
convertView.setBackgroundColor(getResources().getColor(
R.color.lightblue));
}
return convertView;
}
}
class ErrorItem {
String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public ErrorItem(HashMap<String, String> row) {
cMode = row.get(XT.MODE);
dDate = row.get(XT.DATE);
userCount = row.get(XT.USER_COUNT);
totLoginTime = row.get(XT.TOT_LOGIN_TIME);
totPickItemCount = row.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = row.get(XT.AVG_PICKING_SPEED);
}
}
private class DataLoader extends Thread {
#Override
public void run() {
super.run();
System.out.println("DataLoader dashboard");
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair(C.PRM_IDX, C.GET_SUMMARY));
param.add(new BasicNameValuePair(C.PRM_HDR_DATA, "2016-07-04")); // yyyy-mm-dd
toggleProgressNoUINoBlock(true);
final String result = callService(C.WS_ST_PERFORMANCE_DASHBOARD,
param);
if (!App.validateXmlResult(actContext, null, result, true))
return;
runOnUiThread(new Runnable() {
#Override
public void run() {
Runnable r = new Runnable() {
#Override
public void run() {
dataAdap.notifyDataSetChanged();
toggleProgressNoUINoBlock(false);
}
};
dashboardData = result;
processOutData(r);
}
});
}
}
private String callService(String serviceName, List<NameValuePair> params) {
String result = ws.callService(serviceName, params);
return result;
}
private void processOutData(final Runnable rAfterProcessing) {
if (dashboardData == null || dashboardData.length() == 0)
return;
new Thread() {
#Override
public void run() {
super.run();
final List<HashMap<String, String>> dataList = XMLfunctions
.getDataList(dashboardData, new String[] { XT.MODE,
XT.DATE, XT.USER_COUNT, XT.TOT_LOGIN_TIME,
XT.TOT_PICK_ITEM_COUNT, XT.AVG_PICKING_SPEED });
final List<DasDetails> tempList = new ArrayList<DasDetails>();
for (int i = 0; i < dataList.size(); i++) {
int pos = docExists(tempList, dataList.get(i).get(XT.MODE));
if (pos == -1) {
if (SEARCH_TYPE == 0
|| KEYWORD.equals("")
|| (SEARCH_TYPE == 1 && dataList.get(i)
.get(XT.CUST_NAME).contains(KEYWORD))
|| (SEARCH_TYPE == 2 && dataList.get(i)
.get(XT.DOC_NO).contains(KEYWORD))) {
DasDetails doc = new DasDetails(dataList.get(i));
int cachePos = getPosInCachedCounterUpdates(doc.cMode);
if (cachePos != -1) {
if (cachedCounterUpdates.get(cachePos)[1]
.equals(doc.dDate))
cachedCounterUpdates.remove(cachePos);
else
doc.dDate = cachedCounterUpdates
.get(cachePos)[1];
}
tempList.add(doc);
pos = tempList.size() - 1;
}
}
if (pos == -1)
continue;
}
runOnUiThread(new Runnable() {
#Override
public void run() {
docList = tempList;
rAfterProcessing.run();
logit("processOutData", "Processing OVER");
}
});
for (int i = 0; i < docList.size(); i++) {
itemsTotal = itemsTotal+ Integer.parseInt(docList.get(i).totPickItemCount);
userTotal = userTotal + Integer.parseInt(docList.get(i).userCount);
totalTime = totalTime + Integer.parseInt(docList.get(i).totLoginTime);
}
System.out.println("PerformanceDashboard.processOutData() -- fINAL item TOTAL " + itemsTotal); // 6 i have data here but i need this data in my oncreate but not getting why?????
System.out.println("PerformanceDashboard.processOutData() -- userTotal TOTAL " + userTotal); //4
System.out.println("PerformanceDashboard.processOutData() -- totalTime TOTAL " + totalTime); //310
noOfItems.setText(itemsTotal); // crashing with null pointer exception
// userCount.setText(userTotal);
// totalLoginTime.setText(totalTime);
};
}.start();
}
private class DasDetails {
public String cMode, dDate, userCount, totLoginTime, totPickItemCount,
avgPickingSpeed;
public DasDetails(HashMap<String, String> data) {
cMode = data.get(XT.MODE);
dDate = data.get(XT.DATE);
userCount = data.get(XT.USER_COUNT);
totLoginTime = data.get(XT.TOT_LOGIN_TIME);
totPickItemCount = data.get(XT.TOT_PICK_ITEM_COUNT);
avgPickingSpeed = data.get(XT.AVG_PICKING_SPEED);
}
}
public Integer docExists(List<DasDetails> list, String docNo) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).cMode.equals(docNo))
return i;
}
return -1;
}
private int getPosInCachedCounterUpdates(String docNo) {
for (int i = 0; i < cachedCounterUpdates.size(); i++) {
if (cachedCounterUpdates.get(i)[0].equals(docNo))
return i;
}
return -1;
}
}
This is the above code please go through it and let me know if any clarifications are required. I cannot able to set "itemsTotal" value to "noOfIttems" textview. I have added the comments. Please help me in solving this issue.
Thanks in advance.
Please check your noOfItems textView's id. TextView is null.

Android actionbar: Custom fade animation on tab icon and title

I'm trying to make a custom animation that works pretty much the same way the tumblr android app works using the standard actionbar. (Not fading of the content of the tabs) I'm pretty close to getting it working but I have troubles fixing the last part. Maybe someone here can help me in the right direction to get this working.
EDIT: Image to show what I mean: IMAGE
What I have.
In onCreate I add some custom views for the tabs:
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
final CustomPageTransformer cpt = new CustomPageTransformer();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
cpt.currentItem = position;
}
});
mViewPager.setPageTransformer(true, cpt);
CustomTabView tabNews = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(0).toString(), mSectionsPagerAdapter.getIcon(0));
CustomTabView tabEvents = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(1).toString(), mSectionsPagerAdapter.getIcon(1));
CustomTabView tabContacts = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(2).toString(), mSectionsPagerAdapter.getIcon(2));
CustomTabView tabClub = new CustomTabView(this, mSectionsPagerAdapter.getPageTitle(3).toString(), mSectionsPagerAdapter.getIcon(3));
actionBar.addTab(actionBar.newTab().setCustomView(tabNews).setTabListener(this).setTag(0));
actionBar.addTab(actionBar.newTab().setCustomView(tabEvents).setTabListener(this).setTag(1));
actionBar.addTab(actionBar.newTab().setCustomView(tabContacts).setTabListener(this).setTag(2));
actionBar.addTab(actionBar.newTab().setCustomView(tabClub).setTabListener(this).setTag(3));
The CustomTabView looks like this, where I've added two custom view so I can easily set the alpha of the views:
public class CustomTabView extends RelativeLayout {
AlphaTextView text1;
AlphaImageView icon1;
int alpha;
public CustomTabView(Context context, String text, Drawable icon) {
super(context);
init(context, text, icon);
}
public CustomTabView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, null, null);
}
public CustomTabView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, null, null);
}
private void init(Context context, String text, Drawable icon) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.tab_view, this, true);
text1 = (AlphaTextView) findViewById(R.id.title);
text1.setTypeface(Font.rMedium(context));
text1.setText(text);
icon1 = (AlphaImageView) findViewById(R.id.icon);
icon1.setImageDrawable(icon);
setTheAlpha(128);
}
public void setTheAlpha(int aleph) {
this.alpha = aleph;
if (alpha < 128) alpha = 128;
if (alpha > 255) alpha = 255;
text1.onSetAlpha(alpha);
icon1.onSetAlpha(alpha);
}
public int getTheAlpha() {
return alpha;
}
}
Then there is the problem, the CustomPageTransformer:
public class CustomPageTransformer implements ViewPager.PageTransformer {
public int currentItem = 0;
View currentView = null;
public CustomTabView tabNews = null;
public CustomTabView tabEvents = null;
public CustomTabView tabContacts = null;
public CustomTabView tabClub = null;
#Override
public void transformPage(View view, float position) {
if (position != 0.0 && position != 1.0 && position != 2.0 && position != -1.0) {
if (currentView == null) {
currentView = view;
Log.e("First number", String.valueOf(position));
}
} else if (position == 0.0 || position == 1.0 || position == 2.0 || position == -1.0 || position == -2.0) currentView = null;
if (view == currentView) {
int alphaCurrent = (int) (255 - (128*Math.abs(position)));
if (alphaCurrent > 255) alphaCurrent = 255;
else if (alphaCurrent < 128) alphaCurrent = 128;
int alphaNext = (int) (128 + (128*Math.abs(position)));
if (alphaNext > 255) alphaNext = 255;
else if (alphaNext < 128) alphaNext = 128;
if (tabNews != null && tabEvents != null && tabContacts != null && tabClub != null) {
switch(currentItem) {
case 0:
if (position <= -1) {
tabNews.setTheAlpha(128);
tabEvents.setTheAlpha(255);
} else if (position <= 0) {
tabNews.setTheAlpha(alphaCurrent);
tabEvents.setTheAlpha(alphaNext);
}
break;
case 1:
if (position <= -1) {
tabEvents.setTheAlpha(128);
tabContacts.setTheAlpha(255);
} else if (position <= 0) {
tabEvents.setTheAlpha(alphaCurrent);
tabContacts.setTheAlpha(alphaNext);
} else if (position <= 1) {
tabEvents.setTheAlpha(alphaCurrent);
tabNews.setTheAlpha(alphaNext);
} else if (position > 1) {
tabEvents.setTheAlpha(128);
tabNews.setTheAlpha(255);
}
break;
case 2:
if (position <= -1) {
tabContacts.setTheAlpha(128);
tabClub.setTheAlpha(255);
} else if (position <= 0) {
tabContacts.setTheAlpha(alphaCurrent);
tabClub.setTheAlpha(alphaNext);
} else if (position <= 1) {
tabContacts.setTheAlpha(alphaCurrent);
tabEvents.setTheAlpha(alphaNext);
} else if (position > 1) {
tabEvents.setTheAlpha(255);
tabContacts.setTheAlpha(128);
}
break;
case 3:
if (position <= 1) {
tabClub.setTheAlpha(alphaCurrent);
tabContacts.setTheAlpha(alphaNext);
} else if (position > 1) {
tabClub.setTheAlpha(128);
tabContacts.setTheAlpha(255);
}
break;
}
}
}
}
}
The transformPage method gets (View & Position). The view is always the fragment you are going to and from in the viewpager, so every second time I have a positive value in position and then the next a negative value depending on which direction you are sliding.
First I thought I could use the view to determine which the current tab is and what direction I'm going in by taking whatever view comes first, but that seems to be random.
And since the position value jumps from negative to positive it generates a bit of a random fading result in the tabs.
Any ideas of how I can get this to work smoothly?
I found a better way of achieving this without using the page transformer. By using setOnPageChangeListener.
I've made an example app here: https://github.com/andreborud/FadingTabs
The code is pretty much just this:
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int alphaCurrent = (int) (255 - (128*Math.abs(positionOffset)));
int alphaNext = (int) (128 + (128*Math.abs(positionOffset)));
if (positionOffset != 0) {
switch(position) {
case 0:
tab0.setTheAlpha(alphaCurrent);
tab1.setTheAlpha(alphaNext);
break;
case 1:
tab1.setTheAlpha(alphaCurrent);
tab2.setTheAlpha(alphaNext);
break;
case 2:
tab2.setTheAlpha(alphaCurrent);
tab3.setTheAlpha(alphaNext);
break;
}
}
}
});

Categories

Resources