DatePickerFragment SelectedValue Xamarin.Android - xamarin.android

I want to pick a date in a DatePickerFragment in xamarin android like this:
DatePickerFragment frag = DatePickerFragment.NewInstance(delegate(DateTime time)
{
LoadMap(time.ToString("yyyy-MM-dd"));
});
frag.Show(FragmentManager, DatePickerFragment.TAG);
Meanwhile the DatePickerFragment Class is like this:
public class DatePickerFragment : Android.Support.V4.App.DialogFragment,
DatePickerDialog.IOnDateSetListener
{
// TAG can be any string of your choice.
public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();
// Initialize this value to prevent NullReferenceExceptions.
Action<DateTime> _dateSelectedHandler = delegate { };
public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
{
DatePickerFragment frag = new DatePickerFragment();
frag._dateSelectedHandler = onDateSelected;
return frag;
}
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
DateTime currently = DateTime.Now;
DatePickerDialog dialog = new DatePickerDialog(Activity,
this,
currently.Year,
currently.Month - 1,
currently.Day);
return dialog;
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
// Note: monthOfYear is a value between 0 and 11, not 1 and 12!
DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
Log.Debug(TAG, selectedDate.ToLongDateString());
_dateSelectedHandler(selectedDate);
}
}
The problem is that everytime i try to pick a date, the datepicker shows only today, it happens cause of DateTime currently = DateTime.Now;. How can I change this, so the Datepicker stores the last selected date?

I resolved by declaring static selectedDate = DateTime.Today; in the DatePickerFragment Class, full class below:
public class DatePickerFragment : Android.Support.V4.App.DialogFragment, DatePickerDialog.IOnDateSetListener
{
// TAG can be any string of your choice.
public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();
// Initialize this value to prevent NullReferenceExceptions.
Action<DateTime> _dateSelectedHandler = delegate { };
private static DateTime selectedDate = DateTime.Today;
public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
{
DatePickerFragment frag = new DatePickerFragment();
frag._dateSelectedHandler = onDateSelected;
return frag;
}
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
DateTime currently = selectedDate;
DatePickerDialog dialog = new DatePickerDialog(Activity,
this,
currently.Year,
currently.Month - 1,
currently.Day);
return dialog;
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
// Note: monthOfYear is a value between 0 and 11, not 1 and 12!
selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
Log.Debug(TAG, selectedDate.ToLongDateString());
_dateSelectedHandler(selectedDate);
}
}

Related

Set bindings for custom DependencyObjects

This is a continuation of a question here: Trying to setup a custom DependencyObject. Clearly missing something. It's not practical to edit the original question; changes are too great. So I'm starting a fresh question.
I'm trying to setup bindings between custom DependencyObjects in my UWP app. The relevant code is below. I am seeing calls to ActualWidthPropertyChanged, but they are not triggering any call to WidthPropertyChanged. What am I missing?
class WindowsElement: DependencyObject
{
public WindowsElement()
{
}
public double Width
{
get
{
return (double)GetValue(WidthProperty);
}
set
{
SetValue(WidthProperty, value);
}
}
private static void WidthPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WindowsElement element = (WindowsElement)o;
double width = (double)e.NewValue;
CommonDebug.LogLine("WPC", element, o, width);
element.Width = width;
}
private static void ActualWidthPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WindowsElement element = (WindowsElement)o;
double width = (double)e.NewValue;
CommonDebug.LogLine("AWPC", o, e, width, element.Width);
element.ActualWidth = width;
}
public static readonly DependencyProperty WidthProperty = DependencyProperty.Register(
"Width",
typeof(double),
typeof(WindowsElement),
new PropertyMetadata((double)0, WidthPropertyChanged));
public double ActualWidth {
get
{
return (double)GetValue(ActualWidthProperty);
}
set
{
SetValue(ActualWidthProperty, value);
}
}
public static readonly DependencyProperty ActualWidthProperty =
DependencyProperty.Register(
"ActualWidth",
typeof(double),
typeof(WindowsElement),
new PropertyMetadata((double)0, ActualWidthPropertyChanged));
public static void MessWithBindings()
{
WindowsElement we1 = new WindowsElement();
WindowsElement we2 = new WindowsElement();
var b = new Binding
{
Source = we2,
Path = new PropertyPath("ActualWidth")
};
BindingOperations.SetBinding(we1, WindowsElement.WidthProperty, b);
we2.ActualWidth = 13;
CommonDebug.LogLine(we1, we1.Width, we1.ActualWidth, we2, we2.Width, we2.ActualWidth);
}
}
I am seeing calls to ActualWidthPropertyChanged, but they are not triggering any call to WidthPropertyChanged. What am I missing?
To solve this question, you would need to implement the INotifyPropertyChanged interface on the source object so that the source can report changes.
Please see the following code:
class WindowsElement : DependencyObject, INotifyPropertyChanged
{
public WindowsElement()
{
}
public double Width
{
get
{
return (double)GetValue(WidthProperty);
}
set
{
SetValue(WidthProperty, value);
}
}
private static void WidthPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WindowsElement element = (WindowsElement)o;
double width = (double)e.NewValue;
CommonDebug.LogLine("WPC", element, o, width);
//element.Width = width;
element.RaisedPropertyChanged("Width");
}
private static void ActualWidthPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WindowsElement element = (WindowsElement)o;
double width = (double)e.NewValue;
CommonDebug.LogLine("AWPC", o, e, width, element.Width);
//element.ActualWidth = width;
element.RaisedPropertyChanged("ActualWidth");
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisedPropertyChanged(string PropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
public static readonly DependencyProperty WidthProperty = DependencyProperty.Register(
"Width",
typeof(double),
typeof(WindowsElement),
new PropertyMetadata((double)0, WidthPropertyChanged));
public double ActualWidth
{
get
{
return (double)GetValue(ActualWidthProperty);
}
set
{
SetValue(ActualWidthProperty, value);
}
}
public static readonly DependencyProperty ActualWidthProperty = DependencyProperty.Register(
"ActualWidth",
typeof(double),
typeof(WindowsElement),
new PropertyMetadata((double)0, ActualWidthPropertyChanged));
public static void MessWithBindings()
{
WindowsElement we1 = new WindowsElement();
WindowsElement we2 = new WindowsElement();
var b = new Binding
{
Source = we2,
Path = new PropertyPath("ActualWidth")
};
BindingOperations.SetBinding(we1, WindowsElement.WidthProperty, b);
we2.ActualWidth = 13;
CommonDebug.LogLine(we1, we1.Width, we1.ActualWidth, we2, we2.Width, we2.ActualWidth);
}
}
Not sure why in UWP a one-way Binding from one dependency property to another doesn't automatically update the target property (as it does in WPF).
However, you could simply revert the direction of the Binding and make it two-way:
var b = new Binding
{
Source = we1,
Path = new PropertyPath("Width"),
Mode = BindingMode.TwoWay
};
BindingOperations.SetBinding(we2, WindowsElement.ActualWidthProperty, b);
we2.ActualWidth = 13;

How to open new class file on click of treeview parent and child item in blackberry?

public class Expandablelistview extends MainScreen {
public Expandablelistview() {
// A separator field between each type of control\
// setTitle("Tree Field Demo");
String parentfield1 = new String("Demo1");
String parentfield2 = new String("Demo2");
String childfield1 = new String("Demo3");
String childfield2 = new String("Demo4");
String parentfield3 = new String("Demo5");
String parentfield4 = new String("Demo6");
String childfield3 = new String("Demo7");
String childfield4 = new String("Demo8");
String childfield5 = new String("Demo9");
String childfield6 = new String("Demo10");
String parentfield5 = new String("Demo11");
String childfield7 = new String("Demo12");
String childfield8 = new String("Demo13");
TreeCallback myCallback = new TreeCallback();
final TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE);
myTree.setDefaultExpanded(false);
int node12 = myTree.addChildNode(0, parentfield5);
int node13 = myTree.addChildNode(node12, childfield7);
int node14 = myTree.addChildNode(node12, childfield8);
// int node7 = myTree.addChildNode(0, parentfield5);
int node6 = myTree.addChildNode(0, parentfield4);
int node11 = myTree.addChildNode(node6, childfield6);
int node10 = myTree.addChildNode(node6, childfield5);
int node8 = myTree.addChildNode(node6, childfield3);
int node9 = myTree.addChildNode(node6, childfield4);
int node5 = myTree.addChildNode(0, parentfield3);
int node2 = myTree.addChildNode(0, parentfield2);
int node3 = myTree.addChildNode(node2, childfield1);
int node4 = myTree.addChildNode(node2, childfield2);
int node1 = myTree.addChildNode(0, parentfield1);
add(myTree);
// myTree.setChangeListener(new myTreeChangeListener());
// HERE I TRIED FOR ITEM CLICK
FieldChangeListener fdbtncalculate = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
int a = myTree.getNodeCount();
System.out.print("mytree" + a);
if (a == 0) {
Dialog.alert("data");
} else if (a == 1) {
Dialog.alert("data");
}
}
};
myTree.setChangeListener(fdbtncalculate);
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
String text = (String) _tree.getCookie(node);
g.drawText(text, indent, y);
}
}
}
i want to know what i am doing wrong? i want to open my class file on click of parent and child item of treeview for that i used field listener
Instead of using a FieldChangeListener, try this code, which overrides navigationClick():
TreeCallback myCallback = new TreeCallback();
TreeField myTree = new TreeField(myCallback, Field.FOCUSABLE) {
protected boolean navigationClick(int status, int time) {
// We'll only override unvarnished navigation click behavior
if ((status & KeypadListener.STATUS_ALT) == 0 &&
(status & KeypadListener.STATUS_SHIFT) == 0)
{
final int node = getCurrentNode();
if (getFirstChild(node) == -1) {
// Click is on a leaf node.
Dialog.alert("clicked leaf node " + getCookie(node));
return true;
} else {
// Node is a parent node
setExpanded(node, !getExpanded(node));
Dialog.alert("clicked parent node " + getCookie(node));
return true;
}
}
return super.navigationClick(status, time);
}
};
I'm not sure what you mean by "open new class file", but whatever you want to do after the user clicks a part of the tree, you would do it where I have the Dialog.alert() code above.

How to get multiple selected list items from list field checkbox and add into an arraylist in blackberry

Please anyone help me get selected listitems from a listfieldcheckbox, and add them into an arraylist. If possible, give any useful links also. Here's my code so far (I am new to blackberry application development). Please help.
package mypackage;
import java.util.Vector;
import net.rim.device.api.system.Characters;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.IntVector;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen implements ListFieldCallback
{
private Vector _listData = new Vector();
private Vector _checkedData = new Vector();
private ListField listField;
private static final String[] _elements = {"First element", "Second element","Third element"
};
//private static final String[] _elements1 = {"hai","welcome","where r u"
//};
private MenuItem _getDataMenu,selectall,Delete;
Vector result = new Vector();
protected void makeMenu(Menu menu, int instance)
{
menu.add(_getDataMenu);
menu.add(selectall);
menu.add(Delete);
//Create the default menu.
super.makeMenu(menu, instance);
}
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
public Vector getCheckedItems() {
return _checkedData;
}
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
VerticalFieldManager main = new VerticalFieldManager(VerticalFieldManager.USE_ALL_HEIGHT|
VerticalFieldManager.USE_ALL_WIDTH|VerticalFieldManager.VERTICAL_SCROLL);
this.add(main);
HorizontalFieldManager hfm = new HorizontalFieldManager();
main.add(hfm);
listField = new ListField(){
//Allow the space bar to toggle the status of the selected row.
protected boolean keyChar(char key, int status, int time)
{
boolean retVal = false;
//If the spacebar was pressed...
if (key == Characters.SPACE)
{
//Get the index of the selected row.
int index = getSelectedIndex();
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index);
//Invalidate the modified row of the ListField.
invalidate(index);
//Consume this keyChar (key pressed).
retVal = true;
}
return retVal;
}
};
listField.setCallback(this);
reloadList();
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.addElement(new ChecklistData(_elements[count], false));
//_listData.addElement(new ChecklistData(_elements1[count], false));
listField.insert(count);
}
main.add(listField);
_getDataMenu =new MenuItem("Get Data", 200, 10) {
public void run(){
int index = listField.getSelectedIndex();
ChecklistData data = (ChecklistData)_listData.elementAt(index);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
//Dialog.alert(message);
// get all the checked data indices
IntVector selectedIndex = new IntVector(0, 1);
//ChecklistData data;
for (int i=0;i<_listData.size();i++) {
data = (ChecklistData)_listData.elementAt(i);
if(data.isChecked()) {
selectedIndex.addElement(i);
String selectedvalues = data.getStringVal();
System.out.println("Selected items are:"+selectedvalues);
}
}
data = null;
// now selectedIndex will contain all the checked data indices.
//String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
}
};
selectall = new MenuItem("Selectall", 200, 10){
public void run(){
int elementLength = _elements.length;
for(int count = 0; count < elementLength; ++count)
{
_listData.setElementAt(new ChecklistData(_elements[count], true), count);
}
}
};
Delete = new MenuItem("Delete", 200, 10){
public void run(){
int index = listField.getSelectedIndex();
_listData.removeElementAt(index);
// update the view
listField.delete(index);
listField.invalidate(index);
}
};
}
private void reloadList() {
// TODO Auto-generated method stub
_listData.setSize(_listData.size());
}
public void drawListRow(ListField list, Graphics graphics, int index, int y, int w)
{
ChecklistData currentRow = (ChecklistData)this.get(list, index);
StringBuffer rowString = new StringBuffer();
if (currentRow.isChecked())
{
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else
{
rowString.append(Characters.BALLOT_BOX);
}
//Append a couple spaces and the row's text.
rowString.append(Characters.SPACE);
rowString.append(Characters.SPACE);
rowString.append(currentRow.getStringVal());
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*if (currentRow.isChecked()) {
if( -1 ==_checkedData.indexOf(currentRow))
_checkedData.addElement(currentRow);
rowString.append(Characters.BALLOT_BOX_WITH_CHECK);
}
else {
if( -1 !=_checkedData.indexOf(currentRow))
_checkedData.removeElement(currentRow);
rowString.append(Characters.BALLOT_BOX);
} */
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
}
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
return _listData.indexOf(p, s);
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
protected boolean navigationClick(int status, int time) {
int index1 = listField.getSelectedIndex();
/*System.out.println("Selected item index:"+index1);
//int[] list =listField.getSelection();
//String s = Integer.toString(list);
System.out.println(" items are:"+_elements[index1]);
//ChecklistData data = (ChecklistData)_listData.elementAt(index1);*/
//Get the ChecklistData for this row.
ChecklistData data = (ChecklistData)_listData.elementAt(index1);
String message = "Selected data: " + data.getStringVal() + ", and status: " + data.isChecked();
System.out.println("message is:"+message);
//Toggle its status.
data.toggleChecked();
//Update the Vector with the new ChecklistData.
_listData.setElementAt(data, index1);
//Invalidate the modified row of the ListField.
listField.invalidate(index1);
return true;
}
}

how to convert date from yyyy-MM-dd to dd-MMM-yyyy without using Date function

I have "2011-12-05" and I want to convert this to "Monday 05-Dec-2011".
My date conversion code depends on the device timezone. If my timezone is India, then I get date Monday 05-Dec-2011 and if my timezone is Kingston, Jamaica, I get Sunday 04-Dec-2011.
For this reason my application does not display the correct date for different timezones.
Is there any solution to convert date without Blackberry Date class or using current Date and Time Zone?
I want to only convert this date to String
I am converting this date using below function
public static String reformatMonthDate(String source)
{
SimpleDateFormat write = new SimpleDateFormat("dd MMM yyyy"); //YYYY-MMM-dd
Date date = new Date(HttpDateParser.parse(source));
return write.format(date);
}
You can specify a specific locale, instead of relying on the system's default.
Locale locale = Locale.get(Locale.LOCALE_fr);
// Parse with HttpDateParser
Date date = new Date(HttpDateParser.parse("2002-01-29"));
// Format with a custom format and locale
DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
StringBuffer buf = new StringBuffer(30);
String s = formatter.format(date, buf, null).toString(); // mar., 29 janv. 2002
DateTimePicker gives the current date according to the location or device configuration settings.
Try this code:
You should get your requirement.
public class LoadingScreen extends MainScreen implements FieldChangeListener
{
private String select_Date[]={"Select Date"};
private String month_ar[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
private ObjectChoiceField choiceField;
private ButtonField show;
public LoadingScreen()
{
createGUI();
}
private void createGUI()
{
choiceField=new ObjectChoiceField("Select Date: ", select_Date, 0)
{
protected boolean navigationClick(int status, int time)
{
DateTimePicker datePicker = DateTimePicker.createInstance( Calendar.getInstance(), "dd/MM/yyyy",null);
datePicker.doModal();
Calendar cal1=datePicker.getDateTime();
String day="";
String mon="";
if(String.valueOf(cal1.get(Calendar.DAY_OF_MONTH)).length()==1)
{
day="0"+String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
else
{
day=String.valueOf(cal1.get(Calendar.DAY_OF_MONTH));
}
mon=String.valueOf(cal1.get(Calendar.MONTH));
String month=""+month_ar[cal1.get(Calendar.MONTH)];
select_Date[0]=day+"-"+month+"-"+cal1.get(Calendar.YEAR);
choiceField.setChoices(select_Date);
return true;
}
};
add(choiceField);
show=new ButtonField("Show",FIELD_HCENTER);
show.setChangeListener(this);
add(show);
}
public void fieldChanged(Field field, int context)
{
if(field==show)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(select_Date[choiceField.getSelectedIndex()]);
}
});
}
}
public boolean onMenu(int instance)
{
return true;
}
protected boolean onSavePrompt()
{
return true;
}
}

BlackBerry 6: ListFieldCallback.indexOfList() - how to filter while typing?

I'm trying to display a TextField and a ListField below it:
And I would like to filter (aka "live search") the number of displayed rows, while the user is typing a word into the TextField.
I've tried calling ListField.setSearchable(true) but it doesn't change anything, even if I type words while having the ListField focussed.
And by the way I wonder which TextField to take. I've used AutoCompleteField because it looks exactly as I want the field to be (white field with rounded corners), but it is probably not the best choice (because I don't need AutoCompleteField's drop down list while typing).
Here is my current code -
MyScreen.java:
private ListField presetListField = new ListField();
private MyList presetList = new MyList(presetListField);
private MyScreen() {
int size;
getMainManager().setBackground(_bgOff);
setTitle("Favorites");
BasicFilteredList filterList = new BasicFilteredList();
String[] days = {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"};
int uniqueID = 0;
filterList.addDataSet(uniqueID, days, "days",
BasicFilteredList.COMPARISON_IGNORE_CASE);
// XXX probably a bad choice here?
AutoCompleteField autoCompleteField =
new AutoCompleteField(filterList);
add(autoCompleteField);
presetListField.setEmptyString("* No Favorites *", DrawStyle.HCENTER);
add(presetListField);
presetList.insert("Monday");
presetList.insert("Tuesday");
presetList.insert("Wednesday");
for (int i = 0; i < 16; i++) {
presetList.insert("Favorite #" + (1 + i));
}
}
MyList.java:
public class MyList implements ListFieldCallback {
private Vector _preset = new Vector();
private ListField _list;
public MyList(ListField list) {
_list = list;
_list.setCallback(this);
_list.setRowHeight(-2);
// XXX does not seem to have any effect
_list.setSearchable(true);
}
public void insert(String str) {
insert(str, _preset.size());
}
public void insert(String str, int index) {
_preset.insertElementAt(str, index);
_list.insert(index);
}
public void delete(int index) {
_preset.removeElementAt(index);
_list.delete(index);
}
public void drawListRow(ListField listField,
Graphics g, int index, int y, int width) {
Font f = g.getFont();
Font b = f.derive(Font.BOLD, f.getHeight() * 2);
Font i = f.derive(Font.ITALIC, f.getHeight());
g.setColor(Color.WHITE);
g.drawText((String)_preset.elementAt(index), Display.getWidth()/3, y);
g.setFont(i);
g.setColor(Color.GRAY);
g.drawText("Click to get frequency",
Display.getWidth()/3, y + g.getFont().getHeight());
g.setFont(b);
g.setColor(Color.YELLOW);
g.drawText(String.valueOf(100f + index/10f), 0, y);
}
public Object get(ListField list, int index) {
return _preset.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int start) {
return _preset.indexOf(prefix, start);
}
public int getPreferredWidth(ListField list) {
return Display.getWidth();
}
}
Thank you!
Alex
Have you checked the net.rim.device.api.ui.component.KeywordFilterField ?

Resources