Android Google Maps Api v2 In Fragment : NullPointerException error - java

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();
}

Related

Binary XML file line #18: Binary XML file line #18: Error inflating class com.qdocs.smartschool.utils.CustomCalendar

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 can't display the timer in a TextView

I've created a Listview with a Countdown timer and below is the code :
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
long timeLeftMS ;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
startTimer(viewHolder.handler);
// Return the completed view to render on screen
return convertView;
}
private void startTimer(final Handler handler) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
timeLeftMS = l;
handler.sendEmptyMessage(0);
}
#Override
public void onFinish() {
}
}.start();
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
TicketModel class :
public class TicketModel {
String titreTicket;
String slaTicket;
String DateTicket;
String UrgenceTicket;
boolean ticketEnRetard;
String TempsRestantTicket;
public TicketModel(String titreTicket, String slaTicket, String dateTicket, String tempsRestantTicket) {
this.titreTicket = titreTicket;
this.slaTicket = slaTicket;
DateTicket = dateTicket;
TempsRestantTicket = tempsRestantTicket;
}
public String getTitreTicket() {
return titreTicket;
}
public String getSlaTicket() {
return slaTicket;
}
public String getDateTicket() {
return DateTicket;
}
public String getUrgenceTicket() {
return UrgenceTicket;
}
public void setUrgenceTicket(String urgenceTicket) {
UrgenceTicket = urgenceTicket;
}
public void setTempsRestantTicket(String tempsRestantTicket) {
TempsRestantTicket = tempsRestantTicket;
}
public String getTempsRestantTicket() {
return TempsRestantTicket;
}
public boolean isTicketEnRetard() {
return ticketEnRetard;
}
public void setTicketEnRetard(boolean ticketEnRetard) {
this.ticketEnRetard = ticketEnRetard;
}
}
Where I'm populating my ListView :
public class ListTickets extends AppCompatActivity {
ArrayList<TicketModel> TicketModels;
ListView listView;
private static TicketAdapter adapter;
String session_token, nameUser, idUser, firstnameUser, nbTicket;
RequestQueue queue;
String titreTicket, slaTicket, urgenceTicket,
demandeurTicket, categorieTicket, etatTicket, dateDebutTicket,
dateEchanceTicket, dateClotureTicket, descriptionTicket, lieuTicket;
boolean ticketEnretard;
public static int nbTicketTab = 6;
public static int nbInfoTicket = 12;
public static String[][] ticketTab ;
public static String[][] infoTicket ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
queue = Volley.newRequestQueue(this);
Intent i = getIntent();
session_token = i.getStringExtra("session");
nbTicket = i.getStringExtra("nb");
nameUser = i.getStringExtra("nom");
firstnameUser = i.getStringExtra("prenom");
idUser = i.getStringExtra("id");
listView=(ListView)findViewById(R.id.list);
TicketModels = new ArrayList<>();
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
infoTicket = new String[Integer.valueOf(nbTicket)][nbInfoTicket];
String url = FirstEverActivity.GLPI_URL+"search/Ticket";
List<KeyValuePair> params = new ArrayList<>();
params.add(new KeyValuePair("criteria[0][field]","5"));
params.add(new KeyValuePair("criteria[0][searchtype]","equals"));
params.add(new KeyValuePair("criteria[0][value]",idUser));
params.add(new KeyValuePair("forcedisplay[0]","4"));
params.add(new KeyValuePair("forcedisplay[1]","10"));
params.add(new KeyValuePair("forcedisplay[2]","7"));
params.add(new KeyValuePair("forcedisplay[3]","12"));
params.add(new KeyValuePair("forcedisplay[4]","15"));
params.add(new KeyValuePair("forcedisplay[5]","30"));
params.add(new KeyValuePair("forcedisplay[6]","18"));
params.add(new KeyValuePair("forcedisplay[7]","21"));
params.add(new KeyValuePair("forcedisplay[8]","83"));
params.add(new KeyValuePair("forcedisplay[9]","82"));
params.add(new KeyValuePair("forcedisplay[10]","16"));
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, generateUrl(url, params), null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
// Récupération des items pour le row_item
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
//Récupération du reste
demandeurTicket = oneTicket.getString("4");
categorieTicket = oneTicket.getString("7");
etatTicket = oneTicket.getString("12");
dateEchanceTicket = oneTicket.getString("18");
descriptionTicket = oneTicket.getString("21");
lieuTicket = oneTicket.getString("83");
dateClotureTicket = oneTicket.getString("16");
ticketEnretard = getBooleanFromSt(oneTicket.getString("82"));
System.out.println("Direct = " + oneTicket.getString("82") + "\n After f(x) = " + getBooleanFromSt(oneTicket.getString("82")));
} catch (JSONException e) {
Log.e("Nb of data: "+Jdata.length()+" || "+"Error JSONArray at "+i+" : ", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket); //TimeLeft value here
ticketTab[i][5] = String.valueOf(ticketEnretard);
infoTicket[i][0] = demandeurTicket;
infoTicket[i][1] = urgenceText(urgenceTicket);
infoTicket[i][2] = categorieTicket;
infoTicket[i][3] = etatText(etatTicket);
infoTicket[i][4] = dateDebutTicket;
infoTicket[i][5] = slaTicket;
infoTicket[i][6] = dateEchanceTicket;
infoTicket[i][7] = titreTicket;
infoTicket[i][8] = descriptionTicket;
infoTicket[i][9] = lieuTicket;
infoTicket[i][10] = calculTempsRestant(dateDebutTicket, slaTicket);
infoTicket[i][11] = dateClotureTicket;
System.out.println("Temps restant = "+calculTempsRestant(dateDebutTicket, slaTicket));
System.out.println("SLA = "+slaTicket);
System.out.println("Between : "+getBetweenBrackets(slaTicket));
System.out.println("Minimum : "+getMinTemps(slaTicket));
System.out.println("Maximim : "+getMaxTemps(slaTicket));
}
System.out.println("*** Tab Ticket ***");
System.out.println("isLate: "+ticketTab[0][5]);
System.out.println("\n\n*** Info Ticket ***");
System.out.println("Titre: "+infoTicket[0][7]);
// Populate the ListView
addModelsFromTab(ticketTab);
adapter = new TicketAdapter(TicketModels,getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TicketModel TicketModel= TicketModels.get(position);
Snackbar.make(view, "Index = "+position, Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
Intent i = new Intent(getApplicationContext(), InfoTicket.class);
i.putExtra("session",session_token);
i.putExtra("nom",nameUser);
i.putExtra("prenom",firstnameUser);
i.putExtra("id",idUser);
i.putExtra("infoTicket", infoTicket[position]);
startActivity(i);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
//progressBar.setVisibility(View.GONE);
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
}
private void addModelsFromTab(String[][] ticketTab) {
for (int i = 0; i < ticketTab.length; i++){
TicketModel ticket = new TicketModel(ticketTab[i][0], ticketTab[i][1], ticketTab[i][2], ticketTab[i][4]);
ticket.setUrgenceTicket(ticketTab[i][3]);
ticket.setTicketEnRetard(Boolean.parseBoolean(ticketTab[i][5]));
//ticket.setTempsRestantTicket(ticketTab[i][4]);
TicketModels.add(ticket);
}
}
private String calculTempsRestant(String dateDebutTicket, String slaTicket) {
String minTemps = getMinTemps(slaTicket);
String maxTemps = getMaxTemps(slaTicket);
long dateDebutMS = getDateDebutMS(dateDebutTicket);
long currentTimeMS = CurrentTimeMS();
long minTempsMS = hourToMSConvert(minTemps);
long differenceCurrentDebut = currentTimeMS - dateDebutMS;
long tempsRestant = minTempsMS - differenceCurrentDebut;
return String.valueOf(tempsRestant);
}
}
The issue I have is that I want to display the timer (the timeLeftText String) in the txtTempsRestant TextView, but I can't access it. Can anyone give me advice?
When I print in the console and the output is correct, but I'm not able to display it. Should I change the way I'm working?
Modified Adapter class to make the count down work properly.
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
// View lookup cache
private class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtTempsRestant;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
System.out.println("handler");
Bundle bundle = msg.getData();
long timeLeftMS = bundle.getLong("time");
int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
int minute = (int) ((timeLeftMS / (60000)) % 60);
int seconde = (int)timeLeftMS % 60000 / 1000;
String timeLeftText = "";
if (hour<10) timeLeftText += "0";
timeLeftText += hour;
timeLeftText += ":";
if (minute<10) timeLeftText += "0";
timeLeftText += minute;
timeLeftText += ":";
if (seconde<10) timeLeftText += "0";
timeLeftText += seconde;
txtTempsRestant.setText(timeLeftText);
}
};
public void startTimer(long timeLeftMS) {
CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {
#Override
public void onTick(long l) {
Bundle bundle = new Bundle();
bundle.putLong("time", l);
Message message = new Message();
message.setData(bundle);
handler.sendMessage(message);
}
#Override
public void onFinish() {
}
}.start();
}
}
public TicketAdapter(ArrayList<TicketModel> data, Context context) {
super(context, R.layout.row_item_ticket, data);
this.dataSet = data;
this.mContext=context;
//startUpdateTimer();
}
#Override
public void onClick(View v) {
int position=(Integer) v.getTag();
Object object= getItem(position);
TicketModel TicketModel=(TicketModel)object;
switch (v.getId())
{
case R.id.item_info:
Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
.setAction("No action", null).show();
break;
}
}
private int lastPosition = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
TicketModel TicketModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
final ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);
result=convertView;
viewHolder.startTimer(Long.valueOf(TicketModel.getTempsRestantTicket()));
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result=convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.txtName.setText(TicketModel.getTitreTicket());
viewHolder.txtDate.setText(TicketModel.getDateTicket());
viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
//viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
viewHolder.info.setOnClickListener(this);
viewHolder.info.setTag(position);
System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct
// Return the completed view to render on screen
return convertView;
}
private int getColorBG(boolean ticketEnRetard) {
int color;
if (ticketEnRetard){
color = Color.parseColor("#3caa0000");
}
else{
color = Color.parseColor("#ffffff");
}
return color;
}
private int getIconUrgence(String urgenceTicket) {
int icon;
if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
icon = R.drawable.basse;
}
else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
icon = R.drawable.haute;
}
else {
icon = R.drawable.moyenne;
}
return icon;
}
}
You don't want to declare the TextView static if you'll be changing the value.
Try declaring it outside the method here:
public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{
private ArrayList<TicketModel> dataSet;
Context mContext;
static long timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());
private TextView txtTempsRestant ;
// View lookup cache
private static class ViewHolder {
TextView txtName;
TextView txtType;
TextView txtDate;
TextView txtSLA;
ImageView info;
RelativeLayout layout;
TextView txtTempsRestant ;
}
Hi i have a code its good
beucse u dont need definination 3 textview for right and left ,....
You will create one TextView and use this code for create
private void Time() {
mCountTimer = new CountDownTimer(aTime, 1000) {
#Override
public void onTick(long millisUntilFinished) {
aMinute = (int) (millisUntilFinished / 1000) / 60;
mSecond = (int) (millisUntilFinished / 1000) % 60;
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", aMinute, mSecond));
}
#Override
public void onFinish() {
mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", 0, 0));
mSend_Again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Your EVENT
}
});
}
}.start();
}

how to cancel method of count down timer to stop working

I have list of music that user set time to play. I want to have a button to cancel m count down timer .
I test some way but it doesn't work at all.
here is my code to play and set time to play.
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = new HashMap<>();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info int'o it
textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),null);
//notify about the data change
notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
make the count down timer an instance variable;
private CountDownTimer timer;
then delegate your count to this variable:
#Override
public void onClick(View v) {
...
timer = new CountDownTimer(result, 1000) {
...
}
}
now you can stop the timer whenever you want to:
timer.cancel();
Check this code, working Successfull
call class from here
timer = new CounterClass(timeInmilles, 1000);
timer.start();
CounterClass is here
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
}
public void onTick(long millisUntilFinished) {
}
}
use to cancel see below line
timer.cancel()

How to scroll to a particular item in Horizontal List View?

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 );

unable to bold or highlight event dates of android Custom calendar

#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.

Categories

Resources