I need help on how to go about and make prev month's days visible (grayed out) on this calendar.
I am getting a present months view here.. but as you can see the previous months days are not visible.I know why.. but how to go about it? also few bugs are there in this present one as well.please help.Posting the code for the custom adapter class:
CalendarAdapter.java
import java.util.ArrayList;
import java.util.Calendar;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CalendarAdapter extends BaseAdapter {
static final int FIRST_DAY_OF_WEEK =0; // Sunday = 0, Monday = 1
private Context mContext;
private java.util.Calendar month;
private Calendar selectedDate;
private ArrayList<String> items;
public CalendarAdapter(Context c, Calendar monthCalendar) {
month = monthCalendar;
selectedDate = (Calendar)monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
refreshDays();
}
public void setItems(ArrayList<String> items) {
for(int i = 0;i != items.size();i++){
if(items.get(i).length()==1) {
items.set(i, "0" + items.get(i));
}
}
this.items = items;
}
public int getCount() {
return days.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.calendar_item, null);
}
dayView = (TextView)v.findViewById(R.id.date);
// disable empty days from the beginning
if(days[position].equals("")) {
dayView.setClickable(false);
dayView.setFocusable(false);
//need to show previous months date
}
else {
// mark current day as focused
if(month.get(Calendar.YEAR)== selectedDate.get(Calendar.YEAR) && month.get(Calendar.MONTH)== selectedDate.get(Calendar.MONTH) && days[position].equals(""+selectedDate.get(Calendar.DAY_OF_MONTH))) {
v.setBackgroundResource(R.drawable.date_area);
dayView.setTextColor(Color.parseColor("#FFFFFF"));
}
else {
v.setBackgroundResource(R.drawable.current_date_area);
}
}
dayView.setText(days[position]);
// create date string for comparison
String date = days[position];
if(date.length()==1) {
date = "0"+date;
}
String monthStr = ""+(month.get(Calendar.MONTH)+1);
if(monthStr.length()==1) {
monthStr = "0"+monthStr;
}
// show icon if date is not empty and it exists in the items array
/* ImageView iw = (ImageView)v.findViewById(R.id.date_icon);
if(date.length()>0 && items!=null && items.contains(date)) {
iw.setVisibility(View.VISIBLE);
}
else {
iw.setVisibility(View.INVISIBLE);
}*/
return v;
}
public void refreshDays()
{
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
// figure size of the array
if(firstDay==1){
days = new String[lastDay+(FIRST_DAY_OF_WEEK*6)];
}
else {
days = new String[lastDay+firstDay-(FIRST_DAY_OF_WEEK+1)];
}
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay>1) {
for(j=0;j<firstDay-FIRST_DAY_OF_WEEK;j++) {
days[j] = "";
}
}
else {
for(j=0;j<FIRST_DAY_OF_WEEK*6;j++) {
days[j] = "";
}
j=FIRST_DAY_OF_WEEK*6+1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
for(int i=j-1;i<days.length;i++) {
days[i] = ""+dayNumber;
dayNumber++;
}
}
// references to our items
public String[] days;}
and this is the Activity code on how i am using this adapter:
CalendarView.java
/*some code above*/
/*this is in the OnCreate block*/
adapter = new CalendarAdapter(this, month);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);
/*some code below*/
and heres my calendar view screen (grid):
CalendarView Screenshot:
To be straight and to the point,All i want is that blank boxes before 1st of the month be filled in with the previous month's last week's days
Declare another calendar
private java.util.Calendar month, prevMonth;
Add a clone to calendar in the constructor
prevMonth = (Calendar) month.clone();
prevMonth.roll(Calendar.MONTH, false);
Then replace the refreshDays with this one.This fills up the blank spaces with the days from the last month and the next month for the first and last week of the current month respectively.
public void refreshDays() {
// clear items
items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int) month.get(Calendar.DAY_OF_WEEK);
int maxweek = month.getActualMaximum(Calendar.WEEK_OF_MONTH);
Log.d("CalendarAdapter", String.valueOf(maxweek));
// figure size of the array
/*
* if (firstDay == 1) { days = new String[lastDay + (FIRST_DAY_OF_WEEK *
* 6)]; }
*
* else { days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK +
* 1)]; }
*/
days = new String[maxweek * 7];
int j = FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if (firstDay > 1) {
// can be made a bit faster if implemented without this following
// for loop for roll
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
prevMonth.roll(Calendar.DAY_OF_MONTH, false);
Log.d("CalendarAdapter",
"roll block: " + prevMonth.get(Calendar.DAY_OF_MONTH));
}
for (j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++) {
// days[j] = "";
prevMonth.roll(Calendar.DAY_OF_MONTH, true);
int dayPrev = prevMonth.get(Calendar.DAY_OF_MONTH);
days[j] = " " + String.valueOf(dayPrev) + " ";
Log.d("CalendarAdapter", "calculation:J if firstDay>1 -- " + j
+ " roll gives:" + dayPrev);
}
} else {
for (j = 0; j < FIRST_DAY_OF_WEEK * 6; j++) {
days[j] = "";
Log.d("CalendarAdapter", "calculation:J if firstDay<1 -- " + j);
}
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}
// populate days
int dayNumber = 1;
boolean flag = false;
for (int i = j - 1; i < days.length; i++) {
days[i] = String.valueOf(dayNumber).trim() + ".";
if (flag)
days[i] = String.valueOf(dayNumber).trim();
if (dayNumber == lastDay) {
dayNumber = 0;
flag=true;
}
dayNumber++;
}
}
// references to our items
public String[] days;
}
Related
This is my code my problem is this . in calendar view pager adapter i am 5000 page but offScreenPage limit is 1 and I have 3 pages in on time but view pager is not smoth scroll and has bad performance. when I remove this line from Calendar fragment view pager smooth scroll fine. but I dont know what is the problem.
gregorianCal = new GregorianCalendar(persianCal);
IslamicCalendar islamicCal = new IslamicCalendar(persianCal);
///////////////////////////////////////////////
for (int i = 0; i < persianCal.getNumberOfDaysInMonth(); i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = persianCal.getWeekDay();
//////set month names/////////////
dateCalendar.shamsiMonthName = persianCal.getMonthName();
dateCalendar.hejriMonthName = islamicCal.getMonthName();
dateCalendar.gregorianMonthName = gregorianCal.getMonthName();
//////set persian calendar/////
dateCalendar.shamsiDayNumber = persianCal.getDay();
dateCalendar.shamsiMonthNumber = persianCal.getMonth();
dateCalendar.shamsiYearNumber = persianCal.getYear();
//////set islamic calendar/////
dateCalendar.hejriDayNumber = islamicCal.getDay();
dateCalendar.hejriMonthNumber = islamicCal.getMonth();
dateCalendar.hejriYearNumber = islamicCal.getYear();
//////set gregorian calendar/////
dateCalendar.gregorianDayNumber = gregorianCal.getDay();
dateCalendar.gregorianMonthNumber = gregorianCal.getMonth();
dateCalendar.gregorianYearNumber = gregorianCal.getYear();
///////select current day of Month
if (persianCal.getDay() == currentPersianCal.getDay() && persianCal.getMonth() == currentPersianCal.getMonth() && persianCal.getYear() == currentPersianCal.getYear()) {
dateCalendar.isCurrentDay = true;
dateCalendar.isDaySelected = true;
}
///////add days of current month//////
dateCalendarList.add(dateCalendar);
if (i < persianCal.getNumberOfDaysInMonth() - 1) {
persianCal.nextDay();
gregorianCal.nextDay();
islamicCal.nextDay();
}
}
I search a lot of similar subject of viewPager but I not found soultion for it.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.example.moein.mycalendar.R;
import com.example.moein.mycalendar.myCalendar_adapter.GridAdapter1;
import com.example.moein.mycalendar.myCalendar_library.date.GregorianCalendar;
import com.example.moein.mycalendar.myCalendar_library.date.IslamicCalendar;
import com.example.moein.mycalendar.myCalendar_library.date.PersianCalendar;
import com.example.moein.mycalendar.myCalendar_library.util.Operations;
import com.example.moein.mycalendar.myCalendar_model.DateCalendar;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
/**
* Created by Moein on 9/16/2017.
*/
public class CalendarFragment extends Fragment {
private int year;
private int month;
private int day;
// newInstance constructor for creating fragment with arguments
public static CalendarFragment newInstance(int year, int month, int day) {
CalendarFragment calendarFragment = new CalendarFragment();
Bundle args = new Bundle();
args.putInt("year", year);
args.putInt("month", month);
args.putInt("day", day);
calendarFragment.setArguments(args);
return calendarFragment;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
year = getArguments().getInt("year");
month = getArguments().getInt("month");
day = getArguments().getInt("day");
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar, container, false);
TextView yearAndMonth = view.findViewById(R.id.yearAndMonth);
GridView gridView = view.findViewById(R.id.gridCalendar);
/////set timeZone Asia/Tehran and set current calendar///////////////////////////////
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
GregorianCalendar currentGregorianCal = new GregorianCalendar(calendar);
PersianCalendar currentPersianCal = new PersianCalendar(currentGregorianCal);
GregorianCalendar gregorianCal = new GregorianCalendar(year, month, day);
PersianCalendar persianCal = new PersianCalendar(gregorianCal);
/////////add weekDay names to the list of gridAdapter///////
String[] weekDays = getResources().getStringArray(R.array.weekDays);
List<DateCalendar> dateCalendarList = new ArrayList<>();
for (String weekDay : weekDays) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = weekDay;
dateCalendarList.add(dateCalendar);
}
//set title of calendar/////////
yearAndMonth.setText(persianCal.getMonthName() + " " + Operations.toPersianNumber(String.valueOf(persianCal.getYear())));
///Back to the beginning of the month
persianCal.subtractDays(persianCal.getDay() - 1);
//////add empty days to the beginning of the month
int lengthOfEmptyDays = 0;
switch (persianCal.getWeekDay()) {
case "شنبه":
lengthOfEmptyDays = 0;
break;
case "یکشنبه":
lengthOfEmptyDays = 1;
break;
case "دوشنبه":
lengthOfEmptyDays = 2;
break;
case "سه\u200Cشنبه":
lengthOfEmptyDays = 3;
break;
case "چهارشنبه":
lengthOfEmptyDays = 4;
break;
case "پنج\u200Cشنبه":
lengthOfEmptyDays = 5;
break;
case "جمعه":
lengthOfEmptyDays = 6;
break;
}
for (int i = 0; i < lengthOfEmptyDays; i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.isEmpty = true;
dateCalendarList.add(dateCalendar);
}
gregorianCal = new GregorianCalendar(persianCal);
IslamicCalendar islamicCal = new IslamicCalendar(persianCal);
///////////////////////////////////////////////
for (int i = 0; i < persianCal.getNumberOfDaysInMonth(); i++) {
DateCalendar dateCalendar = new DateCalendar();
dateCalendar.nameOFDay = persianCal.getWeekDay();
//////set month names/////////////
dateCalendar.shamsiMonthName = persianCal.getMonthName();
dateCalendar.hejriMonthName = islamicCal.getMonthName();
dateCalendar.gregorianMonthName = gregorianCal.getMonthName();
//////set persian calendar/////
dateCalendar.shamsiDayNumber = persianCal.getDay();
dateCalendar.shamsiMonthNumber = persianCal.getMonth();
dateCalendar.shamsiYearNumber = persianCal.getYear();
//////set islamic calendar/////
dateCalendar.hejriDayNumber = islamicCal.getDay();
dateCalendar.hejriMonthNumber = islamicCal.getMonth();
dateCalendar.hejriYearNumber = islamicCal.getYear();
//////set gregorian calendar/////
dateCalendar.gregorianDayNumber = gregorianCal.getDay();
dateCalendar.gregorianMonthNumber = gregorianCal.getMonth();
dateCalendar.gregorianYearNumber = gregorianCal.getYear();
///////select current day of Month
if (persianCal.getDay() == currentPersianCal.getDay() && persianCal.getMonth() == currentPersianCal.getMonth() && persianCal.getYear() == currentPersianCal.getYear()) {
dateCalendar.isCurrentDay = true;
dateCalendar.isDaySelected = true;
}
///////add days of current month//////
dateCalendarList.add(dateCalendar);
if (i < persianCal.getNumberOfDaysInMonth() - 1) {
persianCal.nextDay();
gregorianCal.nextDay();
islamicCal.nextDay();
}
}
gridView.setAdapter(new GridAdapter1(getActivity(), dateCalendarList));
return view;
}
}
public class CalendarViewPagerAdapter extends FragmentStatePagerAdapter{
private GregorianCalendar centerGregorianCalendar;
private GregorianCalendar nextGregorianCalendar;
private GregorianCalendar prevGregorianCalendar;
private final int MAX = 5000;
public CalendarViewPagerAdapter(FragmentManager fm, GregorianCalendar centerGregorianCalendar, GregorianCalendar nextGregorianCalendar, GregorianCalendar prevGregorianCalendar) {
super(fm);
this.centerGregorianCalendar = centerGregorianCalendar;
this.prevGregorianCalendar = prevGregorianCalendar;
this.nextGregorianCalendar = nextGregorianCalendar;
}
#Override
public Fragment getItem(int position) {
position = position % 3;
if (position == 0) {
return new CalendarFragment().newInstance(prevGregorianCalendar.getYear(), prevGregorianCalendar.getMonth(), prevGregorianCalendar.getDay());
} else if (position == 1) {
return new CalendarFragment().newInstance(centerGregorianCalendar.getYear(), centerGregorianCalendar.getMonth(), centerGregorianCalendar.getDay());
} else {
return new CalendarFragment().newInstance(nextGregorianCalendar.getYear(), nextGregorianCalendar.getMonth(), nextGregorianCalendar.getDay());
}
}
#Override
public int getCount() {
return MAX;
}
}
public class MainActivity extends AppCompatActivity {
private int[] CenterPage = {2500};
private CalendarViewPagerAdapter calendarViewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/////set timeZone Asia/Tehran///////////////////////////////
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
final GregorianCalendar gregorianCal = new GregorianCalendar(calendar);
final GregorianCalendar nextGregorianCal = new GregorianCalendar(calendar);
final GregorianCalendar prevGregorianCal = new GregorianCalendar(calendar);
if (gregorianCal.getMonth() == 12) {
nextGregorianCal.setMonth(1);
nextGregorianCal.setYear(nextGregorianCal.getYear() + 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() + 1);
}
if (gregorianCal.getMonth() == 1) {
prevGregorianCal.setMonth(12);
prevGregorianCal.setYear(prevGregorianCal.getYear() - 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() - 1);
}
final ViewPager calendarViewPager = findViewById(R.id.calendar_viewPager);
calendarViewPagerAdapter = new CalendarViewPagerAdapter(getSupportFragmentManager(), gregorianCal, nextGregorianCal, prevGregorianCal);
calendarViewPager.setAdapter(calendarViewPagerAdapter);
calendarViewPager.setOffscreenPageLimit(1);
calendarViewPager.setCurrentItem(2500);
calendarViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position < CenterPage[0]) {
switch (position % 3) {
case 0:
nextGregorianCal.set(prevGregorianCal);
if (nextGregorianCal.getMonth() == 1) {
nextGregorianCal.setMonth(12);
nextGregorianCal.setYear(nextGregorianCal.getYear() - 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() - 1);
}
break;
case 1:
prevGregorianCal.set(gregorianCal);
if (prevGregorianCal.getMonth() == 1) {
prevGregorianCal.setMonth(12);
prevGregorianCal.setYear(prevGregorianCal.getYear() - 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() - 1);
}
break;
case 2:
gregorianCal.set(nextGregorianCal);
if (gregorianCal.getMonth() == 1) {
gregorianCal.setMonth(12);
gregorianCal.setYear(gregorianCal.getYear() - 1);
} else {
gregorianCal.setMonth(gregorianCal.getMonth() - 1);
}
break;
}
} else if (position > CenterPage[0]) {
switch (position % 3) {
case 0:
gregorianCal.set(prevGregorianCal);
if (gregorianCal.getMonth() == 12) {
gregorianCal.setMonth(1);
gregorianCal.setYear(gregorianCal.getYear() + 1);
} else {
gregorianCal.setMonth(gregorianCal.getMonth() + 1);
}
break;
case 1:
nextGregorianCal.set(gregorianCal);
if (nextGregorianCal.getMonth() == 12) {
nextGregorianCal.setMonth(1);
nextGregorianCal.setYear(nextGregorianCal.getYear() + 1);
} else {
nextGregorianCal.setMonth(nextGregorianCal.getMonth() + 1);
}
break;
case 2:
prevGregorianCal.set(nextGregorianCal);
if (prevGregorianCal.getMonth() == 12) {
prevGregorianCal.setMonth(1);
prevGregorianCal.setYear(prevGregorianCal.getYear() + 1);
} else {
prevGregorianCal.setMonth(prevGregorianCal.getMonth() + 1);
}
break;
}
}
CenterPage[0] = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
i hope you can use this code
my site https://mohammadhosseinaref.ir
public static string PersianDayOfWeek(DayOfWeek dayOfWeek)
{
switch (dayOfWeek)
{
case DayOfWeek.Sunday:
return "یکشنبه";
case DayOfWeek.Monday:
return "دوشنبه";
case DayOfWeek.Tuesday:
return "سه شنبه";
case DayOfWeek.Wednesday:
return "چهار شنبه";
case DayOfWeek.Thursday:
return "پنج شنبه";
case DayOfWeek.Friday:
return "جمعه";
case DayOfWeek.Saturday:
return "شنبه";
default:
return null;
}
}
public static Dictionary<int, string> ListOfPersianDayOfMonth(int month, int years)
{
Dictionary<int, string> dicDays = new Dictionary<int, string>();
PersianCalendar p = new PersianCalendar();
var dates = Enumerable.Range(1, p.GetDaysInMonth(years, month))
.Select(day => ParsePersianToGorgian(years + "/" + month + "/" + day))
.ToList();
foreach (var item in dates)
{
var day = GeorgianToPersian(item.Value, ShowMode.OnlyDate);
dicDays.Add(int.Parse(day.Split('/')[2]), DayPersian(item.Value.DayOfWeek) + " " + day);
}
return dicDays;
}
I am creating calendar which contains events and I want to show total no of events on particular date. I am using
CalendarAdapter.java class. For showing total no. of events count (like notification bubble) on date I am using
Badge.java class. Now problem is that badge is apply on Calendars dates which current month is showing first,
after changing month then that badge is not remove from next month calendar.
Calendar Adapter:
package vyClean.wemecalendar.adapters;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import vyClean.wemecalendar.activity.Event1;
import vyClean.wemecalendar.util.BadgeView;
import vyClean.wemecalendar.util.BadgeView1;
import vyClean.wemecalendar.util.CalendarEvent;
import vyClean.wemecalendar.R;
import vyClean.wemecalendar.util.ToastMessage;
public class CalendarAdapter extends BaseAdapter {
private Context context;
private java.util.Calendar month;
public GregorianCalendar pmonth;
/*-----------calendar instance for previous month for getting complete view-------------------*/
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
public static TextView textno;
RelativeLayout cal_item_ll;
private ArrayList<String> items;
public static List<String> day_string;
private View previousView;
private View getView;
public ArrayList<CalendarEvent> event_calendar_arr;
public CalendarAdapter(Context context, GregorianCalendar monthCalendar, ArrayList<CalendarEvent> event_calendar_arr) {
this.event_calendar_arr = event_calendar_arr;
CalendarAdapter.day_string = new ArrayList<>();
Locale.setDefault(Locale.getDefault());
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
this.context = context;
month.set(GregorianCalendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
curentDateString = df.format(selectedDate.getTime());
refreshDays();
}
public int getCount() {
return day_string.size();
}
public Object getItem(int position) {
return day_string.get(position);
}
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
getView = convertView;
TextView dayView;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getView = vi.inflate(R.layout.cal_item, parent, false);
cal_item_ll = (RelativeLayout) getView.findViewById(R.id.cal_item_ll);
//textno = (TextView) getView.findViewById(R.id.textno);
}
dayView = (TextView) getView.findViewById(R.id.date);
String[] separatedTime = day_string.get(position).split("-");
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.GRAY);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.parseColor("#ff69b4"));
}
if (day_string.get(position).equals(curentDateString)) {
getView.setBackgroundColor(Color.CYAN);
} else {
getView.setBackgroundColor(Color.WHITE);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = day_string.get(position);
if (date.length() == 1) {
date = "0" + date;
}
String monthStr = "" + (month.get(GregorianCalendar.MONTH) + 1);
if (monthStr.length() == 1) {
monthStr = "0" + monthStr;
}
int len = CalendarEvent.event_calendar_arr.size();
HashSet<String> eventListSet1 = new HashSet<>();
int flag = 0;
for (int j = 0; j < len; j++) {
//textno.setTextColor(Color.WHITE);
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(j);
if (day_string.get(position).equals(cal_event.getEventFromDate())) {
eventListSet1.add(cal_event.getEventCateId());
flag = 1;
}
}
if (flag == 1) {
setEventView(getView, position, dayView, eventListSet1);
/*----------call badgeview here--------*/
/*----------call badgeview on linear layout (cal_item_ll) which is inside getview--------*/
BadgeView badge = new BadgeView(context, cal_item_ll);
badge.setText("1");
badge.show();
}
System.out.println("eventListSet1:" + eventListSet1);
return getView;
}
public View setSelected(View view, int pos) {
if (previousView != null) {
// previousView.setBackgroundColor(Color.CYAN);
previousView.setBackgroundColor(Color.WHITE);
}
view = previousView;
// view.setBackgroundColor(Color.CYAN);
int len = day_string.size();
if (len > pos) {
if (day_string.get(pos).equals(curentDateString)) {
} else {
previousView = view;
}
}
return view;
}
public void refreshDays() {
// clear items
items.clear();
day_string.clear();
Locale.setDefault(Locale.getDefault());
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(GregorianCalendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(GregorianCalendar.WEEK_OF_MONTH);
// allocating maximum row number for the gridview.
mnthlength = maxWeeknumber * 7;
maxP = getMaxP(); // previous month maximum day 31,30....
calMaxP = maxP - (firstDay - 1);// calendar offday starting 24,25 ...
//Calendar instance for getting a complete gridview including the three month's (previous,current,next) dates.
pmonthmaxset = (GregorianCalendar) pmonth.clone();
//setting the start date as previous month's required date.
pmonthmaxset.set(GregorianCalendar.DAY_OF_MONTH, calMaxP + 1);
// filling calendar gridview.
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(GregorianCalendar.DATE, 1);
System.out.println(" 214 itemvale :" + itemvalue);
day_string.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(GregorianCalendar.MONTH) == month
.getActualMinimum(GregorianCalendar.MONTH)) {
pmonth.set((month.get(GregorianCalendar.YEAR) - 1),
month.getActualMaximum(GregorianCalendar.MONTH), 1);
} else {
pmonth.set(GregorianCalendar.MONTH,
month.get(GregorianCalendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
return maxP;
}
public void setEventView(View v, int pos, TextView txt, HashSet<String> eventListSet1) {
ArrayList<String> eventList = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
int len1 = day_string.size();
if (len1 > pos) {
String category = cal_event.getEventCateId();
HashSet<String> eventListSet = new HashSet<String>();
StringTokenizer stR = new StringTokenizer(category, ",");
while (stR.hasMoreTokens()) {
eventListSet.add(stR.nextToken());
}
ArrayList<String> sortedList = new ArrayList(eventListSet1);
Collections.sort(sortedList);
//System.out.println("sortedList:" + sortedList);
StringBuffer CategoryNew = new StringBuffer();
Iterator<String> itr = sortedList.iterator();
while (itr.hasNext()) {
CategoryNew.append(itr.next() + ",");
}
eventList.add(category);
switch (CategoryNew.toString()) {
/* ----------only one category ----------*/
case "1,":
v.setBackgroundResource(R.drawable.gs);
break;
case "2,":
v.setBackgroundResource(R.drawable.se);
break;
case "3,":
v.setBackgroundResource(R.drawable.ge);
break;
case "4,":
v.setBackgroundResource(R.drawable.tuce);
break;
/*----------two category----------*/
case "1,2,":
v.setBackgroundResource(R.drawable.gsse);
break;
case "1,3,":
v.setBackgroundResource(R.drawable.gsge);
break;
case "1,4,":
v.setBackgroundResource(R.drawable.gstuce);
break;
case "2,3,":
v.setBackgroundResource(R.drawable.sege);
break;
case "2,4,":
v.setBackgroundResource(R.drawable.setuce);
break;
case "3,4,":
v.setBackgroundResource(R.drawable.getuce);
break;
/*----------three category----------*/
case "1,2,3,":
v.setBackgroundResource(R.drawable.gssege);
break;
case "1,3,4,":
v.setBackgroundResource(R.drawable.gsgetuce);
break;
case "1,2,4,":
v.setBackgroundResource(R.drawable.gssetuce);
break;
case "2,3,4,":
v.setBackgroundResource(R.drawable.gesetuce);
break;
/*----------four category----------*/
case "1,2,3,4,":
v.setBackgroundResource(R.drawable.gssegetuce);
default:
System.out.println("Invalid event");
break;
}
/*BadgeView1 badge = new BadgeView1(context, cal_item_ll);
badge.setText("1");
badge.show();*/
txt.setTextColor(Color.BLUE);
}
}
}
public void getPositionList(String date, final Activity act) {
final String TAG_EVENT_NAME = "event_name";
final String TAG_EVENT_DESC = "event_desc";
final String TAG_EVENT_FROM_DATE = "event_from_date";
final String TAG_EVENT_TO_DATE = "event_to_date";
final String TAG_EVENT_TIMING = "event_timing";
final String TAG_EVENT_PLACE = "event_place";
final String TAG_EVENT_CATE_ID = "event_cate_id";
String event_name, event_desc, event_from_date;
String event_to_date, event_timing, event_place, event_cate_id;
ArrayList<HashMap<String, String>> event = new ArrayList<>();
int len = CalendarEvent.event_calendar_arr.size();
for (int i = 0; i < len; i++) {
CalendarEvent cal_event = CalendarEvent.event_calendar_arr.get(i);
event_name = cal_event.getEventName();
event_desc = cal_event.getEventDesc();
event_from_date = cal_event.getEventFromDate();
event_to_date = cal_event.getEventToDate();
event_timing = cal_event.getEventTiming();
event_place = cal_event.getEventPlace();
event_cate_id = cal_event.getEventCateId();
if (date.equals(event_from_date)) {
HashMap<String, String> map = new HashMap<>();
map.put(TAG_EVENT_NAME, event_name);
map.put(TAG_EVENT_DESC, event_desc);
map.put(TAG_EVENT_FROM_DATE, event_from_date);
map.put(TAG_EVENT_TO_DATE, event_to_date);
map.put(TAG_EVENT_TIMING, event_timing);
map.put(TAG_EVENT_PLACE, event_place);
if (event_cate_id.equals(1)) {
map.put(TAG_EVENT_CATE_ID, "General Science");
}
if (event_cate_id.equals(2)) {
map.put(TAG_EVENT_CATE_ID, "Scientific Exhibition");
}
if (event_cate_id.equals(3)) {
map.put(TAG_EVENT_CATE_ID, "General Events");
}
if (event_cate_id.equals(4)) {
map.put(TAG_EVENT_CATE_ID, "Tuce Clubs");
}
if (event_cate_id.equals("")) {
map.put(TAG_EVENT_CATE_ID, "");
}
event.add(map);
}
}
if (event.size() > 0) {
Bundle b = new Bundle();
b.putSerializable("EVENT_LIST", event);
Intent in = new Intent(context, Event1.class);
in.putExtras(b);
context.startActivity(in);
} else {
ToastMessage.toastMessage(context, "On this date there is no event");
}
}
BadgeView.class -
package vyClean.wemecalendar.util;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
public class BadgeView extends TextView {
private Context context;
protected View target;
private ShapeDrawable badgeBg;
public BadgeView(Context context, View target) {
this(context, null, android.R.attr.textViewStyle, target);
}
public BadgeView(Context context, AttributeSet attrs, int defStyle, View target) {
super(context, attrs, defStyle);
init(context, target);
}
private void init(Context context, View target) {
try {
this.context = context;
this.target = target;
//apply defaults
setTypeface(Typeface.DEFAULT_BOLD);
setPadding(7, 0, 7, 0);
setTextColor(Color.WHITE);
if (this.target != null) {
applyTo(this.target);
} else {
show();
}
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private void applyTo(View target) {
try {
ViewGroup.LayoutParams lp = target.getLayoutParams();
//ViewParent parent = target.getParent();
FrameLayout container = new FrameLayout(context);
// TODO verify that parent is indeed a ViewGroup
ViewGroup group = (ViewGroup) target;
int index = group.indexOfChild(target);
group.removeView(target);
group.addView(container, index,lp);
container.addView(target);
container.addView(this);
group.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void show() {
try {
if (getBackground() == null) {
if (badgeBg == null) {
badgeBg = getDefaultBackground();
}
setBackgroundDrawable(badgeBg);
}
applyLayoutParams();
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
private ShapeDrawable getDefaultBackground() {
ShapeDrawable drawable = null;
try {
float[] outerR = new float[]{20, 20, 20, 20, 20, 20, 20, 20};
RoundRectShape rr = new RoundRectShape(outerR, null, null);
drawable = new ShapeDrawable(rr);
drawable.getPaint().setColor(Color.BLACK);
} catch (StackOverflowError e) {
e.printStackTrace();
}
return drawable;
}
private void applyLayoutParams() {
try {
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.RIGHT | Gravity.TOP;
setLayoutParams(lp);
} catch (StackOverflowError e) {
e.printStackTrace();
}
}
}
I am working with Section list view in Android to show Call details according to date.
Means under a particular date number of call details. But when I get 2 calls under the same date, the last date is visible only and the list does not show the rest of the calls of that date.
Calls under different dates are shown correctly but calls under same date are not shown correctly, only the last call is shown.
I am using the below code:
public String response = "{ \"Message\":\"Success\", "
+ "\"Data\":[ { \"ACCOUNT\":\"000014532497\", "
+ "\"DATE\":\"8/6/2006\", \"TIME\":\"15:37:14\", "
+ "\"CH_ITEM\":\"341T\", \"ITEM\":\"TIMEUSED\", "
+ "\"DESCRIPTION\":\"FROM3103475779\", \"DETAIL\":"
+ "\"UnitedKingdom011441980849463\", \"QUANTITY\":84, "
+ "\"RATE\":0.025, \"AMOUNT\":2.1, \"ACTUAL\":83.2, "
+ "\"NODE_NAME\":\"TNT02\", \"USER_NAME\":\"Shailesh Sharma\""
+ ", \"MODULE_NAME\":\"DEBIT\", \"ANI\":\"3103475779\", "
+ "\"DNIS\":\"3103210104\", \"ACCOUNT_GROUP\":\"WEBCC\", "
+ "\"SALES_REP\":\"sascha_d\", \"SALES_REP2\":\"\", \"SALES_REP3"
+ "\":\"\", \"IN_PORT\":\"I10\", \"EXTRA1\":\"RATE\", \"EXTRA2\":"
+ "\"44\", \"EXTRA3\":\"UnitedKingdom\", \"OUT_PORT\":\"I70\", "
+ "\"CRN\":\"WEBCC\", \"CallId\":null, \"ID\":4517734, \"PhoneNumber"
+ "\":\"011441980849463\" }, {\"ACCOUNT\":\"000014532497\",\"DATE\":"
+ "\"8/6/2006\",\"TIME\":\"09:22:57\",\"CH_ITEM\":\"541T\",\"ITEM\":"
+ "\"TIMEUSED\",\"DESCRIPTION\":\"FROM3103475779\",\"DETAIL\":"
+ "\"UnitedKingdom011447914422787\",\"QUANTITY\":1,\"RATE\":0.29,"
+ "\"AMOUNT\":0.29,\"ACTUAL\":0.5,\"NODE_NAME\":\"TNT02\",\"USER_NAME"
+ "\":\"Tusshar\",\"MODULE_NAME\":\"DEBIT\",\"ANI\":\"3103475779\",\"DNIS"
+ "\":\"6173950047\",\"ACCOUNT_GROUP\":\"WEBCC\",\"SALES_REP\":\"sascha_d"
+ "\",\"SALES_REP2\":\"\",\"SALES_REP3\":\"\",\"IN_PORT\":\"I30\",\"EXTRA1"
+ "\":\"RATE\",\"EXTRA2\":\"44\",\"EXTRA3\":\"UnitedKingdom-Special\","
+ "\"OUT_PORT\":\"I90\",\"CRN\":\"WEBCC\",\"CallId\":null,\"ID\":4535675,"
+ "\"PhoneNumber\":\"011447914422787\"}, ], \"NumberOfContacts\":2, "
+ "\"TotalCharges\":4.830000000000001 }";
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if (message != null && message.equalsIgnoreCase("Success")) {
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
for (int i = 0; i < dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
_date = history.getString("DATE");
String updatedDate = createDateFormat(_date);
// notes =new ArrayList<String>();
itemList = new ArrayList<Object>();
// ADDING DATE IN THE ARRAYLIST<String>
days.add(updatedDate);
_username = history.getString("USER_NAME");
_number = history.getString("PhoneNumber");
_time = history.getString("TIME");
_amount = history.getString("AMOUNT");
_duration = history.getString("QUANTITY");
/*
* notes.add(_username); notes.add(_number);
* notes.add(_time);
*/
AddObjectToList(_username, _number, _time, _amount,
_duration);
// listadapter = new <String>(this, R.layout.list_item,
// notes);
listadapter = new ListViewCustomAdapter(this, itemList);
adapter.addSection(days.get(i), listadapter);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public class SeparatedListAdapter extends BaseAdapter {
/*
* public final Map<String, Adapter> sections = new
* LinkedHashMap<String, Adapter>();
*/
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
}
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return section;
if (position < size)
return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
#Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
#Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return TYPE_SECTION_HEADER;
if (position < size)
return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
public boolean areAllItemsSelectable() {
return false;
}
#Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0)
return headers.getView(sectionnum, convertView, parent);
if (position < size)
return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
#Override
public long getItemId(int position) {
return position;
}
}
This is my actual requirement:
This is what is happening right now.
SectionListExampleActivity is my Main class in which I am getting RESPONSE from JSON web service. In getJSONResposne method I am calling the EntryAdaptor.
There are two separate geter setter classes for SECTION HEADER and ITEM ENTRY for each header.
public class SectionListExampleActivity extends Activity implements OnClickListener, OnItemSelectedListener, IServerResponse {
/** Called when the activity is first created. */
private ArrayList<Item> items = new ArrayList<Item>();
boolean firstTime = true;
private Spinner _spinner=null;
private ArrayAdapter _amountAdaptor = null;
private ArrayList<String> _monthList =new ArrayList<String>();
private ListView _list=null;
private Button _monthButton=null;
private ImageButton _backImageButton=null;
private ImageButton _headerImageButton=null;
private String _token;
private String _account;
private Point p=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.account_history);
String response = this.getIntent().getExtras().getString("history_resp");
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
_list = (ListView)findViewById(R.id.listview);
getJSON_Response(response,Constant.PID_ACCOUNT_HISTORY);
EntryAdapter adapter = new EntryAdapter(this, items);
_list.setAdapter(adapter);
_monthList.add("Months");
_monthList.add("January");
_monthList.add("February");
_monthList.add("March");
_monthList.add("April");
_monthList.add("May");
_monthList.add("June");
_monthList.add("July");
_monthList.add("August");
_monthList.add("September");
_monthList.add("October");
_monthList.add("November");
_monthList.add("December");
_spinner = (Spinner)findViewById(R.id.month_spinner);
_amountAdaptor = new ArrayAdapter(this,
android.R.layout.simple_spinner_dropdown_item,
_monthList);
_spinner.setAdapter(_amountAdaptor);
_spinner.setOnItemSelectedListener(this);
_monthButton = (Button)findViewById(R.id.monthSpinner_button);
_monthButton.setOnClickListener(this);
_backImageButton = (ImageButton)findViewById(R.id.back_ImageButton);
_backImageButton.setOnClickListener(this);
_headerImageButton =(ImageButton)findViewById(R.id.header_ImageButton);
_headerImageButton.setOnClickListener(this);
}
private void getJSON_Response(String response,int pid) {
switch (pid) {
case Constant.PID_ACCOUNT_HISTORY:
try {
JSONObject jsonObj = new JSONObject(response);
String message = jsonObj.getString("Message");
if(message!=null && message.equalsIgnoreCase("Success")){
JSONArray dataArray = jsonObj.getJSONArray("Data");
System.out.println(dataArray.length());
String lastAddedDate = null;
for (int i = 0; i <dataArray.length(); i++) {
JSONObject history = dataArray.getJSONObject(i);
String date = history.getString("DATE");
if(firstTime || !(date.equalsIgnoreCase(lastAddedDate))){
firstTime=false;
lastAddedDate = date;
items.add(new SectionItem(date));
}
String username= history.getString("USER_NAME");
String number = history.getString("PhoneNumber");
String time = history.getString("TIME");
String amount=history.getString("AMOUNT");
String duration =history.getString("QUANTITY");
items.add(new EntryItem(username,duration,amount,number,time));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}
#Override
public void onClick(View v) {
if(v==_monthButton){
_spinner.performClick();
}else if(v==_backImageButton){
SectionListExampleActivity.this.finish();
}else if(v== _headerImageButton){
if (p != null)
showPopup(SectionListExampleActivity.this, p);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long arg3) {
if(position!=0){
switch (parent.getId()) {
case R.id.month_spinner:
String selectedItem = _spinner.getSelectedItem().toString();
_monthButton.setBackgroundResource(R.drawable.month_blank);
_monthButton.setText(selectedItem);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String _historyURL = Constant.prodORdevUrl + "GetAccountHistory?token="+_token+"&account="+_account+"&month="+month+"&year="+year;
getHistory(_historyURL,true);
break;
default:
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class EntryAdapter extends ArrayAdapter<Item> implements IServerResponse {
private Context context;
private ArrayList<Item> items;
private LayoutInflater vi;
private String _token;
private String _account;
public EntryAdapter(Context context,ArrayList<Item> items) {
super(context,0, items);
this.context = context;
this.items = items;
vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_token = Constant.AUTH_TOKEN;
_account = Constant.ACCOUNT_NUM;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final Item i = items.get(position);
if (i != null) {
if(i.isSection()){
SectionItem si = (SectionItem)i;
v = vi.inflate(R.layout.list_item_section, null);
v.setOnClickListener(null);
v.setOnLongClickListener(null);
v.setLongClickable(false);
final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
String date =createDateFormat(si.getTitle());
sectionView.setText(date);
}else{
EntryItem ei = (EntryItem)i;
v = vi.inflate(R.layout.list_item_entry, null);
final RelativeLayout relay = (RelativeLayout)v.findViewById(R.id.account_history_item_relay);
final TextView username = (TextView)v.findViewById(R.id.user_name_textview);
final TextView amount = (TextView)v.findViewById(R.id.amount_textview);
final TextView duration = (TextView)v.findViewById(R.id.duration_textview);
final TextView phone = (TextView)v.findViewById(R.id.phone_no_textview);
final TextView time = (TextView)v.findViewById(R.id.time_textview);
relay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
makeCall(phone.getText().toString());
}
});
if (username != null)
username.setText(ei.username);
if(amount != null)
amount.setText(ei.duration + "min");
if(duration != null)
duration.setText("$"+ ei.amount);
if(phone != null)
phone.setText(ei.number);
if(time != null)
time.setText(ei.time);
}
}
return v;
}
void makeCall(String destination) {
if(_token!=null && _account!=null){
if(destination!=null && !destination.equals("")){
String phoneNumber = Constant.getPhoneNumber(this.context.getApplicationContext());
if(phoneNumber!=null && phoneNumber.length()>0){
String callURL =WebService.WEB_SERVICE_URL+"PlaceLongDistanceCall?token="+_token +
"&phonenumber="+phoneNumber+"&destinationNumber="+destination+"&authtoken="+_token;
getCall(callURL,true);
}else{
Constant.showToast(this.context, Constant.INSERT_SIM);
}
}else{
Constant.showToast(this.context, "In valid destination number.");
}
}
}
}
In my app, I have requirement of showing calendar. Since, calendar view is available from API level 11, so, I used grid view instead. Basically, I follwed this tutorial. Calendar is working, but data in Calendar in appearing with delay, means, when I click on button to display the calendar, it comes up after delay of around 5-10 seconds. I even tested with disabling the log, which I have put in the program, but it didn't made any difference. I am posting my code below.
Calendar Adapter
public class CalendarAdapter extends BaseAdapter //implements OnClickListener
{
static final int FIRST_DAY_OF_WEEK = 0; // Sunday = 0, Monday = 1
private Context mContext;
private Calendar month;
private Calendar selectedDate;
public String[] days;
TextView txtCurMonth;
public static final String TAG = "CalendarAdapter";
int curYear, curMonth;
public ArrayList<EventDetailDAO> mEventDAOList;
String date, dateToHighlight;
public static boolean calendarItemClicked = false;
ViewHolder holder;
public CalendarAdapter(Context c, Calendar monthCalendar, TextView txtCurMonth)
{
month = monthCalendar;
selectedDate = (Calendar)monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
new ArrayList<String>();
this.txtCurMonth = txtCurMonth;
mEventDAOList = new ArrayList<EventDetailDAO>();
curYear = selectedDate.get(Calendar.YEAR);
curMonth = selectedDate.get(Calendar.MONTH) + 1;
refreshDays();
}//Constructor
public void setItems(ArrayList<String> items)
{
for(int i = 0; i != items.size(); i++)
{
if(items.get(i).length() == 1)
{
items.set(i, "0" + items.get(i));
}//if
}//for
}//setItems
public int getCount()
{
return days.length;
}//getCount
public Object getItem(int position)
{
return null;
}//getItem
public long getItemId(int position)
{
return 0;
}//getItemId
// create a new view for each item referenced by the Adapter
public View getView(final int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
holder = new ViewHolder();
convertView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.calendar_grid_adapter, null);
holder.linCalAdapParent = (LinearLayout)convertView
.findViewById(R.id.linCalAdapParent);
holder.dayView = (TextView)convertView.findViewById(R.id.date);
convertView.setTag(holder);
}//if
else
{
holder = (ViewHolder)convertView.getTag();
}//else
Typeface date_TF = Typeface.createFromAsset(mContext.getAssets(), "fonts/arial.ttf");
txtCurMonth.setTypeface(date_TF);
txtCurMonth.setText(DateFormat.format("MMMM yyyy", month.getTime()));
holder.dayView.setTypeface(date_TF);
holder.dayView.setText(days[position]);
if(days[position].equals(""))
{
holder.linCalAdapParent.setBackgroundResource(R.drawable.calendar_tile);
}//if
else
{
String monthToCheck = null;
if(curMonth < 10)
{
monthToCheck = "0"+curMonth;
}//if
else
{
monthToCheck = Integer.toString(curMonth);
}//else
dateToHighlight = curYear+"-"+monthToCheck;
Log.v(TAG, "date to highlight: "+dateToHighlight);
if(isEnabled(position))
{
holder.linCalAdapParent.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Log.v(TAG, "CalendarAdapter mEventDAOList size: "+mEventDAOList.size());
String daysToMatch = days[position];
if(daysToMatch.length() == 1)
{
daysToMatch = "0"+daysToMatch;
}//if
Log.v(TAG, "CalendarAdapter day selected: "+daysToMatch);
ArrayList<EventDetailDAO> mSelectedEventDAOList
= new ArrayList<EventDetailDAO>();
for(int i = 0; i < mEventDAOList.size(); i++)
{
if(mEventDAOList.get(i).getEvent_Date().contains(daysToMatch))
{
mSelectedEventDAOList.add(mEventDAOList.get(i));
selectedDate.set(Calendar.YEAR, curYear);
selectedDate.set(Calendar.MONTH, curMonth - 1);
selectedDate.set(Calendar.DAY_OF_MONTH, Integer.parseInt(daysToMatch));
}//if
}//for
((EventsActivity)mContext).getDataFromCalendar(mSelectedEventDAOList, selectedDate);
((EventsActivity)mContext).calInstanceFromAdapter = selectedDate;
calendarItemClicked = true;
}//onClick
});
}//if
}//else
Log.v(TAG, "Calendar adapter getView called");
return convertView;
}//getView
public void refreshDays()
{
// clear items
//items.clear();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
int firstDay = (int)month.get(Calendar.DAY_OF_WEEK);
Log.v(TAG, "in refreshDays, lastDay: "+lastDay);
Log.v(TAG, "in refreshDays, firstDay: "+firstDay);
// figure size of the array
if(firstDay == 1)
{
Log.v(TAG, "if first day 1");
days = new String[lastDay + (FIRST_DAY_OF_WEEK * 6)];
}//if
else
{
Log.v(TAG, "else first day not 1");
days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK + 1)];
}//else
int j=FIRST_DAY_OF_WEEK;
// populate empty days before first real day
if(firstDay > 1)
{
Log.v(TAG, "if first day > 1");
for(j = 0; j < firstDay - FIRST_DAY_OF_WEEK; j++)
{
Log.v(TAG, "in for if first day > 1");
days[j] = "";
}//for
}//if
else
{
Log.v(TAG, "else first day < 1");
for(j = 0; j < FIRST_DAY_OF_WEEK * 6; j++)
{
Log.v(TAG, "in for else first day < 1");
days[j] = "";
}//for
j = FIRST_DAY_OF_WEEK * 6 + 1; // sunday => 1, monday => 7
}//else
// populate days
int dayNumber = 1;
for(int i = j - 1; i < days.length; i++)
{
Log.v(TAG, "in for day number");
days[i] = "" + dayNumber;
dayNumber++;
}//for
}//refreshDays
#Override
public boolean isEnabled(int position)
{
date = days[position];
if(date.length() == 1)
{
date = "0"+date;
}//if
dateToHighlight = dateToHighlight+"-"+date;
for(EventDetailDAO mEventDetailDAO: GetEventDetailAsyncTask.mainEventDetailArrayList)
{
Log.v(TAG, "CalendarAdapter isEnabled dateToHighlight: "+dateToHighlight);
if(mEventDetailDAO.getEvent_Date().equals(dateToHighlight))
{
mEventDAOList.add(mEventDetailDAO);
holder.linCalAdapParent.setBackgroundResource(R.drawable.calendar_tile_sel);
return true;
}//if
}//for
return false;
}//isEnabled
class ViewHolder
{
LinearLayout linCalAdapParent;
TextView dayView;
}//ViewHolder
}//CalendarAdapter
In my calendar, I have to highlight the dates which have some event. And, on click of highlighted date, it will show the list of events on that date. Every thing is working. except the calendar appears with delay even if I change month. I am not getting the cause.
One of the possible causes of the delay may be the call to Typeface.createFromAsset() which is called for every cell. The createFromAsset() method consumes a lot of resources.
To mitigate this, you could create a singleton class that retains the typeface used, so the font is not generated from the font file every time. Or you initialize it in onCreate() and pass it as an argument to the CalendarAdapter constructor and then use that instance in getView().
(To test this assumption comment the lines that sets the font to txtCurMonth TextView, and see if any difference)
So, I have a spinner, populated with ~35 values. If I select, say, the fifth item, then when it is selected, it does what it is supposed to do (populate a second spinner). My problem is that shortly afterwards (<1/2 second) it reverts the values in the second spinner to what they would be if option 1 in the first spinner were selected. The fifth item in the first spinner is still selected but it acts as though the first item gets selected twice per second.
I've tried everything I could find on this (barely anything) and nothing has worked so far. This basically has me stuck on going further in my app.
Entire Code:
package com.nicotera.colton.londontransitguide;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.*;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class RoutesActivity extends Activity implements OnItemSelectedListener {
Spinner dirSpinner;
Spinner routeSpinner;
static String [] namedDirections = new String [2];
private static final String TAG = "RoutesActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_routes);
dirSpinner = (Spinner) findViewById(R.id.route_direction_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner = (Spinner) findViewById(R.id.route_name_spinner); // Create an ArrayAdapter using the string array and a default spinner layout
routeSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.routes_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner
routeSpinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.i(TAG, "Item selected");
//DecimalFormat df = new DecimalFormat("00##");
int tempPos = pos;
Log.i(TAG, ("Position of selected item: " + tempPos));
int routeSelected;
if (tempPos < 17)
routeSelected = (tempPos + 1);
else if (tempPos >= 17 && tempPos < 29)
routeSelected = (tempPos + 2);
else
routeSelected = (tempPos + 3);
String temp;
if (routeSelected < 10)
temp = ("0") + routeSelected;
else
temp = ("") + routeSelected;
String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
new MyInnerClass().execute(url);
}
public void directionSpinner (String directions []) {
int temp;
for (int i = 1; i <=2; i++)
{
temp = Integer.parseInt(directions[i]);
if (temp == 1)
namedDirections[(i-1)] = "Eastbound";
else if (temp == 2)
namedDirections[(i-1)] = "Northbound";
else if (temp == 3)
namedDirections[(i-1)] = "Southbound";
else if (temp == 4)
namedDirections[(i-1)] = "Westbound";
}
//setContentView(R.layout.activity_routes);
dirSpinner.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add(namedDirections[0]);
adapter.add(namedDirections[1]);
dirSpinner.setAdapter(adapter);
Log.i(TAG, "spinner populated");
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
class MyInnerClass extends AsyncTask<String, Void, String> {
String [] directions = new String [3];
String [] directionNames = new String [3];
private static final String TAG = "RoutesActivity";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
RoutesActivity.this.directionSpinner(directions);
}
#Override
protected String doInBackground(String... params) {
try{
Pattern routeDirPattern = Pattern.compile("\\&d=(\\d{1,2})");
Connection conn = Jsoup.connect(params[0]);
Document doc = conn.get();
int i = 0;
Elements routeLinks = doc.select("a[href]");
for (Element routeLink : routeLinks) {
i = (i + 1);
String name = routeLink.text();
Attributes attrs = routeLink.attributes();
String href = attrs.get("href");
Matcher m = routeDirPattern.matcher(href);
if (m.find()) {
String number = m.group(1);
directions [i] = number;
directionNames [i] = name;
Log.i(TAG, directionNames [i]);
}
}
}catch(Exception e){Log.d("doinbackground exception", e.toString());}
return ("Done");
}
}
}
I was using the same onselected listener for both without an if statement to check which one was clicked so it just thought that the first one was clicked.
This is the corrected code:
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Spinner spnr = (Spinner) parent;
Log.i(TAG, "Item selected");
switch(parent.getId()) {
case R.id.route_name_spinner:
//DecimalFormat df = new DecimalFormat("00##");
int tempPos = pos;
Log.i(TAG, ("Position of selected item: " + tempPos));
int routeSelected;
if (tempPos < 17)
routeSelected = (tempPos + 1);
else if (tempPos >= 17 && tempPos < 29)
routeSelected = (tempPos + 2);
else
routeSelected = (tempPos + 3);
String temp;
if (routeSelected < 10)
temp = ("0") + routeSelected;
else
temp = ("") + routeSelected;
String url = "http://www.ltconline.ca/WebWatch/MobileAda.aspx?r=" + temp;
new MyInnerClass().execute(url);
case R.id.route_direction_spinner:
}
}