#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
Locale.setDefault(Locale.US);
test1 = "2014-11-08";
test2 = "2014-11-07";
test3 = "2014-12-08";
test4 = "2014-12-04";
rLayout = (LinearLayout) findViewById(R.id.text);
tvView = (TextView)findViewById(R.id.tvView);
tvView1 = (TextView)findViewById(R.id.tvView1);
tvView2 = (TextView)findViewById(R.id.tvView2);
tvView3 = (TextView)findViewById(R.id.tvView3);
tvView4 = (TextView)findViewById(R.id.tvView4);
tvView5 = (TextView)findViewById(R.id.tvView5);
tvView3.setVisibility(View.GONE);
tvView4.setVisibility(View.GONE);
tvView5.setVisibility(View.GONE);
month = (GregorianCalendar) Calendar.getInstance();
itemmonth = (GregorianCalendar) month.clone();
items = new ArrayList<String>();
adapter = new CalendarAdapter(this, month);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(adapter);
handler = new Handler();
handler.post(calendarUpdater);
TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);
previous.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setPreviousMonth();
refreshCalendar();
tvView.setVisibility(View.GONE);
}
});
RelativeLayout next = (RelativeLayout) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setNextMonth();
refreshCalendar();
tvView.setVisibility(View.GONE);
}
});
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
TextView cdate = (TextView)v.findViewById(R.id.date);
if(cdate instanceof TextView && !cdate.getText().equals(""))
{
TextView title = (TextView) findViewById(R.id.title);
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
testMonth=title.getText().toString();
String day = cdate.getText().toString();
Toast.makeText(getApplicationContext(),day+" "+testMonth,Toast.LENGTH_SHORT).show();
}
// removing the previous view if added
if (rLayout.getChildCount() > 0) {
// rLayout.removeAllViews();
}
desc = new ArrayList<String>();
date = new ArrayList<String>();
((CalendarAdapter) parent.getAdapter()).setSelected(v);
String selectedGridDate = CalendarAdapter.dayString
.get(position);
tvView.setVisibility(View.VISIBLE);
tvView3.setVisibility(View.VISIBLE);
tvView4.setVisibility(View.VISIBLE);
tvView5.setVisibility(View.VISIBLE);
if(test1.equals(selectedGridDate))
{
tvView.setText("My Goal");
tvView.setTextColor(Color.RED);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
}
else if(test2.equals(selectedGridDate))
{
tvView.setText("Passion of a Student");
tvView.setTextColor(Color.RED);
tvView1.setText("Creating my own Goal");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("Circular Task");
tvView2.setTextColor(Color.GREEN);
}
else if(test3.equals(selectedGridDate))
{
tvView.setText("My test Passion");
tvView.setTextColor(Color.RED);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
}
else if(test3.equals(selectedGridDate))
{
tvView.setText("My test Task");
tvView.setTextColor(Color.RED);
}
else
{
tvView.setText("No task found");
tvView.setTextColor(Color.MAGENTA);
tvView1.setText("");
tvView1.setTextColor(Color.CYAN);
tvView2.setText("");
tvView2.setTextColor(Color.GREEN);
tvView3.setVisibility(View.GONE);
tvView4.setVisibility(View.GONE);
tvView5.setVisibility(View.GONE);
}
String[] separatedTime = selectedGridDate.split("-");
String gridvalueString = separatedTime[2].replaceFirst("^0*",
"");// taking last part of date. ie; 2 from 2012-12-02.
int gridvalue = Integer.parseInt(gridvalueString);
// navigate to next or previous month on clicking offdays.
if ((gridvalue > 10) && (position < 8)) {
setPreviousMonth();
refreshCalendar();
} else if ((gridvalue < 7) && (position > 28)) {
setNextMonth();
refreshCalendar();
}
((CalendarAdapter) parent.getAdapter()).setSelected(v);
for (int i = 0; i < Utility.startDates.size(); i++) {
if (Utility.startDates.get(i).equals(selectedGridDate)) {
desc.add(Utility.nameOfEvent.get(i));
}
}
if (desc.size() > 0) {
for (int i = 0; i < desc.size(); i++) {
TextView rowTextView = new TextView(CalendarView.this);
// set some properties of rowTextView or something
rowTextView.setText("Event:" + desc.get(i));
rowTextView.setTextColor(Color.BLACK);
// add the textview to the linearlayout
rLayout.addView(rowTextView);
}
}
desc = null;
}
});
}
protected void setNextMonth() {
if (month.get(Calendar.MONTH) == month
.getActualMaximum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR) + 1),
month.getActualMinimum(Calendar.MONTH), 1);
} else {
month.set(Calendar.MONTH,
month.get(Calendar.MONTH) + 1);
}
}
protected void setPreviousMonth() {
if (month.get(Calendar.MONTH) == month
.getActualMinimum(Calendar.MONTH)) {
month.set((month.get(Calendar.YEAR) - 1),
month.getActualMaximum(Calendar.MONTH), 1);
} else {
month.set(Calendar.MONTH,
month.get(Calendar.MONTH) - 1);
}
}
protected void showToast(String string) {
Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
}
public void refreshCalendar() {
TextView title = (TextView) findViewById(R.id.title);
adapter.refreshDays();
adapter.notifyDataSetChanged();
handler.post(calendarUpdater); // generate some calendar items
title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
}
public Runnable calendarUpdater = new Runnable() {
#Override
public void run() {
items.clear();
// Print dates of the current week
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String itemvalue;
event = Utility.readCalendarEvent(CalendarView.this);
Log.d("=====Event====", event.toString());
Log.d("=====Date ARRAY====", Utility.startDates.toString());
for (int i = 0; i < Utility.startDates.size(); i++) {
itemvalue = df.format(itemmonth.getTime());
itemmonth.add(Calendar.DATE, 1);
items.add(Utility.startDates.get(i).toString());
}
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
here I able to see all events while clicking on a particular date,but my requirement is also show the dates with bold style or any other color view that containing events without clicking gridview items.My adapter class as follows:::
public class CalendarAdapter extends BaseAdapter {
private Context mContext;
private java.util.Calendar month;
public GregorianCalendar pmonth;
public GregorianCalendar pmonthmaxset;
private GregorianCalendar selectedDate;
int firstDay;
int maxWeeknumber;
int maxP;
int calMaxP;
int lastWeekDay;
int leftDays;
int mnthlength;
String itemvalue, curentDateString;
DateFormat df;
private ArrayList<String> items;
public static List<String> dayString;
private View previousView;
public CalendarAdapter(Context c, GregorianCalendar monthCalendar) {
CalendarAdapter.dayString = new ArrayList<String>();
Locale.setDefault(Locale.US);
month = monthCalendar;
selectedDate = (GregorianCalendar) monthCalendar.clone();
mContext = c;
month.set(Calendar.DAY_OF_MONTH, 1);
this.items = new ArrayList<String>();
df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
curentDateString = df.format(selectedDate.getTime());
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;
}
#Override
public int getCount() {
return dayString.size();
}
#Override
public Object getItem(int position) {
return dayString.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
// create a new view for each item referenced by the Adapter
#Override
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_layout, null);
}
dayView = (TextView) v.findViewById(R.id.date);
// separates daystring into parts.
String[] separatedTime = dayString.get(position).split("-");
// taking last part of date. ie; 2 from 2012-12-02
String gridvalue = separatedTime[2].replaceFirst("^0*", "");
// checking whether the day is in current month or not.
if ((Integer.parseInt(gridvalue) > 1) && (position < firstDay)) {
// setting offdays to white color.
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else if ((Integer.parseInt(gridvalue) < 7) && (position > 28)) {
dayView.setTextColor(Color.WHITE);
dayView.setClickable(false);
dayView.setFocusable(false);
} else {
// setting curent month's days in blue color.
dayView.setTextColor(Color.BLUE);
}
if (dayString.get(position).equals(curentDateString)) {
setSelected(v);
previousView = v;
} else {
v.setBackgroundResource(R.drawable.list_item_background);
}
dayView.setText(gridvalue);
// create date string for comparison
String date = dayString.get(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 View setSelected(View view) {
if (previousView != null) {
previousView.setBackgroundResource(R.drawable.list_item_background);
}
previousView = view;
view.setBackgroundResource(R.drawable.calendar_cel_selectl);
return view;
}
public void refreshDays() {
// clear items
items.clear();
dayString.clear();
Locale.setDefault(Locale.US);
pmonth = (GregorianCalendar) month.clone();
// month start day. ie; sun, mon, etc
firstDay = month.get(Calendar.DAY_OF_WEEK);
// finding number of weeks in current month.
maxWeeknumber = month.getActualMaximum(Calendar.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(Calendar.DAY_OF_MONTH, calMaxP + 1);
/**
* filling calendar gridview.
*/
for (int n = 0; n < mnthlength; n++) {
itemvalue = df.format(pmonthmaxset.getTime());
pmonthmaxset.add(Calendar.DATE, 1);
dayString.add(itemvalue);
}
}
private int getMaxP() {
int maxP;
if (month.get(Calendar.MONTH) == month
.getActualMinimum(Calendar.MONTH)) {
pmonth.set((month.get(Calendar.YEAR) - 1),
month.getActualMaximum(Calendar.MONTH), 1);
} else {
pmonth.set(Calendar.MONTH,
month.get(Calendar.MONTH) - 1);
}
maxP = pmonth.getActualMaximum(Calendar.DAY_OF_MONTH);
return maxP;
}
}
Atlast I had already solved my problem changing my Runnable calendar updater as follows:
public Runnable calendarUpdater = new Runnable() {
#Override
public void run()
{
items.clear();
// Print dates of the current week
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String itemvalue;
for (int i = 0; i < 7; i++)
{
itemvalue = df.format(itemmonth.getTime());
itemmonth.add(Calendar.DATE, 1);
items.add("2014-12-08");
items.add("2014-12-04");
items.add("2014-11-07");
items.add("2014-11-08");
}
adapter.setItems(items);
adapter.notifyDataSetChanged();
}
};
Now I can see the events without clicking gridView items what I want.Thanx all of you guys for your kind cooperation in this regard. but now issue is how can I also show this event on android google calendar.
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 am trying to pass the value from spinner.setOnItemSelectedListener to a string that contains date string. I have two spinners month and year, here I am showing only for month spinner because if I get the solution for month spinner then it will be same for year as well.
month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.month_spinner){
seltmont = parent.getSelectedItem().toString();
Toast.makeText(MainActivity.this, "Selected Month: " + seltmont, Toast.LENGTH_SHORT).show();
textviewMonth.setText(seltmont);
setMonthView();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
I have tried to access the spinner value like this:- String month = month_spinner.getSelectedItem().toString();
and try to pass the spinner onItemSelectListener value to combinedString string variable like this:-
combinedString = "01/" + month + "/" + year ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMMM/yyyy");
selectdate = LocalDate.parse(combinedString, formatter);
I get the default value in the combined string that is already preselected in the spinner but
when user try to change the default value that is shown in spinner it does not change the value. It gives null value in the combinedString.
Can anyone help me How to pass the value from onItemSelectListener to combinedString
Is it because of the scope of a method (' { } ') or is it because of private or public variable declaration.
Please help.
By the way whole code is in JAVA.
Here is complete code:-
public class MainActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
TextView monthYearText, textviewMonth,textviewYear,textviewYearnMonth;
RecyclerView calendarReyclerView;
LocalDate selectdate;
private Spinner month_spinner,spinYear;
String [] months;
String combinedString;
String selectedMonth;
String seltmont;
String selctYear;
#SuppressLint("SetTextI18n")
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textviewMonth = findViewById(R.id.textviewMonth);
textviewYear = findViewById(R.id.textviewYear);
//for testing
textviewYearnMonth = findViewById(R.id.textviewYearnMonth);
month_spinner = findViewById(R.id.month_spinner);
spinYear = findViewById(R.id.yearspin);
populateSpinnerMonth();
populateSpinnerYear();
initWidget();
selectdate = LocalDate.now();
setMonthView();
//---- on click listener ---//
month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.month_spinner){
seltmont = parent.getSelectedItem().toString();
Toast.makeText(MainActivity.this, "Selected Month: " + seltmont, Toast.LENGTH_SHORT).show();
textviewMonth.setText(seltmont);
setMonthView();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.yearspin){
selctYear = parent.getSelectedItem().toString();
Toast.makeText(MainActivity.this, "Selected Year" + selctYear, Toast.LENGTH_SHORT).show();
textviewYear.setText(selctYear);
setMonthView();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// ---- on click listener ---//
String month = month_spinner.getSelectedItem().toString();
String year= spinYear.getSelectedItem().toString();
// String month = textviewMonth.getText().toString();
//String year = textviewYear.getText().toString();
//combinedString = "16/09/2019";
combinedString = "01/" + month + "/" + year ;
// combinedString = "01/" + mon + "/" + year ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMMM/yyyy");
selectdate = LocalDate.parse(combinedString, formatter);
/* //not working
String mon = textviewMonth.getText().toString();
Log.d("month","code is going here");
textviewYearnMonth.setText(mon);
Log.d("month","code cross the textviewYearnMonth"); */
// textviewYearnMonth.setText(seltmont);
}
private void populateSpinnerYear() {
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = 1950; i <= thisYear; i++){
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,years);
spinYear.setAdapter(adapter);
}
private void populateSpinnerMonth() {
months = new DateFormatSymbols().getMonths();
ArrayAdapter<String> monthAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,months);
monthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
month_spinner.setAdapter(monthAdapter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setMonthView() {
monthYearText.setText(monthYearFromDate(selectdate));
ArrayList<String> daysInMonth = daysInMonthArray(selectdate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),7); //for calendar columns
calendarReyclerView.setLayoutManager(layoutManager);
calendarReyclerView.setAdapter(calendarAdapter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private ArrayList<String> daysInMonthArray(LocalDate date) {
ArrayList<String> daysInMonthArray = new ArrayList<>();
YearMonth yearMonth = YearMonth.from(date);
int daysInMonth = yearMonth.lengthOfMonth();
LocalDate firstOfMonth = selectdate.withDayOfMonth(1);
int dayOfWeek = firstOfMonth.getDayOfWeek().getValue();
for(int i = 1; i <= 42; i++)
{
if(i <= dayOfWeek || i > daysInMonth + dayOfWeek)
{
daysInMonthArray.add("");
}
else
{
daysInMonthArray.add(String.valueOf(i - dayOfWeek));
}
}
return daysInMonthArray;
}
#RequiresApi(api = Build.VERSION_CODES.O)
private String monthYearFromDate(LocalDate date){
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
return date.format(formatter);
}
private void initWidget() {
calendarReyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void previousMonthAction(View view) {
selectdate = selectdate.minusMonths(1);
setMonthView();
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void nextMonthAction(View view) {
selectdate = selectdate.plusMonths(1);
setMonthView();
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onItemClick(int position, String dayText) {
if(!dayText.equals(""))
{
String message = "Selected Date " + dayText + " " + monthYearFromDate(selectdate);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
I have attached two images of the output:
Initial Stage at first launch ->Image 1
After I changed the spinners value ->Image 2
Declare selectdate as static public static LocalDate selectdate;
Create a method named getSelectDate and call it to get changed value , such as inside onCreate, inside onItemSelected of month_spinner and spinYear.
private void getSelectDate() {
//added
String month = month_spinner.getSelectedItem().toString();
String year = spinYear.getSelectedItem().toString();
//String month = textviewMonth.getText().toString();
//String year = textviewYear.getText().toString();
//combinedString = "16/09/2019";
combinedString = "01/" + month + "/" + year;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMMM/yyyy");
selectdate = LocalDate.parse(combinedString, formatter);
//
}
This will fix your button issue also. All is well . setMonthView roll backed to your old code . Here yours Class-
public class MainActivity extends AppCompatActivity implements CalendarAdapter.OnItemListener {
TextView monthYearText, textviewMonth, textviewYear, textviewYearnMonth;
RecyclerView calendarReyclerView;
public static LocalDate selectdate;
private Spinner month_spinner, spinYear;
String[] months;
String combinedString;
String selectedMonth;
String seltmont;
String selctYear;
#SuppressLint("SetTextI18n")
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textviewMonth = findViewById(R.id.textviewMonth);
textviewYear = findViewById(R.id.textviewYear);
//for testing
textviewYearnMonth = findViewById(R.id.textviewYearnMonth);
month_spinner = findViewById(R.id.month_spinner);
spinYear = findViewById(R.id.yearspin);
populateSpinnerMonth();
populateSpinnerYear();
initWidget();
// selectdate = LocalDate.now();
getSelectDate();
setMonthView();
//---- on click listener ---//
month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.month_spinner) {
seltmont = parent.getSelectedItem().toString();
Toast.makeText(MainActivity.this, "Selected Month: " + seltmont, Toast.LENGTH_SHORT).show();
textviewMonth.setText(seltmont);
//added
getSelectDate();
updateView();
setMonthView();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.yearspin) {
selctYear = parent.getSelectedItem().toString();
Toast.makeText(MainActivity.this, "Selected Year" + selctYear, Toast.LENGTH_SHORT).show();
textviewYear.setText(selctYear);
getSelectDate();
updateView();
setMonthView();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// ---- on click listener ---//
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void getSelectDate() {
//added
String month = month_spinner.getSelectedItem().toString();
String year = spinYear.getSelectedItem().toString();
//String month = textviewMonth.getText().toString();
//String year = textviewYear.getText().toString();
//combinedString = "16/09/2019";
combinedString = "01/" + month + "/" + year;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMMM/yyyy");
selectdate = LocalDate.parse(combinedString, formatter);
//
}
//added
private void updateView() {
// combinedString = "01/" + mon + "/" + year ;
//not working
String mon = textviewMonth.getText().toString();
// Log.d("month","code is going here");
// textviewYearnMonth.setText(mon);
// Log.d("month","code cross the textviewYearnMonth");
textviewYearnMonth.setText(mon);
}
private void populateSpinnerYear() {
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = 1950; i <= thisYear; i++) {
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, years);
spinYear.setAdapter(adapter);
}
private void populateSpinnerMonth() {
months = new DateFormatSymbols().getMonths();
ArrayAdapter<String> monthAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, months);
monthAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
month_spinner.setAdapter(monthAdapter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void setMonthView() {
monthYearText.setText(monthYearFromDate(selectdate));
ArrayList<String> daysInMonth = daysInMonthArray(selectdate);
CalendarAdapter calendarAdapter = new CalendarAdapter(daysInMonth, this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 7); //for calendar columns
calendarReyclerView.setLayoutManager(layoutManager);
calendarReyclerView.setAdapter(calendarAdapter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private ArrayList<String> daysInMonthArray(LocalDate date) {
ArrayList<String> daysInMonthArray = new ArrayList<>();
YearMonth yearMonth = YearMonth.from(date);
int daysInMonth = yearMonth.lengthOfMonth();
LocalDate firstOfMonth = selectdate.withDayOfMonth(1);
int dayOfWeek = firstOfMonth.getDayOfWeek().getValue();
for (int i = 1; i <= 42; i++) {
if (i <= dayOfWeek || i > daysInMonth + dayOfWeek) {
daysInMonthArray.add("");
} else {
daysInMonthArray.add(String.valueOf(i - dayOfWeek));
}
}
return daysInMonthArray;
}
#RequiresApi(api = Build.VERSION_CODES.O)
private String monthYearFromDate(LocalDate date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
return date.format(formatter);
}
private void initWidget() {
calendarReyclerView = findViewById(R.id.calendarRecyclerView);
monthYearText = findViewById(R.id.monthYearTV);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void previousMonthAction(View view) {
selectdate = selectdate.minusMonths(1);
setMonthView();
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void nextMonthAction(View view) {
selectdate = selectdate.plusMonths(1);
setMonthView();
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void onItemClick(int position, String dayText) {
if (!dayText.equals("")) {
String message = "Selected Date " + dayText + " " + monthYearFromDate(selectdate);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
}
To get "dd/MM/yyyy" this format use DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH).format(selectdate); , no other changes need .
To test -
#RequiresApi(api = Build.VERSION_CODES.O)
private void updateView() {
// combinedString = "01/" + mon + "/" + year ;
//not working
String mon = textviewMonth.getText().toString();
// Log.d("month","code is going here");
// textviewYearnMonth.setText(mon);
// Log.d("month","code cross the textviewYearnMonth");
textviewYearnMonth.setText(DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.ENGLISH).format(selectdate));
}
In the onItemSelected callbacks, just use the data sources with the position variable and you'll get it. For example for months spinner:
month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent.getId() == R.id.month_spinner){
seltmont = months[position]; // ATTENTION HERE
Toast.makeText(MainActivity.this, "Selected Month: " + seltmont, Toast.LENGTH_SHORT).show();
textviewMonth.setText(seltmont);
setMonthView();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Do the same for all the spinner listeners.
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.
In following code, i had implemented calander in horizontal List view.
now i wanted to scroll towards particular date, Like if i am passing
22 date, so it should be automatically scroll to 21st item. I had
tried horizontalListView.scrollTO(int x) but its not working. Please
Help me out, if you need more explanation on following code, then let
me know. I had uploaded whole class on this URL
http://tinyurl.com/o6q2uty
public class MyAppointment extends BaseActivity implements OnClickListener,
DataListener {
private LinearLayout myAppointment;
public LinearLayout llCalTop;
private ListView appointmentsExpandableList;
private ArrayList<String> alist;
private ArrayList<AppointmentDO> childs1, childs2, childs3;
private AppointmentListAdapter adapter;
private HashMap<String, ArrayList<AppointmentDO>> map;
private Vector<RequestDO> vecRequestDOs;
Boolean flag = true;
private View monthview;
private MyAppointment context;
private TextView tvSelMonthYear;
public View selView;
private View oldView;
private LinearLayout llcalBody;
static Calendar calendar;
private Calendar CalNext;
private Calendar CalPrev;
private int month, year;
TextView tvPrevMonthClick, tvNextMonthClick;
private CustomCalendar customCalender;
static String calSelectedDate;
private ImageView ivCalRightArrow, ivCalLeftArrow;
public static int width;
// ----------------------------------Slider calendar
// variables------------------------------------//
private HorizontialListView lvItems;
private CalendarAdapter calendarAdapter;
private TextView tvMonth;
private ImageView ivleft, ivright;
private Calendar cal;
private CommonBL commonBL;
private RequestDO requestDO;
private String appointmentdate = "", appointmenttime = "";
// -------- Selected date intializing with -1 because 0 is the minimum value
// in calander.-----//
int selectedDay = -1, selectedMonth = -1, selectedYear = -1;
// -------------------------------------------------*/*---------------------------------------//
#SuppressLint("NewApi")
#Override
public void initialize() {
myAppointment = (LinearLayout) inflater.inflate(
R.layout.my_appointments_layout, null);
llCalTop = (LinearLayout) myAppointment.findViewById(R.id.llCalTop);
llBody.addView(myAppointment, new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
appointmentsExpandableList = (ListView) findViewById(R.id.appointmentsExpandableList);
ivHeaderRight = (ImageView) findViewById(R.id.ivHeaderRight);
// initLists();
vecRequestDOs = new MyAppointmentsDA()
.getAllInitiativesById("31-01-2015");
adapter = new AppointmentListAdapter(MyAppointment.this, vecRequestDOs);
header.setText("My Appointment");
appointmentsExpandableList.setAdapter(adapter);
ivHeaderRight.setVisibility(View.VISIBLE);
ivHeaderRight.setImageResource(R.drawable.cal);
ivHeaderRight.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (flag) {
ivHeaderRight.setImageResource(R.drawable.list);
flag = false;
oldView = findViewById(R.id.llCalTop);
//
show();
} else {
ivHeaderRight.setImageResource(R.drawable.cal);
flag = true;
oldView = (LinearLayout) inflater.inflate(
R.layout.my_appointments_layout, null);
llCalTop.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
llCalTop.removeAllViews();
selectedDay = CustomCalendar.todayDate;
selectedMonth = customCalender.month;
selectedYear = customCalender.year;
llCalTop.addView(oldView, new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
sliderCalendar();
}
}
});
sliderCalendar();
}
#SuppressLint("NewApi")
public void show() {
monthview = inflater.inflate(R.layout.monthview_cal, null);
monthview.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
llCalTop.removeAllViews();
llCalTop.addView(monthview, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
context = MyAppointment.this;
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
CustomCalendar.CALENDER_CELL_WIDTH = width / 7;
tvSelMonthYear = (TextView) findViewById(R.id.tvSelMonthYear);
llcalBody = (LinearLayout) findViewById(R.id.llcalBody);
tvPrevMonthClick = (TextView) findViewById(R.id.prevMonth);
tvNextMonthClick = (TextView) findViewById(R.id.nextMonth);
ivCalLeftArrow = (ImageView) findViewById(R.id.ivCalLeftArrow);
ivCalRightArrow = (ImageView) findViewById(R.id.ivCalRightArrow);
tvSelMonthYear.setTextSize(16);
calendar = Calendar.getInstance();
if (selectedDay != -1 && selectedMonth != -1 && selectedYear != -1) {
calendar.set(selectedYear, selectedMonth, selectedDay);
}
month = calendar.get(Calendar.MONTH);
year = calendar.get(Calendar.YEAR);
CalPrev = Calendar.getInstance();
CalPrev.add(Calendar.MONTH, -1);
CalNext = Calendar.getInstance();
CalNext.add(Calendar.MONTH, 1);
tvSelMonthYear.setText(CalendarUtility.getMonth(month) + " "
+ calendar.get(Calendar.YEAR));
showCalender(month, year);
ivCalLeftArrow.setOnClickListener(this);
ivCalRightArrow.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.ivCalLeftArrow) {
calendar.add(Calendar.MONTH, -1);
tvSelMonthYear.setText(CalendarUtility.getMonth(calendar
.get(Calendar.MONTH)) + " " + calendar.get(Calendar.YEAR));
setMonthText();
showCalender(calendar.get(Calendar.MONTH),
calendar.get(Calendar.YEAR));
} else if (v.getId() == R.id.ivCalRightArrow) {
calendar.add(Calendar.MONTH, +1);
tvSelMonthYear.setText(CalendarUtility.getMonth(calendar
.get(Calendar.MONTH)) + " " + calendar.get(Calendar.YEAR));
showCalender(calendar.get(Calendar.MONTH),
calendar.get(Calendar.YEAR));
setMonthText();
}
}
public void showCalender(int month, int year) {
llcalBody.removeAllViews();
customCalender = new CustomCalendar(context, month, year);
llcalBody.addView(customCalender.makeCalendar(),
LayoutParams.MATCH_PARENT);
}
public void setMonthText() {
int tempCurrentMonth = calendar.get(Calendar.MONTH);
if (tempCurrentMonth > 0 && tempCurrentMonth < 11) {
tvPrevMonthClick.setText(CalendarUtility
.getMonth(tempCurrentMonth - 1));
tvNextMonthClick.setText(CalendarUtility
.getMonth(tempCurrentMonth + 1));
} else if (tempCurrentMonth == 0) {
tvPrevMonthClick.setText(CalendarUtility.getMonth(11));
tvNextMonthClick.setText(CalendarUtility.getMonth(1));
} else if (tempCurrentMonth == 11) {
tvPrevMonthClick.setText(CalendarUtility.getMonth(10));
tvNextMonthClick.setText(CalendarUtility.getMonth(0));
}
}
private void initLists() {
// alist = new ArrayList<String>();
// childs1 = new ArrayList<AppointmentDO>();
// childs2 = new ArrayList<AppointmentDO>();
// childs3 = new ArrayList<AppointmentDO>();
// alist.add("WED, JAN 28");
// // alist.add("THU, JAN 29");
// // alist.add("FRI, JAN 30");
// childs1.add(new AppointmentDO("R.MOHAN REDDY", "address", "09:00 AM",
// "40 minutes"));
// // childs1.add(new AppointmentDO("KIRAN KATTA", "address",
// "10:00 AM",
// // "40 minutes"));
// // childs1.add(new AppointmentDO("R.MOHAN REDDY", "address",
// "11:00 AM",
// // "40 minutes"));
// childs2.add(new AppointmentDO("KIRAN KATTA", "address", "12:00 PM",
// "40 minutes"));
// childs2.add(new AppointmentDO("R.MOHAN REDDY", "address", "10:30 AM",
// "40 minutes"));
// childs3.add(new AppointmentDO("KIRAN KATTA", "address", "10:45 AM",
// "40 minutes"));
// map = new HashMap<String, ArrayList<AppointmentDO>>();
// map.put(alist.get(0), childs1);
// map.put(alist.get(1), childs2);
// map.put(alist.get(2), childs3);
}
protected void sliderCalendar() {
// ---------------------------------Slider Calendar Implementation
// -------------------------------------------//
llCalTop = (LinearLayout) myAppointment.findViewById(R.id.llCalTop);
lvItems = (HorizontialListView) myAppointment
.findViewById(R.id.lvItems);
tvMonth = (TextView) myAppointment.findViewById(R.id.tvMonth);
ivleft = (ImageView) myAppointment.findViewById(R.id.ivleft);
ivright = (ImageView) myAppointment.findViewById(R.id.ivright);
commonBL = new CommonBL(MyAppointment.this, MyAppointment.this);
cal = Calendar.getInstance();
if (selectedDay != -1 && selectedMonth != -1 && selectedYear != -1) {
cal.set(selectedYear, selectedMonth, selectedDay);
}
if (lvItems.getAdapter() == null) {
calendarAdapter = new CalendarAdapter(MyAppointment.this, cal);
calendarAdapter.setSelectedPosition(selectedDay - 1);
lvItems.setAdapter(calendarAdapter);
tvMonth.setText(CalendarUtils.getMonthFromNumber(cal
.get(Calendar.MONTH) + 1));
// /// -----------------Trying to scroll at selected date ---------------------//
// ---------------/////
lvItems.scrollTo((selectedDay - 1) * (60)
+ (lvItems.getChildCount() - (selectedDay - 1)));
} else {
calendarAdapter.notifyDataSetChanged();
}
// --------------------**--------------------------------------//
lvItems.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
appointmentdate = "";
calendarAdapter.setSelectedPosition(position);
// ----------------------**----------------//
selectedDay = position;
selectedMonth = cal.get(Calendar.MONTH);
selectedYear = cal.get(Calendar.YEAR);
Toast.makeText(getApplicationContext(),
selectedDay + "/" + selectedMonth + "/" + selectedYear,
Toast.LENGTH_SHORT).show();
LogUtils.errorLog(
"Clicked Date",
(position + 1)
+ ""
+ CalendarUtils.getMonthFromNumber(cal
.get(Calendar.MONTH) + 1) + ","
+ cal.get(Calendar.YEAR));
if (cal.get(Calendar.MONTH) + 1 < 10)
appointmentdate = (position + 1) + "-0"
+ (cal.get(Calendar.MONTH) + 1) + "-"
+ cal.get(Calendar.YEAR);
else
appointmentdate = (position + 1) + "-"
+ (cal.get(Calendar.MONTH) + 1) + "-"
+ cal.get(Calendar.YEAR);
}
});
ivleft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cal.add(Calendar.MONTH, -1);
tvMonth.setText(CalendarUtils.getMonthFromNumber(cal
.get(Calendar.MONTH) + 1)
+ " "
+ cal.get(Calendar.YEAR));
calendarAdapter.refresh(cal);
calendarAdapter.setSelectedPosition(0);
}
});
ivright.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cal.add(Calendar.MONTH, 1);
tvMonth.setText(CalendarUtils.getMonthFromNumber(cal
.get(Calendar.MONTH) + 1)
+ " "
+ cal.get(Calendar.YEAR));
calendarAdapter.refresh(cal);
calendarAdapter.setSelectedPosition(0);
}
});
// --------------------------------------/**/--------------------------------------------------//
}
private class CalendarAdapter extends BaseAdapter {
private String week[] = { "Su", "M", "T", "W", "Th", "F", "S" };
private Context context;
private int seletedPosition;
private Calendar cal;
public CalendarAdapter(Context context, Calendar cal) {
this.cal = cal;
this.context = context;
}
#Override
public int getCount() {
return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
#Override
public Object getItem(int position) {
return position;
}
public void setSelectedPosition(int seletedPosition) {
this.seletedPosition = seletedPosition;
notifyDataSetChanged();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(
R.layout.calendar_cell, null);
viewHolder.tvweek = (TextView) convertView
.findViewById(R.id.tvweek);
viewHolder.tvday = (TextView) convertView
.findViewById(R.id.tvday);
convertView.setTag(viewHolder);
} else
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.tvday.setText((position + 1) + "");
cal.set(Calendar.DAY_OF_MONTH, position + 1);
viewHolder.tvweek
.setText(week[cal.get(Calendar.DAY_OF_WEEK) - 1 % 7]);
if (seletedPosition == position) {
viewHolder.tvday.setBackgroundResource(R.drawable.date_hover);
viewHolder.tvday.setTextColor(getResources().getColor(
R.color.white_color));
} else {
viewHolder.tvday.setBackgroundResource(0);
viewHolder.tvday.setTextColor(getResources().getColor(
R.color.date_color));
}
return convertView;
}
public void refresh(Calendar cal) {
this.cal = cal;
notifyDataSetChanged();
}
}
private static class ViewHolder {
public TextView tvweek, tvday;
}
#Override
public void dataRetreived(Response data) {
if (data.data != null) {
if (data.method == ServiceMethods.WS_INSERT_REQUEST) {
requestDO = (RequestDO) data.data;
if (requestDO != null) {
LogUtils.errorLog("Data Came", requestDO.Reason);
}
}
}
}
}
Try listView.setSelection( index );
I'm getting NullPointerException error when I using MapFragment in Fragment.
I can't post image,this is LogCat:
java.lang.NullPointerException
com.ps.admin.EventsFragment.onCreateView(EventsFragment.Java:103)
Basically when activity start twice has been stop!!
package com.ps.admin;
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_events, container, false);
app = getActivity();
month = Calendar.getInstance();
prevMonth = (Calendar) month.clone();
prevMonth.roll(Calendar.MONTH, false);
try{
map = ((MapFragment) app.getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}catch (Exception e){
Toast.makeText(app, e.toString(), Toast.LENGTH_LONG).show();
}
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {
days.add(String.valueOf(i));
}
tx = (TextView)v.findViewById(R.id.textView1);
cCalendar = (GridView)v.findViewById(R.id.gridView1);
cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
readCalendarEvent(app);
cCalendar.setOnTouchListener(gestureListener);
cCalendar.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
RelativeLayout rld = (RelativeLayout)arg1.findViewById(R.id.rld);
try{
popupHoney(rld.getTag().toString(),getRelativeLeft(arg1),getRelativeTop(arg1));
}catch (Exception e){
}
}
});
cCalendar.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int arg2, long arg3) {
RelativeLayout mn = (RelativeLayout)view.findViewById(R.id.main);
TextView tx = (TextView)view.findViewById(R.id.textView1);
addCalendarEvent(arg2);
tx.setText("+");
mn.setBackgroundResource(R.color.Green);
return false;
}
});
return v;
}
private int getRelativeLeft(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getLeft();
else
return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}
private int getRelativeTop(View myView) {
if (myView.getParent() == myView.getRootView())
return myView.getTop();
else
return myView.getTop() + getRelativeTop((View) myView.getParent());
}
private String getDayOfMonth() {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
String date = c.getTime().toString().substring(0, 3).toString();
if (date.equals("Mon")){
return "1";
}else
if (date.equals("Tue")){
return "2";
}else
if (date.equals("Wed")){
return "3";
}else
if (date.equals("Thu")){
return "4";
}else
if (date.equals("Fri")){
return "5";
}else
if (date.equals("Sat")){
return "6";
}else
if (date.equals("Sun")){
return "7";
}
return date;
}
public String getFirstDay(int day, int month, int year)
{
Calendar cal = new GregorianCalendar();
cal.set(Calendar.DATE, day);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_MONTH, 1);
switch (cal.get(Calendar.DAY_OF_WEEK)) {
case Calendar.SUNDAY:
return "SUNDAY";
case Calendar.MONDAY:
return "MONDAY";
case Calendar.TUESDAY:
return "TUESDAY";
case Calendar.WEDNESDAY:
return "WEDNESDAY";
case Calendar.THURSDAY:
return "THURSDAY";
case Calendar.FRIDAY:
return "FRIDAY";
case Calendar.SATURDAY:
return "SATURDAY";
}
return null;
}
public static ArrayList<String> readCalendarEvent(Context context) {
Cursor cursor = context.getContentResolver()
.query(
Uri.parse("content://com.android.calendar/events"),
new String[] { "calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation" }, null,
null, null);
cursor.moveToFirst();
String CNames[] = new String[cursor.getCount()];
nameOfEvent.clear();
startDates.clear();
endDates.clear();
descriptions.clear();
for (int i = 0; i < CNames.length; i++) {
nameOfEvent.add(cursor.getString(1));
startDates.add(getDate(Long.parseLong(cursor.getString(3))));
endDates.add(getDate(Long.parseLong(cursor.getString(4))));
descriptions.add(cursor.getString(2));
CNames[i] = cursor.getString(1);
cursor.moveToNext();
}
return nameOfEvent;
}
#SuppressLint("SimpleDateFormat")
public static String getDate(long milliSeconds) {
SimpleDateFormat formatter = new SimpleDateFormat(
"dd/MM/yyyy hh:mm:ss a");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
private void addCalendarEvent(int day){
long startTime = 0;
Calendar calendar = Calendar.getInstance();
String startDate = calendar.get(Calendar.YEAR)+"-"+(calendar.get(Calendar.MONTH)+1)+"-"+(day-space+1);
try {
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
startTime=date.getTime();
}catch (Exception e){
}
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime",startTime);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
app.startActivity(intent);
}
private void editCalendarEvent(int calendarEventID){
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(Uri.parse("content://com.android.calendar/events/" + String.valueOf(calendarEventID)));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
app.startActivity(intent);
}
public class ProductAdapter extends ArrayAdapter<String> {
ArrayList<String> items;
LayoutInflater vi;
public ProductAdapter(Context context, int textViewResourceId,
ArrayList<String> objects) {
super(context, textViewResourceId, objects);
this.items = objects;
vi = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#SuppressLint({ "NewApi", "SimpleDateFormat" })
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = vi.inflate(R.layout.product_event, null);
}
try {
RelativeLayout bg = (RelativeLayout)convertView.findViewById(R.id.rld);
RelativeLayout mn = (RelativeLayout)convertView.findViewById(R.id.main);
TextView name = (TextView)convertView.findViewById(R.id.textView1);
name.setText(items.get(position).toString());
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
String localTime = format1.format(month.getTime());
System.out.println(localTime);
if (Integer.valueOf(days.get(position))<10) {
if (("0"+days.get(position)+""+localTime.substring(2, localTime.length())).equals(localTime)){
mn.setBackgroundResource(R.color.Blue_Trans);
}
}else{
if ((days.get(position)+""+localTime.substring(2, localTime.length())).equals(localTime)){
mn.setBackgroundResource(R.color.Blue_Trans);
}
}
for (int j = 0; j < startDates.size(); j++) {
if (days.get(position).equals("")){
System.out.println(days.get(position));
}else{
if (Integer.valueOf(days.get(position))<10) {
if (("0"+days.get(position)+""+localTime.substring(2, localTime.length())).equals(startDates.get(j).substring(0, 10))){
bg.setBackgroundResource(R.color.Green);
bg.setTag(j);
}
}else{
if ((days.get(position)+""+localTime.substring(2, localTime.length())).equals(startDates.get(j).substring(0, 10))){
bg.setBackgroundResource(R.color.Green);
bg.setTag(j);
}
}
}
}
} catch (Exception e) {
}finally{
app.setProgressBarIndeterminateVisibility(false);
}
return convertView;
}
}
class MyGestureDetector extends SimpleOnGestureListener {
#SuppressLint("NewApi")
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
month.set(month.get(Calendar.YEAR), month.get(Calendar.MONTH)+1,month.get(Calendar.DAY_OF_MONTH),month.get(Calendar.HOUR),month.get(Calendar.MINUTE));
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
days.clear();
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {
days.add(String.valueOf(i));
}
cCalendar.startAnimation(AnimationUtils.loadAnimation(app, R.anim.righttoleft));
cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
app.getActionBar().setTitle(format1.format(month.getTime()));
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
month.set(month.get(Calendar.YEAR), month.get(Calendar.MONTH)-1,month.get(Calendar.DAY_OF_MONTH),month.get(Calendar.HOUR),month.get(Calendar.MINUTE));
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
days.clear();
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {
days.add(String.valueOf(i));
}
cCalendar.startAnimation(AnimationUtils.loadAnimation(app, R.anim.lefttoright));
cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
app.getActionBar().setTitle(format1.format(month.getTime()));
}
} catch (Exception e) {
// nothing
}
return false;
}
}
#Override
public void onResume(){
super.onResume();
int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
days.clear();
if(Integer.valueOf(getDayOfMonth())>1){
for (int i = 0; i < Integer.valueOf(getDayOfMonth())-1; i++) {
days.add("");
}
space = Integer.valueOf(getDayOfMonth())-1;
}
for (int i = 1; i <= lastDay; i++) {
days.add(String.valueOf(i));
}
cCalendar.setAdapter(new ProductAdapter(app, android.R.layout.simple_expandable_list_item_1, days));
}
#SuppressLint("NewApi")
private void popupHoney(final String builded,float f,float g) {
try {
LayoutInflater inflater = (LayoutInflater) app
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.toast_popup,
(ViewGroup) v.findViewById(R.id.popup_element));
pwindow = new PopupWindow(layout,WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,true);
pwindow.showAtLocation(layout, Gravity.NO_GRAVITY, Math.round(f)-40, Math.round(g)-30);
TextView tx = (TextView)layout.findViewById(R.id.textView2);
TextView tx1 = (TextView)layout.findViewById(R.id.textView1);
RelativeLayout close = (RelativeLayout)layout.findViewById(R.id.popup);
tx.setText(" "+nameOfEvent.get(Integer.valueOf(builded))+" ");
tx1.setText(" "+nameOfEvent.get(Integer.valueOf(builded))+" ");
tx.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try{
String loca = descriptions.get(Integer.valueOf(builded));
String[] separated = loca.split(",");
setLatLang(Double.valueOf(separated[0]),Double.valueOf(separated[1]),nameOfEvent.get(Integer.valueOf(builded)),startDates.get(Integer.valueOf(builded)).substring(0, startDates.get(Integer.valueOf(builded)).length()-6)+"\n"+
endDates.get(Integer.valueOf(builded)).substring(0, endDates.get(Integer.valueOf(builded)).length()-6));
pwindow.dismiss();
}catch(Exception e){
Toast.makeText(app, "Bu bir harita notu değildir!", Toast.LENGTH_LONG).show();
}}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pwindow.dismiss();
}
});
} catch (Exception e) {
}
app.setProgressBarIndeterminateVisibility(false);
}
public void setLatLang(final double lat,final double lon,final String tit,String date){
sydney = new LatLng(lat, lon);
//map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(sydney, 16));
//map.addCircle(new CircleOptions().center(sydney).fillColor(Color.TRANSPARENT).radius(100).strokeColor(Color.BLUE));
map.addMarker(new MarkerOptions()
.title(tit)
.snippet(date)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_mic))
.visible(true)
.anchor(0.5f, 1)
.position(sydney));
map.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(lat, lon)) // Sydney
/*.add(new LatLng(-18.142, 178.431)) // Fiji
.add(new LatLng(21.291, -157.821)) // Hawaii
.add(new LatLng(37.423, -122.091)) */ // Mountain View
);
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
/*String label = tit;
String uriBegin = "geo:" + lat + "," + lon;
String query = lat + "," + lon + "(" + label + ")";
String encodedQuery = Uri.encode(query);
String uriString = uriBegin + "?q=" + encodedQuery + "&z=16";
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, uri);
startActivity(intent);*/
}
});
}
}
The problem is that you saved the Activity reference in onCreateView, and also tried to dereference it.
Error can be from following lines in your code :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//your code ...
app = getActivity(); //getActivity() can return null, so app will be null
//your code ...
map = ((MapFragment) app.getFragmentManager().findFragmentById(R.id.map)).getMap(); //possible NPE
Correct approach is save the Activity reference in onAttach, and dereference it.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
app = activity; //correct place to get activity reference
//your code ...
map = ((MapFragment) app.getFragmentManager().findFragmentById(R.id.map)).getMap();
}