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.
Related
I have a smart school app. I have built a custom calendar in this, but the app crashed while the app call fragment in which the custom calendar exists in XML. I am trying to do this using the XML file but I get the Error inflating class. Can anyone help me, please? Thanks in advance
xml class is:
<LinearLayout
android:id="#+id/attendance_mainLay"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/lightGrey">
<com.qdocs.smartschool.utils.CustomCalendar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/robotoCalendarPicker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<!--android:background="#android:color/transparent"-->
</LinearLayout>
and the logcat said:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.qdocs.smartschool, PID: 18617
android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class com.qdocs.smartschool.utils.CustomCalendar
Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class com.qdocs.smartschool.utils.CustomCalendar
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at android.view.LayoutInflater.createView(LayoutInflater.java:658)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:801)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:874)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:877)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:835)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.qdocs.smartschool.fragments.DashboardCalender.onCreateView(DashboardCalender.java:72)
Custom Calendar code:
public class CustomCalendar extends LinearLayout {
private Context context;
private TextView dateTitle;
private ImageView leftButton;
private ImageView rightButton;
private View rootView;
public String startweek;
private ViewGroup robotoCalendarMonthLayout;
String dateText;
private RobotoCalendarListener robotoCalendarListener;
private Calendar currentCalendar;
private Calendar lastSelectedDayCalendar;
private static final String DAY_OF_THE_WEEK_TEXT = "dayOfTheWeekText";
private static final String DAY_OF_THE_WEEK_LAYOUT = "dayOfTheWeekLayout";
private static final String DAY_OF_THE_MONTH_LAYOUT = "dayOfTheMonthLayout";
private static final String DAY_OF_THE_MONTH_TEXT = "dayOfTheMonthText";
private static final String DAY_OF_THE_MONTH_BACKGROUND = "dayOfTheMonthBackground";
private static final String DAY_OF_THE_MONTH_CIRCLE_IMAGE_1 = "dayOfTheMonthCircleImage1";
private static final String DAY_OF_THE_MONTH_CIRCLE_IMAGE_2 = "dayOfTheMonthCircleImage2";
private static final String DAY_OF_THE_MONTH_CIRCLE_IMAGE_3 = "dayOfTheMonthCircleImage3";
private static final String DAY_OF_THE_MONTH_CIRCLE_IMAGE_4 = "dayOfTheMonthCircleImage4";
private static final String DAY_OF_THE_MONTH_CIRCLE_IMAGE_5 = "dayOfTheMonthCircleImage5";
private boolean shortWeekDays = false;
String[] weekDaysArray;
// ************************************************************************************************************************************************************************
// * Initialization methods
// ************************************************************************************************************************************************************************
public CustomCalendar(Context context) {
super(context);
this.context = context;
onCreateView();
}
public CustomCalendar(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
if (isInEditMode()) {
return;
}
onCreateView();
}
private View onCreateView() {
LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rootView = inflate.inflate(R.layout.roboto_calendar_picker_layout, this, true);
findViewsById(rootView);
setUpEventListeners();
Calendar currentCalendar = Calendar.getInstance();
setCalendar(currentCalendar);
return rootView;
}
private void findViewsById(View view) {
robotoCalendarMonthLayout = (ViewGroup) view.findViewById(R.id.robotoCalendarDateTitleContainer);
leftButton = (ImageView) view.findViewById(R.id.leftButton);
rightButton = (ImageView) view.findViewById(R.id.rightButton);
dateTitle = (TextView) view.findViewById(R.id.monthText);
robotoCalendarMonthLayout.setBackgroundColor(Color.parseColor(Utility.getSharedPreferences(context.getApplicationContext(), Constants.secondaryColour)));
for (int i = 0; i < 42; i++) {
LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int weekIndex = (i % 7) + 1;
ViewGroup dayOfTheWeekLayout = (ViewGroup) view.findViewWithTag(DAY_OF_THE_WEEK_LAYOUT + weekIndex);
// Create day of the month
View dayOfTheMonthLayout = inflate.inflate(R.layout.roboto_calendar_day_of_the_month_layout, null);
View dayOfTheMonthText = dayOfTheMonthLayout.findViewWithTag(DAY_OF_THE_MONTH_TEXT);
View dayOfTheMonthBackground = dayOfTheMonthLayout.findViewWithTag(DAY_OF_THE_MONTH_BACKGROUND);
View dayOfTheMonthCircleImage1 = dayOfTheMonthLayout.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_1);
View dayOfTheMonthCircleImage2 = dayOfTheMonthLayout.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_2);
View dayOfTheMonthCircleImage3 = dayOfTheMonthLayout.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_3);
View dayOfTheMonthCircleImage4 = dayOfTheMonthLayout.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_4);
View dayOfTheMonthCircleImage5 = dayOfTheMonthLayout.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_5);
// Set tags to identify them
int viewIndex = i + 1;
dayOfTheMonthLayout.setTag(DAY_OF_THE_MONTH_LAYOUT + viewIndex);
dayOfTheMonthText.setTag(DAY_OF_THE_MONTH_TEXT + viewIndex);
dayOfTheMonthBackground.setTag(DAY_OF_THE_MONTH_BACKGROUND + viewIndex);
dayOfTheMonthCircleImage1.setTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_1 + viewIndex);
dayOfTheMonthCircleImage2.setTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_2 + viewIndex);
dayOfTheMonthCircleImage3.setTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_3 + viewIndex);
dayOfTheMonthCircleImage4.setTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_4 + viewIndex);
dayOfTheMonthCircleImage5.setTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_5 + viewIndex);
dayOfTheWeekLayout.addView(dayOfTheMonthLayout);
// Log.e("circle iv tag", dayOfTheMonthCircleImage1.getTag().toString()+"..");
}
}
private void setUpEventListeners() {
leftButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (robotoCalendarListener == null) {
throw new IllegalStateException("You must assign a valid RobotoCalendarListener first!");
}
// Decrease month
currentCalendar.add(Calendar.MONTH, -1);
Log.e("currentMonthvv",currentCalendar.toString());
lastSelectedDayCalendar = null;
updateView();
robotoCalendarListener.onLeftButtonClick();
}
});
rightButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (robotoCalendarListener == null) {
throw new IllegalStateException("You must assign a valid RobotoCalendarListener first!");
}
// Increase month
currentCalendar.add(Calendar.MONTH, 1);
lastSelectedDayCalendar = null;
updateView();
robotoCalendarListener.onRightButtonClick();
}
});
}
// ************************************************************************************************************************************************************************
// * Auxiliary UI methods
// ************************************************************************************************************************************************************************
private void setUpMonthLayout() {
dateText = new DateFormatSymbols(Locale.getDefault()).getMonths()[currentCalendar.get(Calendar.MONTH)];
dateText = dateText.substring(0, 1).toUpperCase() + dateText.subSequence(1, dateText.length());
Calendar calendar = Calendar.getInstance();
if (currentCalendar.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)) {
dateTitle.setText(dateText);
} else {
dateTitle.setText(String.format("%s %s", dateText, currentCalendar.get(Calendar.YEAR)));
}
}
private void setUpWeekDaysLayout() {
TextView dayOfWeek;
String dayOfTheWeekString;
startweek = Utility.getSharedPreferences(context.getApplicationContext(), "startWeek");
if(startweek.equals("Sunday")){
weekDaysArray = new DateFormatSymbols(Locale.getDefault()).getWeekdays();
}else if(startweek.equals("Monday")){
weekDaysArray = new String[] {"", context.getApplicationContext().getString(R.string.monday), context.getApplicationContext().getString(R.string.tuesday), context.getApplicationContext().getString(R.string.wednesday), context.getApplicationContext().getString(R.string.thursday), context.getApplicationContext().getString(R.string.friday), context.getApplicationContext().getString(R.string.saturday), context.getApplicationContext().getString(R.string.sunday) };
}else if(startweek.equals("Tuesday")){
weekDaysArray = new String[] {"", context.getApplicationContext().getString(R.string.tuesday), context.getApplicationContext().getString(R.string.wednesday), context.getApplicationContext().getString(R.string.thursday), context.getApplicationContext().getString(R.string.friday), context.getApplicationContext().getString(R.string.saturday), context.getApplicationContext().getString(R.string.sunday), context.getApplicationContext().getString(R.string.monday) };
}else if(startweek.equals("Wednesday")){
weekDaysArray = new String[] {"", context.getApplicationContext().getString(R.string.wednesday), context.getApplicationContext().getString(R.string.thursday), context.getApplicationContext().getString(R.string.friday), context.getApplicationContext().getString(R.string.saturday), context.getApplicationContext().getString(R.string.sunday), context.getApplicationContext().getString(R.string.monday), context.getApplicationContext().getString(R.string.tuesday) };
}else if(startweek.equals("Thursday")){
weekDaysArray = new String[] {"", context.getApplicationContext().getString(R.string.thursday), context.getApplicationContext().getString(R.string.friday), context.getApplicationContext().getString(R.string.saturday), context.getApplicationContext().getString(R.string.sunday), context.getApplicationContext().getString(R.string.monday), context.getApplicationContext().getString(R.string.tuesday), context.getApplicationContext().getString(R.string.wednesday) };
}else if(startweek.equals("Friday")){
weekDaysArray = new String[] {"", context.getApplicationContext().getString(R.string.friday), context.getApplicationContext().getString(R.string.saturday), context.getApplicationContext().getString(R.string.sunday), context.getApplicationContext().getString(R.string.monday), context.getApplicationContext().getString(R.string.tuesday), context.getApplicationContext().getString(R.string.wednesday), context.getApplicationContext().getString(R.string.thursday) };
}else if(startweek.equals("Saturday")){
weekDaysArray = new String[] {"", context.getApplicationContext().getString(R.string.saturday), context.getApplicationContext().getString(R.string.sunday), context.getApplicationContext().getString(R.string.monday), context.getApplicationContext().getString(R.string.tuesday), context.getApplicationContext().getString(R.string.wednesday), context.getApplicationContext().getString(R.string.thursday), context.getApplicationContext().getString(R.string.friday) };
}else if(startweek.equals("")){
weekDaysArray = new DateFormatSymbols(Locale.getDefault()).getWeekdays();
}
for (int i = 1; i < weekDaysArray.length; i++) {
dayOfWeek = (TextView) rootView.findViewWithTag(DAY_OF_THE_WEEK_TEXT + getWeekIndex(i, currentCalendar));
dayOfTheWeekString = weekDaysArray[i];
System.out.println("weekDaysArray["+i+"]"+dayOfTheWeekString);
if (shortWeekDays) {
dayOfTheWeekString = checkSpecificLocales(dayOfTheWeekString, i);
} else {
dayOfTheWeekString = dayOfTheWeekString.substring(0, 1).toUpperCase() + dayOfTheWeekString.substring(1, 3);
System.out.println("dayOfTheWeekString==" + dayOfTheWeekString);
}
dayOfWeek.setText(dayOfTheWeekString);
}
}
private void setUpDaysOfMonthLayout() {
TextView dayOfTheMonthText;
View circleImage1;
View circleImage2;
View circleImage3;
View circleImage4;
View circleImage5;
ViewGroup dayOfTheMonthContainer;
ViewGroup dayOfTheMonthBackground;
for (int i = 1; i < 43; i++) {
dayOfTheMonthContainer = (ViewGroup) rootView.findViewWithTag(DAY_OF_THE_MONTH_LAYOUT + i);
dayOfTheMonthBackground = (ViewGroup) rootView.findViewWithTag(DAY_OF_THE_MONTH_BACKGROUND + i);
dayOfTheMonthText = (TextView) rootView.findViewWithTag(DAY_OF_THE_MONTH_TEXT + i);
circleImage1 = rootView.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_1 + i);
circleImage2 = rootView.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_2 + i);
circleImage3 = rootView.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_3 + i);
circleImage4 = rootView.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_4 + i);
circleImage5 = rootView.findViewWithTag(DAY_OF_THE_MONTH_CIRCLE_IMAGE_5 + i);
dayOfTheMonthText.setVisibility(View.INVISIBLE);
circleImage1.setVisibility(View.GONE);
circleImage2.setVisibility(View.GONE);
circleImage3.setVisibility(View.GONE);
circleImage4.setVisibility(View.GONE);
circleImage5.setVisibility(View.GONE);
// Apply styles
dayOfTheMonthText.setBackgroundResource(android.R.color.transparent);
dayOfTheMonthText.setTypeface(null, Typeface.NORMAL);
dayOfTheMonthText.setTextColor(ContextCompat.getColor(context, R.color.roboto_calendar_day_of_the_month_font));
dayOfTheMonthContainer.setBackgroundResource(android.R.color.transparent);
dayOfTheMonthContainer.setOnClickListener(null);
dayOfTheMonthBackground.setBackgroundResource(android.R.color.transparent);
}
}
private void setUpDaysInCalendar() {
Calendar auxCalendar = Calendar.getInstance(Locale.getDefault());
auxCalendar.setTime(currentCalendar.getTime());
auxCalendar.set(Calendar.DAY_OF_MONTH, 1);
// int firstDayOfMonth = auxCalendar.get(Calendar.DAY_OF_WEEK);
int firstDayOfMonth = auxCalendar.get(Calendar.DAY_OF_WEEK);
if(startweek.equals("Sunday")){
firstDayOfMonth=firstDayOfMonth;
}else if(startweek.equals("Monday")){
if(firstDayOfMonth==1){
firstDayOfMonth=firstDayOfMonth+6;
}else{
firstDayOfMonth=firstDayOfMonth-1;
}
}else if(startweek.equals("Tuesday")){
if(firstDayOfMonth==1){
firstDayOfMonth=firstDayOfMonth+5;
}else if(firstDayOfMonth==2){
firstDayOfMonth=firstDayOfMonth+5;
}else{
firstDayOfMonth=firstDayOfMonth-2;
}
}else if(startweek.equals("Wednesday")){
if(firstDayOfMonth==1){
firstDayOfMonth=firstDayOfMonth+4;
}else if(firstDayOfMonth==2){
firstDayOfMonth=firstDayOfMonth+4;
}else if(firstDayOfMonth==3){
firstDayOfMonth=firstDayOfMonth+4;
}else{
firstDayOfMonth=firstDayOfMonth-3;
}
}else if(startweek.equals("Thursday")){
firstDayOfMonth=firstDayOfMonth+3;
}else if(startweek.equals("Friday")){
firstDayOfMonth=firstDayOfMonth+2;
}else if(startweek.equals("Saturday")){
firstDayOfMonth=firstDayOfMonth+1;
}
TextView dayOfTheMonthText;
ViewGroup dayOfTheMonthContainer;
ViewGroup dayOfTheMonthLayout;
// Calculate dayOfTheMonthIndex
int dayOfTheMonthIndex = getWeekIndex(firstDayOfMonth, auxCalendar);
for (int i = 1; i <= auxCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++, dayOfTheMonthIndex++) {
dayOfTheMonthContainer = (ViewGroup) rootView.findViewWithTag(DAY_OF_THE_MONTH_LAYOUT + dayOfTheMonthIndex);
dayOfTheMonthText = (TextView) rootView.findViewWithTag(DAY_OF_THE_MONTH_TEXT + dayOfTheMonthIndex);
if (dayOfTheMonthText == null) {
break;
}
dayOfTheMonthContainer.setOnClickListener(onDayOfMonthClickListener);
dayOfTheMonthContainer.setOnLongClickListener(onDayOfMonthLongClickListener);
dayOfTheMonthText.setVisibility(View.VISIBLE);
dayOfTheMonthText.setText(String.valueOf(i));
}
for (int i = 36; i < 43; i++) {
dayOfTheMonthText = (TextView) rootView.findViewWithTag(DAY_OF_THE_MONTH_TEXT + i);
dayOfTheMonthLayout = (ViewGroup) rootView.findViewWithTag(DAY_OF_THE_MONTH_LAYOUT + i);
if (dayOfTheMonthText.getVisibility() == INVISIBLE) {
dayOfTheMonthLayout.setVisibility(GONE);
} else {
dayOfTheMonthLayout.setVisibility(VISIBLE);
}
}
}
private void markDayAsCurrentDay() {
// If it's the current month, mark current day
Calendar nowCalendar = Calendar.getInstance();
if (nowCalendar.get(Calendar.YEAR) == currentCalendar.get(Calendar.YEAR) && nowCalendar.get(Calendar.MONTH) == currentCalendar.get(Calendar.MONTH)) {
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(nowCalendar.getTime());
ViewGroup dayOfTheMonthBackground = getDayOfMonthBackground(currentCalendar);
dayOfTheMonthBackground.setBackgroundResource(R.drawable.ring);
}
}
private void markDayAsSelectedDay(Calendar calendar) {
// Clear previous current day mark
clearSelectedDay(lastSelectedDayCalendar);
// Store current values as last values
lastSelectedDayCalendar = calendar;
// Mark current day as selected
ViewGroup dayOfTheMonthBackground = getDayOfMonthBackground(calendar);
dayOfTheMonthBackground.setBackgroundResource(R.drawable.circle_blue);
TextView dayOfTheMonth = getDayOfMonthText(calendar);
dayOfTheMonth.setTextColor(ContextCompat.getColor(context, R.color.roboto_calendar_selected_day_font));
ImageView circleImage1 = getCircleImage1(calendar);
ImageView circleImage2 = getCircleImage2(calendar);
ImageView circleImage3 = getCircleImage3(calendar);
ImageView circleImage4 = getCircleImage3(calendar);
ImageView circleImage5 = getCircleImage3(calendar);
if (circleImage1.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage1.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_selected_day_font));
}
if (circleImage2.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage2.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_selected_day_font));
}
if (circleImage3.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage3.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_selected_day_font));
}
if (circleImage4.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage4.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_selected_day_font));
}
if (circleImage5.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage5.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_selected_day_font));
}
}
private void clearSelectedDay(Calendar calendar) {
if (calendar != null) {
ViewGroup dayOfTheMonthBackground = getDayOfMonthBackground(calendar);
// If it's today, keep the current day style
Calendar nowCalendar = Calendar.getInstance();
if (nowCalendar.get(Calendar.YEAR) == lastSelectedDayCalendar.get(Calendar.YEAR) && nowCalendar.get(Calendar.DAY_OF_YEAR) == lastSelectedDayCalendar.get(Calendar.DAY_OF_YEAR)) {
dayOfTheMonthBackground.setBackgroundResource(R.drawable.ring);
} else {
dayOfTheMonthBackground.setBackgroundResource(android.R.color.transparent);
}
TextView dayOfTheMonth = getDayOfMonthText(calendar);
dayOfTheMonth.setTextColor(ContextCompat.getColor(context, R.color.roboto_calendar_day_of_the_month_font));
ImageView circleImage1 = getCircleImage1(calendar);
ImageView circleImage2 = getCircleImage2(calendar);
ImageView circleImage3 = getCircleImage3(calendar);
ImageView circleImage4 = getCircleImage3(calendar);
ImageView circleImage5 = getCircleImage3(calendar);
if (circleImage1.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage1.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_circle_1));
}
if (circleImage2.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage2.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_circle_2));
}
if (circleImage3.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage3.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_circle_3));
}
if (circleImage4.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage4.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_circle_4));
}
if (circleImage5.getVisibility() == VISIBLE) {
DrawableCompat.setTint(circleImage5.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_circle_5));
}
}
}
private String checkSpecificLocales(String dayOfTheWeekString, int i) {
// Set Wednesday as "X" in Spanish Locale.getDefault()
if (i == 4 && Locale.getDefault().getCountry().equals("ES")) {
dayOfTheWeekString = "X";
} else {
dayOfTheWeekString = dayOfTheWeekString.substring(0, 1).toUpperCase();
}
return dayOfTheWeekString;
}
// ************************************************************************************************************************************************************************
// * Public calendar methods
// ************************************************************************************************************************************************************************
/**
* Set an specific calendar to the view
*
* #param calendar
*/
public void setCalendar(Calendar calendar) {
this.currentCalendar = calendar;
updateView();
}
/**
* Update the calendar view
*/
public void updateView() {
setUpMonthLayout();
setUpWeekDaysLayout();
setUpDaysOfMonthLayout();
setUpDaysInCalendar();
markDayAsCurrentDay();
}
public void setShortWeekDays(boolean shortWeekDays) {
this.shortWeekDays = shortWeekDays;
}
/**
* Clear the view of marks and selections
*/
public void clearCalendar() {
updateView();
}
public void markCircleImage1(Calendar calendar) {
ImageView circleImage1 = getCircleImage1(calendar);
circleImage1.setVisibility(View.VISIBLE);
DrawableCompat.setTint(circleImage1.getDrawable(), ContextCompat.getColor(context, R.color.roboto_calendar_circle_1));
ViewGroup dayOfTheMonthBackground = getDayOfMonthBackground(calendar);
// dayOfTheMonthBackground.setBackgroundResource(R.drawable.circle_blue);
}
}
In your onCreateView() try replacing getSystemService() with getLayoutInflator()
I have a cart that can insert only one product at a time, but now i have to insert more than one product at a time. I use check boxes to select the items.
What do I need to change to allow inserting more than one product into the cart?
This is my Adapter Class :
public class AdapterPrice extends BaseAdapter {
ArrayList<ModelPrice> listPrice;
private Context context;
int selectedPosition = 0;
public AdapterPrice(Context context, ArrayList<ModelPrice> listPrice) {
this.context = context;
this.listPrice = listPrice;
}
#Override
public int getCount() {
return listPrice.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup viewGroup) {
final AdapterPrice.ViewHolder holder;
if (view == null) {
holder = new AdapterPrice.ViewHolder();
view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.item_packing, null);
holder.txtOffer = view.findViewById(R.id.txtOffer);
holder.txtPrice = view.findViewById(R.id.txtPrice);
holder.txtQty = view.findViewById(R.id.txtQty);
//holder.radioWeight = view.findViewById(R.id.radioWeight);
holder.checkBox = view.findViewById(R.id.checkboxWeight);
holder.icMinus = view.findViewById(R.id.icMinus);
holder.icPlus = view.findViewById(R.id.icPlus);
view.setTag(holder);
} else {
holder = (AdapterPrice.ViewHolder) view.getTag();
}
//holder.radioWeight.setText((UtilMethods.decimalFormater(listPrice.get(position).getWeight())) + listPrice.get(position).getUnit());
holder.checkBox.setText((UtilMethods.decimalFormater(listPrice.get(position).getWeight())) + listPrice.get(position).getUnit());
double packMrpd = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
double offerMrpd = (double) listPrice.get(position).getQty() * listPrice.get(position).getSellMrp();
holder.txtPrice.setText("Rs." + UtilMethods.decimalFormater(packMrpd));
holder.txtOffer.setText("Rs." + UtilMethods.decimalFormater(offerMrpd));
holder.txtQty.setText(listPrice.get(position).getQty() + "");
/*holder.radioWeight.setChecked(position == selectedPosition);
holder.radioWeight.setTag(position);*/
holder.checkBox.setChecked(position == selectedPosition);
Log.d("POSITION CB>>>>>>",position+"");
//holder.checkBox.setTag(position);
if (holder.checkBox.isChecked()) {
String forString = "for " + UtilMethods.decimalFormater(listPrice.get(selectedPosition).getWeight()) + "" + listPrice.get(selectedPosition).getUnit();
SpannableString forStr = new SpannableString(forString);
forStr.setSpan(new UnderlineSpan(), 0, forString.length(), 0);
//txtFor.setText(forStr);
//txtOferPrice.setText("Rs." + UtilMethods.decimalFormater(listPrice.get(selectedPosition).getSellMrp()) + "");
double saveMrp = ((double) listPrice.get(position).getQty() * listPrice.get(position).getMrp()) - ((double) listPrice.get(position).getQty() * listPrice.get(position).getSellMrp());
txtSAve.setText("Rs." + (UtilMethods.decimalFormater(saveMrp)) + "");
if (saveMrp <= 0) {
offerLayout.setVisibility(View.GONE);
}
mQty = listPrice.get(position).getQty();
mMrp = listPrice.get(position).getMrp();
mSellMrp = listPrice.get(position).getSellMrp();
mweight = listPrice.get(position).getWeight();
mUnit = listPrice.get(position).getUnit();
seletUnit = (1 * selectedPosition);
}
/*holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
notifyDataSetChanged();
}
});*/
holder.icMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int cQty = listPrice.get(position).getQty();
if (cQty > 1) {
cQty = listPrice.get(position).getQty() - 1;
listPrice.get(position).setQty(cQty);
// double totalMrp = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
//holder.txtPrice.setText((String.format("%.2f", totalMrp)) + "");
/* if (position == selectedPosition) {
double saveMrp = totalMrp - (listPrice.get(selectedPosition).getSellMrp() * (double) listPrice.get(position).getQty());
// txtSAve.setText("Rs."+saveMrp + "");
}*/
notifyDataSetChanged();
}
}
});
holder.icPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int cQty = listPrice.get(position).getQty();
cQty = listPrice.get(position).getQty() + 1;
listPrice.get(position).setQty(cQty);
//double totalMrp = (double) listPrice.get(position).getQty() * listPrice.get(position).getMrp();
// holder.txtPrice.setText((String.format("%.2f", totalMrp)) + "");
/* if (position == selectedPosition) {
double saveMrp = totalMrp - (listPrice.get(selectedPosition).getSellMrp() * (double) listPrice.get(position).getQty());
// txtSAve.setText(saveMrp + "");
}*/
notifyDataSetChanged();
}
});
return view;
}
public class ViewHolder {
private TextView txtPrice, txtQty, txtOffer;
private RadioButton radioWeight;
CheckBox checkBox;
private ImageView icPlus, icMinus;
}
}
this is where i insert item into cart through SQLIte :
private void addToCArt() {
ModelCart mcart = new ModelCart();
mcart.setProductName(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getProductName());
mcart.setPid(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getPid());
mcart.setImageUrl(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getImageTag1());
List<String> attrId = new ArrayList<>();
for (ModelPrice mmp : Config.LIST_SINGAL_PRODUCT.get(tempPosition).getListPrice()) {
attrId.add(mmp.getWid() + "," + mmp.getWeight() + "," + mmp.getUnit());
}
String aData = TextUtils.join("-", attrId);
mcart.setQty(mQty);
mcart.setWeight(mweight);
mcart.setUnit(mUnit);
mcart.setMrp(mMrp);
mcart.setSellMrp(mSellMrp);
mcart.setAttributeData(aData);
mcart.setSelectUnit(seletUnit);
mcart.setSelecAttrId((Config.LIST_SINGAL_PRODUCT.get(tempPosition).getListPrice()).get(seletUnit).getWid());
db.insetCArt(mcart);
/*int isQty = db.isProduct(Config.LIST_SINGAL_PRODUCT.get(tempPosition).getPid());
if (isQty != -1 && isQty != 0) {
int tQ = mQty + isQty;
mcart.setQty(tQ);
db.updateCart(mcart);
} else {
db.insetCArt(mcart);
}*/
/*CartFragment orderFrg = new CartFragment();
Bundle args = new Bundle();
orderFrg.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.frmae, orderFrg).addToBackStack(null).commit();
*/
}
I'm trying to show multiple Images inside of List View Item. All Data perfectoly set but When I'm showing multiple images inside of List View Item it show perfectoly when it create but after scrolling the page it show me double images inside of list view item. I'm programmatically create ImageView and add in Linear Layout. Also how to get that ImageView position. I attach Images below. How to fix this bug
This is my Adapter code.
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
final ApproveReimbBin item = getItem(position);
FoldingCell cell = (FoldingCell) convertView;
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();
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 (childDocument.length > 0) {
for (int i = 0; i < childDocument.length; i++) {
String doc = childDocument[i].replace("~", "");
doc = doc.replace(",", "");
image = new ImageView(mContext);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80, 60));
image.setMaxHeight(50);
image.setMaxWidth(50);
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);
}
} else {
viewHolder.linearLayout.setVisibility(View.GONE);
}
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;
}
This is my Json
[ { "documents": [
"~\\Upload\\10 Nov 2017\\KB94L636459349491385669.jpg,"
],
"username": "Pranav Khanvilkar",
"empcode": "313395",
"type": "TRAIN / BUS PASS",
"startEndDate": "03-Nov-2017 To 02-Dec-2017",
"requestid": "1916",
"amount": "265",
"reimbursementid": "3",
"applyDate": "11/10/2017 6:22:29 PM" }, {
"documents": [
"~\\Upload\\07 Apr 2018\\XHKZU636586950672544266.jpg,",
"~\\Upload\\07 Apr 2018\\2V44D636586950672674273.jpg,"
],
"username": "Anil Pawar",
"empcode": "313325",
"type": "SALES VISIT",
"startEndDate": "05-Apr-2018 To 06-Apr-2018",
"requestid": "8448",
"amount": "400",
"reimbursementid": "4",
"applyDate": "4/7/2018 10:51:04 AM" }]
This is I'm getting issue.
Before Scrolling Page.
After Scrolling Page.
Use below code before your for loop.
if (viewHolder.linearLayout..getChildCount()>0)
viewHolder.linearLayout.removeAllViews();
and after call this for loop
if (childDocument.length > 0) {
for (int i = 0; i < childDocument.length; i++) {
String doc = childDocument[i].replace("~", "");
doc = doc.replace(",", "");
image = new ImageView(mContext);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80, 60));
image.setMaxHeight(50);
image.setMaxWidth(50);
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);
}
} else {
viewHolder.linearLayout.setVisibility(View.GONE);
}
Call this
viewHolder.linearLayout.removeAllViews();
before your for loop.
for (int i = 0; i < childDocument.length; i++) {
...
}
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....
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.