I'm using a library called singlerowcalendar in my app. My app contains a toggle button that will change the calendar mode form showing days of month to showing months of year.
days of month view
months of year view
The thing is I'm including the calendar setup code in the toggle change listener, and as a consequence the app keeps piling up calendar selection change listeners, and now I get the calendar change callback to fire multiple times.
Is there a way to keep only one calendar change listener and removing the others.
here is the code of the toggle button where I call setCalendar();
toggle.addOnButtonCheckedListener(new MaterialButtonToggleGroup.OnButtonCheckedListener() {
#Override
public void onButtonChecked(MaterialButtonToggleGroup group, int checkedId, boolean isChecked) {
if (isChecked && checkedId == R.id.btn_day) {
selectedTimeFrame = "day";
tvChartTitleDay.setVisibility(View.VISIBLE);
tvChartTitleMonth.setVisibility(View.GONE);
Log.d("pongo2", "day selecteeeeed");
}
if (isChecked && checkedId == R.id.btn_month) {
selectedTimeFrame = "month";
tvChartTitleDay.setVisibility(View.GONE);
tvChartTitleMonth.setVisibility(View.VISIBLE);
Log.d("pongo2", "month selecteeeeed");
}
setCalendar();
}
});
Here is the calendar setup code.
private void setCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
ArrayList<Date> list = new ArrayList<>();
if(selectedTimeFrame.equals("day")) {
calendar.add(Calendar.DAY_OF_MONTH , -700);
for (int i = 0; i < 30; i++) {
list.add(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH , -1);
}
tvMonth.setVisibility(View.VISIBLE);
tvMonth.setText(DateUtils.INSTANCE.getMonth3LettersName(calendar.getTime()));
tvYear.setText(DateUtils.INSTANCE.getYear(calendar.getTime()));
} else {
calendar.add(Calendar.MONTH , -24);
for (int i = 0; i < 30; i++) {
list.add(calendar.getTime());
calendar.add(Calendar.MONTH , -1);
}
tvMonth.setVisibility(View.GONE);
tvYear.setText(DateUtils.INSTANCE.getYear(calendar.getTime()));
}
myCalendar.setDates(list);
myCalendar.init();
myCalendar.select(5);
}
calendar change observer is here:
private void initCalendar() {
myCalendarChangesObserver = new CalendarChangesObserver() {
#Override
public void whenWeekMonthYearChanged(String s, String s1, String s2, String s3, Date date) {
}
#Override
public void whenSelectionChanged(boolean b, int i, Date date) {
if (b) {
tvMonth.setText(DateUtils.INSTANCE.getMonth3LettersName(date));
tvYear.setText(DateUtils.INSTANCE.getYear(date));
Log.d("pongo", date.toString());
loadNewData();
}
}
#Override
public void whenCalendarScrolled(int i, int i1) {
}
#Override
public void whenSelectionRestored() {
}
#Override
public void whenSelectionRefreshed() {
}
};
myCalendar.setCalendarChangesObserver(myCalendarChangesObserver);
}
Related
I am a beginner level programmer and I am again here to take everybody's help and solve my problem. Actually I don't have an error this time but I need to do something which I am not able to,
The thing is that I want to use a for loop 3 times and everytime I have a condition to check if my Quantity1 = 0 or not, again if my Quantity2 is = 0 or not and same for the third time. I can also repeat the code 3 times but I need to do this is because, I am uploading my data to a realtime database. And I am uploading my SelectedDate1 if Quantity1 != 0 and same for the three times, but to read them I have to know that how many Quantities and SelectedDates are uploaded and for that I have created a variable OrderQuantity. But the problem is if the user has selected the 1st date and the 3rd date and not the 2nd one as its quantity is 0, so when it is uploaded it shows OrderQuantity=2and the selectedDate1 comes under 1 but the 3rd date comes under 2nd node with name 3, but it should come with the name of variable+i, I hope you understand my question. And if not, please comment and I'll provide you an english video for what I want. Hoping your help as soon as possible.-
I think there is no use of main_activity.xml as it will make my question very big.
But here goes my MainActivity.java (without imports as it was very big)
public class MainActivity extends AppCompatActivity implements DatePickerFragment.applyDate, AdapterView.OnItemSelectedListener {
String CurrentDateString;
TextView mainDate;
Integer OrderQuantity = 3;
String itemOneDate;
String itemTwoDate;
String itemThreeDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button SelectDate1 = findViewById(R.id.SelectDateButton1);
Button SelectDate2 = findViewById(R.id.SelectDateButton2);
Button SelectDate3 = findViewById(R.id.SelectDateButton3);
SelectDate1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(1, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate1;
}
});
SelectDate2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(2, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate2;
}
});
SelectDate3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment datePicker = DatePickerFragment.newInstance(3, MainActivity.this);
datePicker.show(getSupportFragmentManager(), "Pick item order date");
mainDate = SelectDate3;
}
});
ArrayAdapter<CharSequence> FoodAdapter = ArrayAdapter.createFromResource(this, R.array.FoodList, android.R.layout.simple_spinner_item);
FoodAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner SelectItem1 = findViewById(R.id.SelectItem1);
SelectItem1.setAdapter(FoodAdapter);
SelectItem1.setOnItemSelectedListener(this);
Spinner SelectItem2 = findViewById(R.id.SelectItem2);
SelectItem2.setAdapter(FoodAdapter);
SelectItem2.setOnItemSelectedListener(this);
Spinner SelectItem3 = findViewById(R.id.SelectItem3);
SelectItem3.setAdapter(FoodAdapter);
SelectItem3.setOnItemSelectedListener(this);
ArrayAdapter<CharSequence> QuantityAdapter = ArrayAdapter.createFromResource(this, R.array.Quantity, android.R.layout.simple_spinner_item);
QuantityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner Quantity1 = findViewById(R.id.SelectQuantity1);
Quantity1.setAdapter(QuantityAdapter);
Quantity1.setOnItemSelectedListener(this);
Spinner Quantity2 = findViewById(R.id.SelectQuantity2);
Quantity2.setAdapter(QuantityAdapter);
Quantity2.setOnItemSelectedListener(this);
Spinner Quantity3 = findViewById(R.id.SelectQuantity3);
Quantity3.setAdapter(QuantityAdapter);
Quantity3.setOnItemSelectedListener(this);
Button DoneButton = findViewById(R.id.DoneButton);
EditText PersonName = findViewById(R.id.PersonName);
EditText PersonPhone = findViewById(R.id.PersonPhone);
EditText PersonAddress = findViewById(R.id.PersonAddress);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DoneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference Name = database.getReference(PersonPhone.getText().toString() + "/Name");
Name.setValue(PersonName.getText().toString());
DatabaseReference Phone = database.getReference(PersonPhone.getText().toString() + "/Phone");
Phone.setValue(PersonPhone.getText().toString());
DatabaseReference Address = database.getReference(PersonPhone.getText().toString() + "/Address");
Address.setValue(PersonAddress.getText().toString());
//I need help here in these three if-else statements
if (Quantity1.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/1" + "/Date");
dateOne.setValue(itemOneDate);
}
if (Quantity2.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/2" + "/Date");
dateOne.setValue(itemTwoDate);
}
if (Quantity3.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders" + "/3" + "/Date");
dateOne.setValue(itemOneDate);
}
DatabaseReference OrderQuantities = database.getReference(PersonPhone.getText().toString() + "/OrderQuantity");
OrderQuantities.setValue(OrderQuantity);
}
});
}
public void setDate(int selectedYear, int selectedMonth, int selectedDay, int buttonNumber) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, selectedYear);
c.set(Calendar.MONTH, selectedMonth);
c.set(Calendar.DAY_OF_MONTH, selectedDay);
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String CurrentDateString = format.format(c.getTime());
mainDate.setText(CurrentDateString);
if (buttonNumber == 1) {
itemOneDate = CurrentDateString;
} else if (buttonNumber == 2) {
itemTwoDate = CurrentDateString;
} else if (buttonNumber == 3) {
itemThreeDate = CurrentDateString;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Here is the image of the data saved on realtime database when 1st and 3rd date are selected.-
Also see that what I have selected on the virtual device.
And here is the link from where I learnt to make a datePickerFragment for selecting date.
Edit: go object-oriented
Edit: since my first two suggestions didn’t work for you, I am suggesting using some abstraction. Declare a class to hold a spinner and its related data, and iterate a list of such objects. Your list can hold a variable number of objects so there will be a variable number of spinners. Caveat: I don’t know Android UI programming, so may be missing a detail or two there. And I still have not compiled my code myself.
public class MySpinner {
private FirebaseDatabase database;
private Spinner quantity;
private String number;
private String itemDate;
public MySpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
this.database = database;
this.quantity = quantity;
this.number = number;
this.itemDate = itemDate;
}
/* #return true if there was a positive quantity to process, false otherwise */
public boolean processQuantity() {
if (quantity.getSelectedItem().toString().equals("0")) {
return false;
}
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
return true;
}
}
I have also object-orientedly fitted the class with a method to do the work for each spinner. Now with a list of objects of your class you may process each in turn in a loop like this:
for (MySpinner mySpinner : yourListOfMySpinners) {
if (! mySpinner.processQuantity()) { // quantity was 0
OrderQuantity -= 1;
}
}
I am leaving to yourself to fill objects into your list. There will probably also be some adjusting and tailoring that you will want to do.
Original answer follows.
Use an array or list
It’s not uncommon for beginners in programming to ask that question. It’s not quite the right question to ask. What you need is to iterate over your quantities in a loop. The solution to that is to put them into an array or list and iterate over that array or list. Code is not tested.
Spinner[] quantities = { Quantity1, Quantity2, Quantity3 };
for (int i = 0; i < quantities.length; i++) {
if (quantities[i].getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString() + "/Orders/" + (i + 1) + "/Date");
dateOne.setValue(itemTwoDate);
}
}
While it would be possible to select a variable the way you describe, it’s neither the best, the easiest nor the nicest solution.
Or use a method
An alternative is to declare a method that does the job for each quantity and call it three times without using any loop. In your case the method may need to take quite many arguments, though, which is not ideal.
processSpinner(database, Quantity1, "/1", itemOneDate);
processSpinner(database, Quantity2, "/2", itemTwoDate);
processSpinner(database, Quantity3, "/3", itemThreeDate);
Your method may be declared like:
private void processSpinner(FirebaseDatabase database,
Spinner quantity, String number, String itemDate) {
if (quantity.getSelectedItem().toString().equals("0")) {
OrderQuantity -= 1;
} else {
DatabaseReference dateOne = database.getReference(PersonPhone.getText().toString()
+ "/Orders" + number + "/Date");
dateOne.setValue(itemDate);
}
}
This is my menu occasion layout...I need to display this delete icon in some condition....
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="ringee.app.com.ringeeapp.Occasion">
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
<item
android:id="#+id/menu_cancel_event"
android:icon="#drawable/delete_icon"
android:title="Cancel event"
app:showAsAction="ifRoom"/>
</menu>
Is it possible to change the visibilty of this delete_icon here...Please help me to find out the code
This is my occasion activity code....here delete icon displayed while Adding event as well as Updating event..Here i need to visible delete icon only when the event is updated...I don't need to display that while Adding event....
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.menu=menu;
getMenuInflater().inflate(R.menu.menu_occasion, menu);
hide();
show();
return true;
}
public boolean show()
{
menu.findItem(R.id.menu_cancel_event).setVisible(true);
return true;
}
public boolean hide(){
menu.findItem(R.id.menu_cancel_event).setVisible(false);
return false;
}
// delete the selected event from event list added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_cancel_event:
//Setting the value for deleted event
eventMO.setIsDelete(1);
del();
//Triggering the Create event
doOnCLickAndOnOptionSelected();
return true;
}
return super.onOptionsItemSelected(item);
}
private void del() {
//Deleting the event from SQLLite
SQLiteDatabase db = dbHelper.getWritableDatabase();
final long Id = eventMO.getEventId();
db.delete("event", "Event_ID" + " = ?", new String[]{String.valueOf(Id)});
db.close();
}
// Common for delete event and save event(Create button click listener)
private void doOnCLickAndOnOptionSelected() {
//We need create button click listener for both delete as well as save the event.so we have this common method.we call this method from delete event and save event
prgDialog = new ProgressDialog(OccasionActivity.this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
prgDialog.show();
UserMO userMO = dbHelper.getRingeeUserData(1);
eventMO.setText(custom_Text.getText().toString());
eventMO.setPlace(event_Place.getText().toString());
eventMO.setEndTime(end_Time);
eventMO.setStartTime(start_Time);
try {
//date and time format changed here
String eventDate = btn_Date.getText().toString();
DateFormat date = new SimpleDateFormat("dd-M-yyyy");
Date date1 = date.parse(eventDate);
DateFormat convertDate = new SimpleDateFormat(" yyyy-MM-dd hh:mm:ss");
eventDate = convertDate.format(date1);
eventMO.setEventDate(eventDate);
} catch (ParseException e) {
e.printStackTrace();
}
//eventMO.setEventDate(btn_Date.getText().toString());
eventMO.setRingeeUserId(userMO.getRingeeUserId());
//event update functionality added here
final Long hidden_Text2 = eventId2;
if ((eventMO.getText() != null) && (eventMO.getPlace() != null) && (eventMO.getEventDate() != null)) {
if (hidden_Text2 != null) {
eventMO.setEventId(hidden_Text2);
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.updateEvent(eventMO, context);
}
#Override
protected void onPostExecute(String arg0) {
prgDialog.dismiss();
Intent contactAct = new Intent(getApplicationContext(), UserDashBoardActivity.class);
// Clears History of Activity
contactAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contactAct);
}
}.execute(null, null, null);
Toast.makeText(getApplicationContext(), "Details updated successfully", Toast.LENGTH_LONG).show();
} else {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return eventDelegates.addEvent(eventMO, context);
}
#Override
protected void onPostExecute(String eventId) {
prgDialog.dismiss();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("eventId", eventId);
editor.commit();
Intent contactAct = new Intent(getApplicationContext(), ContactActivity.class);
// Clears History of Activity
contactAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(contactAct);
}
}.execute(null, null, null);
Toast.makeText(getApplicationContext(), "Details added successfully", Toast.LENGTH_LONG).show();
}
} else {
prgDialog.dismiss();
Toast.makeText(context, "Please check Event custom text or Event place or Event date field", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_occasion);
context = getApplicationContext();
seekBar_startTime = (SeekBar) findViewById(R.id.seekBar1);
seekBar_startTime.setProgress(0);
seekBar_startTime.setMax(1440); //minutes in 24 hours(24*60)
seekBar_startTime.setProgress(1);
textView_startTime = (TextView) findViewById(R.id.textView1);
seekBar_endTime = (SeekBar) findViewById(R.id.seekBar2);
seekBar_endTime.setProgress(0);
seekBar_endTime.setMax(1440); //minutes in 24 hours(24*60)
seekBar_endTime.setProgress(1);
textView_endTime = (TextView) findViewById(R.id.textView2);
btn_Date = (Button) findViewById(R.id.event_date_button);
event_Place = (TextView) findViewById(R.id.Enter_Place);
custom_Text = (TextView) findViewById(R.id.Custom_Text);
checkBox_onEventDay=(CheckBox) findViewById(R.id.cb_onEventDay);
checkBox_2DaysBefore=(CheckBox) findViewById(R.id.cb_2DaysBefore);
checkBox_aWeekBefore=(CheckBox) findViewById(R.id.cb_aWeekBefore);
btn_create_button = (Button) findViewById(R.id.create_button);
sharedpreferences = context.getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
dbHelper = new DatabaseHelper(context);
btn_Date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "Occasion Date");
}
});
seekBar_startTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue, boolean fromUser) {
int minutes;
int hours;
minutes =progressValue % 60;
hours = progressValue/60;
int Hours=hours;
String am_pm;
if (hours==24)
{
hours = hours-12;
am_pm="AM";
}
else if
(hours> 12)
{
hours= hours- 12;
am_pm = "PM";
}
else if (hours ==0) {
hours =hours+12;
am_pm = "AM";
}
else if (hours <12) {
am_pm = "AM";
}
else
{
am_pm="PM";
}
if(minutes < 10)
{
//It shows 12 hours format with AM/PM to user
start_Time = String.valueOf(" "+hours+":0"+minutes+am_pm);
textView_startTime.setText("Event Start Time :" + start_Time);
//It pass 24hours format to database
start_Time = String.valueOf(Hours+":0"+minutes);
}
else {
//It shows 12 hours format with AM/PM to user
start_Time = String.valueOf(" "+hours+":"+minutes+am_pm);
textView_startTime.setText("Event Start Time :" + start_Time);
//It pass 24hours format to database
start_Time = String.valueOf(Hours+":"+minutes);
}
}
});
seekBar_endTime.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progressValue,boolean fromUser) {
int minutes;
int hours;
minutes = progressValue % 60;
hours = progressValue/60;
int Hours=hours;
String am_pm;
if (hours==24)
{
hours = hours-12;
am_pm="AM";
}
else if(hours> 12)
{
hours= hours- 12;
am_pm = "PM";
}
else if (hours ==0) {
hours =hours+12;
am_pm = "AM";
}
else if (hours <12) {
am_pm = "AM";
}
else
{
am_pm="PM";
}
if(minutes < 10)
{
//It shows 12 hours format with AM/PM to user
end_Time = String.valueOf(""+hours+":0"+minutes+am_pm);
textView_endTime.setText("Event Start Time :" + end_Time);
//It pass 24hours format to database
end_Time = String.valueOf(Hours+":0"+minutes);
}
else {
//It shows 12 hours format with AM/PM to user
end_Time = String.valueOf(""+hours+":"+minutes+am_pm);
textView_endTime.setText("Event Start Time :" + end_Time);
//It pass 24hours format to database
end_Time = String.valueOf(Hours+":"+minutes);
}
}
});
//eventid get from OccasionFragment here
Bundle bundle = this.getIntent().getExtras();
if (bundle != null) {
Long eventId1 = bundle.getLong("EventID");
eventId2 = eventId1;
String eventName = bundle.getString("EventName");
custom_Text.setText(eventName);
String eventPlace = bundle.getString("EventPlace");
event_Place.setText(eventPlace);
String eventDate = bundle.getString("EventDate");
try {
//String eventDate = bundle.getString("EventDate");
//time string removed from date here
String result = eventDate.split(" ")[0];
DateFormat sourceDate = new SimpleDateFormat("yyyy-MM-dd");
// parse the date string into Date object
Date date = sourceDate.parse(result);
DateFormat convertDate = new SimpleDateFormat("dd-M-yyyy");
// format the date into another format
result = convertDate.format(date);
btn_Date.setText(result);
} catch (ParseException e) {
e.printStackTrace();
}
//Event Start Time and Event End Time string added before the time here
String eventStart = bundle.getString("EventStart");
textView_startTime.setText("Event Start Time :" + eventStart);
String eventEnd = bundle.getString("EventEnd");
textView_endTime.setText("Event End Time :" + eventEnd);
}
checkBox_onEventDay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(OccasionActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}}
});
checkBox_2DaysBefore.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(OccasionActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}}
});
checkBox_aWeekBefore.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
Toast.makeText(OccasionActivity.this,
"Checked", Toast.LENGTH_LONG).show();
}}
});
btn_create_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doOnCLickAndOnOptionSelected();
}
});
}
#SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Date = new StringBuilder().append(year).append("-").append(month + 1).append("-").append(day).append(" ").toString();
btn_Date.setText(new StringBuilder().append(day).append("-").append(month + 1).append("-").append(year).append(" ").toString());
}
}
}
Here i need to show the delete icon only when the details are updated.....i need to hide that icon while creating an event...creating an event code is in "protected void on Create"....Where i need to add this hide method...i tried this inside this create method but it shows an error...Please help me
Try below code,
public class MainActivity extends Activity {
Menu menu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_act_app_home_new, menu);
return true;
}
void show(){
menu.findItem(R.id.menu_cancel_event).setVisible(true);
}
void hide(){
menu.findItem(R.id.menu_cancel_event).setVisible(false);
}
}
Let me know if this works for you...
And marks it as an answer so it would be useful to others
Simply create your menu:
boolean eventUpdated = true/false;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_occasion, menu);
return true;
}
and set visibility according your condition:
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.getItem(R.id.menu_cancel_event).setVisible(eventUpdated);
return true;
}
Call invalidateOptionsMenu() everytime condition changes to refresh menu.
A MenuItem is not a regular view that's part of your layout. Its something special, completely different. Your code returns null for item and that's causing the crash. What you need instead is to do:
MenuItem item = menu.findItem(R.id.addAction);
Then get a MenuItem pointing to such item, call setVisible() on it to adjust its visibility and then call
invalidateOptionsMenu()
on your activity so the ActionBar menu is adjusted accordingly.
im quite new to android programming. Im am trying to make use of google's latest datetimepicker function. I downloaded the source code from https://android.googlesource.com/platform/frameworks/opt/datetimepicker/+/e91a5dcdcc786074be1f6a9f2a4d79b99e34e18e and i imported it into my own project. So far i dont have any errors but i dont know how to make use of this function and test it into my project. I want to have a dialog box that will provide to the user the ability to select hours and minutes and a button click will save these data into my application.
Example: https://scontent-b-lhr.xx.fbcdn.net/hphotos-ash3/t1.0-9/10157365_10203642451081150_8056765662416057326_n.jpg
The Calendar app has the code to call the DatePickerDialog in the EditEventFragment (I think)
it looks about like this:
private class DateListener implements DatePickerDialog.OnDateSetListener {
View mView;
public DateListener(View view) {
mView = view;
}
#Override
public void onDateSet(DatePickerDialog view, int year, int month, int monthDay) {
// Cache the member variables locally to avoid inner class overhead.
Time startTime = mStartTime;
Time endTime = mEndTime;
// Cache the start and end millis so that we limit the number
// of calls to normalize() and toMillis(), which are fairly
// expensive.
long startMillis;
long endMillis;
if (mView == mFromDateButton) {
startTime.year = year;
startTime.month = month;
startTime.monthDay = monthDay;
startMillis = startTime.normalize(true);
setDate(mFromDateButton, startMillis);
} else {
endTime.year = year;
endTime.month = month;
endTime.monthDay = monthDay;
// Do not allow an event to have an end time before the start
// time.
if (endTime.before(mStartTime)) {
endTime.set(mStartTime);
}
endMillis = endTime.normalize(true);
setDate(mToDateButton, endMillis);
}
}
}
private DatePickerDialog mDatePickerDialog;
private class DateClickListener implements View.OnClickListener {
private Time mTime;
public DateClickListener(Time time) {
mTime = time;
}
#Override
public void onClick(View v) {
final DateListener listener = new DateListener(v);
if (mDatePickerDialog != null) {
mDatePickerDialog.dismiss();
}
mDatePickerDialog = DatePickerDialog.newInstance(listener,
mTime.year, mTime.month, mTime.monthDay);
mDatePickerDialog.setFirstDayOfWeek(PickerUtils.getFirstDayOfWeekAsCalendar( getActivity()));
mDateRangePickerDialog.setYearRange(mToday.year, mToday.year + 2);
mDateRangePickerDialog.show(getActivity().getFragmentManager(), "datePicker");
}
}
I have 2 datepickers and 2 timepickers on a screen and also a submit button. The user selects the start date, start time, end date, and end time. The program then takes these values and stores them into variables, however the variables only return the default values for these controls. Is there anyway to get the updated value from each of these controls?
My code looks like this for the edit screen:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.editscreen);
timepickerStart = (TimePicker)findViewById(R.id.timePicker1);
timepickerEnd = (TimePicker)findViewById(R.id.timePicker2);
datepickerStart = (DatePicker)findViewById(R.id.datePicker1);
datepickerEnd = (DatePicker)findViewById(R.id.datePicker2);
submitbutton = (Button)findViewById(R.id.submit);
locationText = (EditText)findViewById(R.id.locationText);
eventText = (EditText)findViewById(R.id.eventText);
}
public void DateStart(View v)
{
GlobalVariables.datepickerYearStart = datepickerStart.getYear();
GlobalVariables.datepickerMonthStart = datepickerStart.getMonth();
GlobalVariables.datepickerDayStart = datepickerStart.getDayOfMonth();
}
public void DateEnd(View v)
{
GlobalVariables.datepickerYearEnd = datepickerEnd.getYear();
GlobalVariables.datepickerMonthEnd = datepickerEnd.getMonth();
GlobalVariables.datepickerDayEnd = datepickerEnd.getDayOfMonth();
}
public void TimeStart(View v)
{
GlobalVariables.timepickerHourStart = timepickerStart.getCurrentHour();
GlobalVariables.timepickerMinuteStart = timepickerStart.getCurrentMinute();
}
public void TimeEnd(View v)
{
GlobalVariables.timepickerHourEnd = timepickerEnd.getCurrentHour();
GlobalVariables.timepickerMinuteEnd = timepickerEnd.getCurrentMinute();
}
public void submitClicked(View v)
{
startActivity(new Intent(this, AddToCalendar.class));
}
Rewrite
Looking at your current code, let's stick with the various get methods from DatePicker and TimePicker. However you never call DateStart() or any of the others, they look like you have them set up for an OnClickListener... Regardless, try this:
public void submitClick(View v) {
DateStart(null);
TimeStart(null);
DateEnd(null);
TimeEnd(null);
// Do what you please your GlobalVariables
}
Though I might leave out the multiple GlobalVariables and store one long value for each date/time:
public void submitClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(datepickerStart.getYear(), datepickerStart.getMonth(),
datepickerStart.getDayOfMonth(), timepickerStart.getCurrentHour(),
timepickerStart.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();
// And similar approach for the end time, then use them however you please
}
You need to set a listener to your DatePicker:
DatePicker picker = new DatePicker(this);
picker.init(<year>, <monthOfYear>, <dayOfMonth>, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//set the value of the variable here
}
});
I am making a date picker activity that looks like a scrolling 30 day month/calendar (think Outlook calendar). The date picker contains a ListView (for scrolling) of MonthView views each of which is a TableView of the individual days. Each individual day in the MonthView is a button. When the MonthView is instantiated I walk each of the days (buttons) and attach a click listener:
final Button b = getButtonAt(i);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
setSelectedDate(buttonDayClosure, b);
}
});
setSelectedDate does a variety of things, but it also turns the button's background to yellow to signify the date is selected.
On my emulator, everything works as you would expect. Activity comes up, you press a day, the day turns yellow. No problems.
However, on some of my peer's emulators and on physical devices when you touch a day nothing happens... until you scroll the ListView... and then all of a sudden the selected day turns yellow. So, for example, you touch "the 3rd" and then nothing happens. Wait a few seconds and then scroll the ListView (touching an area of the calendar that is NOT the 3rd) and as soon as ListView scrolls the 3rd magically turns yellow.
On my peer emulators that show this behavior, I can set a breakpoint on the fist line of onClick and I see that the BP is in fact not hit until the ListView is scrolled.
This behavior doesn't make any sense to me. I would expect the onClick behavior to be unrelated to the encapsulating View's scrolling efforts.
Any thoughts on why this might be the case and how I can rectify the situation so that onClicks always happen immediately when the button is touched?
Thanks.
Post Scriptus: ArrayAdapter and ListView code requested:
public class MonthArrayAdapter extends ArrayAdapter<Date> {
private MonthView[] _views;
private Vector<Procedure<Date>> _dateSelectionChangedListeners = new Vector<Procedure<Date>>();
public MonthArrayAdapter(Context context, int textViewResourceId, Date minSelectableDay, Date maxSelectableDay) {
super(context, textViewResourceId);
int zeroBasedMonth = minSelectableDay.getMonth();
int year = 1900 + minSelectableDay.getYear();
if(minSelectableDay.after(maxSelectableDay))
{
throw new IllegalArgumentException("Min day cannot be after max day.");
}
Date prevDay = minSelectableDay;
int numMonths = 1;
for(Date i = minSelectableDay; !sameDay(i, maxSelectableDay); i = i.addDays(1) )
{
if(i.getMonth() != prevDay.getMonth())
{
numMonths++;
}
prevDay = i;
}
_views = new MonthView[numMonths];
for(int i = 0; i<numMonths; i++)
{
Date monthDate = new Date(new GregorianCalendar(year, zeroBasedMonth, 1, 0, 0).getTimeInMillis());
Date startSunday = findStartSunday(monthDate);
this.add(monthDate);
_views[i] = new MonthView(this.getContext(), startSunday, minSelectableDay, maxSelectableDay);
zeroBasedMonth++;
if(zeroBasedMonth == 12)
{
year++;
zeroBasedMonth = 0;
}
}
for(final MonthView a : _views)
{
a.addSelectedDateChangedListener(new Procedure<MonthView>()
{
#Override
public void execute(MonthView input) {
for(final MonthView b: _views)
{
if(a != b)
{
b.clearCurrentSelection();
}
}
for(Procedure<Date> listener : _dateSelectionChangedListeners)
{
listener.execute(a.getSelectedDate());
}
}
});
}
}
void addSelectedDateChangedListener(Procedure<Date> listener)
{
_dateSelectionChangedListeners.add(listener);
}
private boolean sameDay(Date a, Date b)
{
return a.getYear() == b.getYear() && a.getMonth() == b.getMonth() &&
a.getDate() == b.getDate();
}
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
return _views[position];
}
private Date findStartSunday(Date d)
{
return d.subtractDays(d.getDay());
}
public void setSelectedDate(Date date)
{
for(MonthView mv : _views)
{
mv.setSelectedDate(date);
}
}
}
and
public class DatePicker extends ActivityBase {
public static final String CHOSEN_DATE_RESULT_KEY = "resultKey";
public static final String MIN_SELECTABLE_DAY = DatePicker.class.getName() + "MIN";
public static final String MAX_SELECTABLE_DAY = DatePicker.class.getName() + "MAX";
private static final String SELECTED_DATE = UUID.randomUUID().toString();
private long _selectedDate = -1;
private MonthArrayAdapter _monthArrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Date now = new Date();
Bundle inputs = this.getIntent().getExtras();
long min = inputs.getLong(MIN_SELECTABLE_DAY, 0);
Date minSelectableDate;
if(min == 0)
{
minSelectableDate = new Date(now);
}
else
{
minSelectableDate = new Date(min);
}
Log.i(DatePicker.class.getName(), "min date = " + minSelectableDate.toString());
long max = inputs.getLong(MAX_SELECTABLE_DAY, 0);
Date maxSelectableDate;
if(max == 0)
{
maxSelectableDate = new Date(now.addDays(35).getTime());
}
else
{
maxSelectableDate = new Date(max);
}
setContentView(R.layout.date_picker);
Button doneButton = (Button) findViewById(R.id.DatePickerDoneButton);
if(doneButton == null)
{
Log.e(this.getClass().getName(), "Could not find doneButton from view id.");
finish();
return;
}
doneButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
Intent result = new Intent();
result.putExtra(CHOSEN_DATE_RESULT_KEY, _selectedDate);
setResult(RESULT_OK, result);
finish();
}
});
Button cancelButton = (Button) findViewById(R.id.DatePickerCancelButton);
if(cancelButton == null)
{
Log.e(this.getClass().getName(), "Could not find cancelButton from view id.");
finish();
return;
}
cancelButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED, null);
finish();
}
});
ListView lv = (ListView)findViewById(R.id.DatePickerMonthListView);
lv.setDividerHeight(0);
_monthArrayAdapter =
new MonthArrayAdapter(this, android.R.layout.simple_list_item_1, minSelectableDate, maxSelectableDate);
_monthArrayAdapter.addSelectedDateChangedListener(new Procedure<Date>()
{
#Override
public void execute(Date input) {
_selectedDate = input.getTime();
}
});
lv.setAdapter(_monthArrayAdapter);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
if(savedInstanceState.containsKey(SELECTED_DATE))
{
_selectedDate = savedInstanceState.getLong(SELECTED_DATE);
_monthArrayAdapter.setSelectedDate(new Date(_selectedDate));
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.putLong(SELECTED_DATE, _selectedDate);
}
}
Having the same problem, looking for an answer. I totally didn't believe it when I didn't get my onClick method until I scrolled my list. I'll post the answer here if I find it.
Right now, my best guess is to try different events besides click (because the scroll space is eating the complex touch events that turn into a click event):
"downView" is a static variable to track the element being clicked.
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downView = v;
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
if (downView == v) {
handleClick(v);
return true;
}
downView = null;
}
return false;
}
});
The main reason is that ListView doesn't like an adapter having an array of views.
So the problem is triggered by
public View getView (int position, View convertView, ViewGroup parent)
{
return _views[position];
}
When looking at the ListView code (or rather it's parents AbsListView.obtainView method) you'll see code like
if (scrapView != null) {
...
child = mAdapter.getView(position, scrapView, this);
...
if (child != scrapView) {
mRecycler.addScrapView(scrapView);
It can happen that getView(position,...) is called with scrapView != _views[position] and hence scrapView will be recycled. On the other hand, it is quite likely that the same view is also added again to ListView, resulting in views having a weird state (see this issue)
Ultimately, this should be fixed in ListView IMO, but temporarily, I advise against using an adapter containing an array of views.
So I'll add a completely separate answer to this outside of manually composing your own click events from touch events.
I traded some emails with the Android Team (there's a few perks from being consumed by the googly) and they suggested that my attempt to implement ListAdapter by hand was inefficient and that if I don't correctly hook up the data observer methods of the adapter it can cause "funny problems with event handling."
So I did the following:
1) Replaced my implementation of ListAdapter with a subclass of BaseAdapter that overrode the necessary functions.
2) Stopped using list.invalidateViews() and started using adapter.notifyDataChanged()
and the bug seems to have gone away.
That's more work than manually composing a click event, but it's also more correct code in the long run.
Aswer is:
public View getView(int position, View convertView, ViewGroup parent) {
View v=makeMyView(position);
v.setFocusableInTouchMode(false);
return v;
}