how to use multi choice spinner in mono for android? - xamarin.android

I want to use multi choice spinner in mono for android.
I want to bind the countries to the spinner
Now in the normal spinner there is label with radio button.
But I want the label with the Checkbox.
can any one please help me.
AlertDialog.Builder alt_bld = new AlertDialog.Builder(
CareCardActivity.this);
alt_bld.setTitle("Select Recepients");
alt_bld.setMultiChoiceItems(tempname, new boolean[tempname.length] , new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
// TODO Auto-generated method stub
}
});
alt_bld.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
ListView list = ((AlertDialog) dialog).getListView();
Log.v("LIST COUNT:: ", ""+list.getCount());
for (int i = 0; i < list.getCount(); i++) {
boolean checked = list.isItemChecked(i);
if (checked) {
sb.append(contactNumber[i]).append(";");
}
}
sb = sb.replace(
sb.length() - 1,
sb.length(), "");
txtPhoneNo.setText(sb.toString());
}
});
alt_bld.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = alt_bld.create();
alert.show();
I have tried this code in the eclipse it is working fine in it, but I want to do it for Mono develop in C#.

call this function on click of button
ShowDialog(DIALOG_MULTIPLE_CHOICE);
Add Following Code
protected override Dialog OnCreateDialog(int id)
{
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, OnDateSet, date.Year, date.Month - 1, date.Day);
case DIALOG_MULTIPLE_CHOICE: {
var builder = new AlertDialog.Builder (this);
// builder.SetIcon (Resource.Drawable.ic_popup_reminder);
builder.SetTitle ("Select Country");
builder.SetMultiChoiceItems (countryName, new bool[countryName.Length], MultiListClicked);
builder.SetPositiveButton ("ok", OkClicked);
builder.SetNegativeButton ("Cancel", CancelClicked);
return builder.Create ();
}
}
return null;
}
private void MultiListClicked (object sender, DialogMultiChoiceClickEventArgs e)
{
Console.WriteLine ("countryMultiListClicked");
if (e.IsChecked) {
mSelectedItems.Add (countryName [(int)e.Which]);
mSelectedItemsID.Add (countryID [(int)e.Which]);
}
else if (mSelectedItems.Contains(countryName [(int)e.Which]))
{
mSelectedItems.Remove(countryName [(int)e.Which]);
mSelectedItemsID.Remove(countryID [(int)e.Which]);
}
}
private void OkClicked (object sender, DialogClickEventArgs e)
{
Console.WriteLine ("countryOkClicked");
String listString = "";
for (int i =0; i<mSelectedItems.Count; i++) {
listString += mSelectedItems [i] + ",";
}
if (listString.Length > 0) {
listString = listString.Remove (listString.Length - 1);
}
et_country.Text = listString;
listStringId = "";
for (int i =0; i<mSelectedItemsID.Count; i++) {
listStringId += mSelectedItemsID [i] + ",";
}
if (listStringId.Length > 0) {
listStringId = listStringId.Remove (listStringId.Length - 1);
}
Console.WriteLine (listStringId);
}
private void CancelClicked (object sender, DialogClickEventArgs e)
{
Console.WriteLine("countryCancelClicked");
}
This works fine ........!

Related

MpAndroidChart for Xamarin.android

I'm using MpAndroidChart for my app. I can create piechart successfully but I have a question. I want an event listener to handle item clicked when user touched one of piechart item.How can I do it?
My Code is as below;
>
int[] ydata = { 5, 2, 3, 1 };
string[] xdata= { "one","two","three","four" };
PieChart pieChart;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
pieChart = FindViewById<PieChart>(Resource.Id.chart1);
pieChart.RotationEnabled = true;
pieChart.HoleRadius = 0;
pieChart.SetTransparentCircleAlpha(0);
pieChart.SetCenterTextSize(20);
pieChart.SetDrawEntryLabels(true);
pieChart.SetUsePercentValues(false);
pieChart.AnimateX(1000, Easing.EasingOption.EaseInOutCubic);
pieChart.Description.Text = "test";
addDataSet();
pieChart.SetTouchEnabled(true);
}
private void addDataSet()
{
List<PieEntry> yEntry = new List<PieEntry>();
List<string> xEntry = new List<string>();
for (int i = 0; i < ydata.Length; i++)
{
yEntry.Add(new PieEntry(ydata[i],xdata[i]));
}
for (int i = 0; i < xdata.Length; i++)
{
xEntry.Add(xdata[i]);
}
PieDataSet piedataset = new PieDataSet(yEntry, "test");
piedataset.SliceSpace = 0;
piedataset.ValueTextSize = 20;
int[] colors= { Color.Blue,Color.Red,Color.Green,Color.White};
piedataset.SetColors(colors);
Legend legend = pieChart.Legend;
legend.Form=Legend.LegendForm.Circle;
PieData pieData = new PieData(piedataset);
//pieData.SetValueFormatter(new int);
pieData.SetValueTextColor(Color.White);
pieChart.Data = (pieData);
pieChart.Invalidate();
}
You could use SetOnChartValueSelectedListener to set a ChartValueSelectedListener.
For example, in onCreate():
pieChart.SetOnChartValueSelectedListener(new MyListener(this));
And the listener:
public class MyListener : Java.Lang.Object, IOnChartValueSelectedListenerSupport
{
Context mContext;
public MyListener(Context context) {
this.mContext = context;
}
public void OnNothingSelected()
{
// throw new NotImplementedException();
}
public void OnValueSelected(Entry e, Highlight h)
{
PieEntry pe = (PieEntry)e;
Toast.MakeText(mContext, pe.Label+ " is clicked, value is "+ pe.Value, ToastLength.Short).Show();
}
}
The result is:

Make two ListBoxes scroll together

I wish to make two ListBoxes scroll together.
I have two ListBoxes of the same height with the same number of items, etc. I want to set it up such that if the user scrolls up/down in one list box the scrollbar for the other ListBox scrolls up/down as well.
But I can not seem to find a way to either detect the scroll bar position value or to detect when it has changed value.
Here is another way to sync the two ListBoxes:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SyncTwoListBox
{
public partial class Form1 : Form
{
private SyncListBoxes _SyncListBoxes = null;
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
//add options
for (int i = 0; i < 40; i++)
{
listBox1.Items.Add("Item " + i);
listBox2.Items.Add("Item " + i);
}
}
private void Form1_Load(object sender, EventArgs e)
{
this._SyncListBoxes = new SyncListBoxes(this.listBox1, this.listBox2);
}
}
public class SyncListBoxes
{
private ListBox _LB1 = null;
private ListBox _LB2 = null;
private ListBoxScroll _ListBoxScroll1 = null;
private ListBoxScroll _ListBoxScroll2 = null;
public SyncListBoxes(ListBox LB1, ListBox LB2)
{
if (LB1 != null && LB1.IsHandleCreated && LB2 != null && LB2.IsHandleCreated &&
LB1.Items.Count == LB2.Items.Count && LB1.Height == LB2.Height)
{
this._LB1 = LB1;
this._ListBoxScroll1 = new ListBoxScroll(LB1);
this._ListBoxScroll1.Scroll += _ListBoxScroll1_VerticalScroll;
this._LB2 = LB2;
this._ListBoxScroll2 = new ListBoxScroll(LB2);
this._ListBoxScroll2.Scroll += _ListBoxScroll2_VerticalScroll;
this._LB1.SelectedIndexChanged += _LB1_SelectedIndexChanged;
this._LB2.SelectedIndexChanged += _LB2_SelectedIndexChanged;
}
}
private void _LB1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this._LB2.TopIndex != this._LB1.TopIndex)
{
this._LB2.TopIndex = this._LB1.TopIndex;
}
if (this._LB2.SelectedIndex != this._LB1.SelectedIndex)
{
this._LB2.SelectedIndex = this._LB1.SelectedIndex;
}
}
private void _LB2_SelectedIndexChanged(object sender, EventArgs e)
{
if (this._LB1.TopIndex != this._LB2.TopIndex)
{
this._LB1.TopIndex = this._LB2.TopIndex;
}
if (this._LB1.SelectedIndex != this._LB2.SelectedIndex)
{
this._LB1.SelectedIndex = this._LB2.SelectedIndex;
}
}
private void _ListBoxScroll1_VerticalScroll(ListBox LB)
{
if (this._LB2.TopIndex != this._LB1.TopIndex)
{
this._LB2.TopIndex = this._LB1.TopIndex;
}
}
private void _ListBoxScroll2_VerticalScroll(ListBox LB)
{
if (this._LB1.TopIndex != this._LB2.TopIndex)
{
this._LB1.TopIndex = this._LB2.TopIndex;
}
}
private class ListBoxScroll : NativeWindow
{
private ListBox _LB = null;
private const int WM_VSCROLL = 0x115;
private const int WM_MOUSEWHEEL = 0x20a;
public event dlgListBoxScroll Scroll;
public delegate void dlgListBoxScroll(ListBox LB);
public ListBoxScroll(ListBox LB)
{
this._LB = LB;
this.AssignHandle(LB.Handle);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_VSCROLL:
case WM_MOUSEWHEEL:
if (this.Scroll != null)
{
this.Scroll(_LB);
}
break;
}
}
}
}
}
enter image description here

Updating image control in Windows Phone 8

I have a HTML5 web app I can view through my mobile devices.
I have an img control that would download an image using an ashx asp.net handler.
I updated via a timer.
I am trying to port this over to a Windows Phone 8.1 app instead.
The image seems to take ages to update (if at all). This is my code:
long tick = DateTime.Now.Ticks;
BitmapImage bmp =new BitmapImage(new Uri("http://my url/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick));
imgFrame1.Source = bmp;
Is this the correct way?
this is the full code:
private async void LogIn()
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/UserManagement/Login.aspx/Test",
new { username = "", password = "", hubuserid = hubuserid });
var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<UserLogIn>(str);
if (jsonObj.d.Success)
{
UpdateConnectionState("Logged In");
}
else
{
UpdateConnectionState("Not Logged In");
}
}
}
public class D
{
public string __type { get; set; }
public bool Success { get; set; }
}
public class UserLogIn
{
public D d { get; set; }
}
private string hubuserid = "";
public string Uptime { get; set; }
private byte ImageIsLoaded = 1;
private async void UpdateTime(int data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
txtInfo.Text = data.ToString();
if (ImageIsLoaded == 1)
{
ImageIsLoaded = 0;
long tick = DateTime.Now.Ticks;
BitmapImage bi = new BitmapImage(new Uri("http://www.informedmotion.co.uk/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick, UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened; }
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
//throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
imgFrame1.Source = (BitmapImage)sender;
}
private void imgFrame1_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
}
private void imgFrame1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
ImageIsLoaded = 1;
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
imgFrame1.ImageFailed += imgFrame1_ImageFailed;
imgFrame1.ImageOpened += imgFrame1_ImageOpened;
ConnectToHub();
}
private void ConnectToHub()
{
proxy.On<int>("broadcastMessage", data =>
{
UpdateTime(data);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
ConnectToHub();
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
LogIn();
}
});
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
ConnectToHub();
};
connection.Reconnected += () =>
{
//LogIn();
UpdateConnectionState("The connection was re-established");
};
}
Windows.UI.Core.CoreDispatcher dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
async void UpdateConnectionState(string state)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try{
txtInfo.Text = state;
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
static HubConnection connection = new HubConnection("http://www.informedmotion.co.uk/");
IHubProxy proxy = connection.CreateHubProxy("ChatHub");
If you're going to download the image, then you probably want to hooked the
Image.DownloadProgress event
Image.ImageOpened event
ImageOpened will fire once the download is complete, so at that moment you can set the .Source to it.
While it is downloading (if it's a huge image) you can either show the previous image or a place holder image (with progress bar maybe?)
BitmapImage bi = new BitmapImage(new Uri("http://www.google.com/myimage.bmp", UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened;
hiddenImage.Source = bi; // we need to set it to an element in the visual tree so the
// events will fire, we're going to use the hiddenImage
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
<!-- myImage is your image that you use to show stuff -->
<!-- hiddenImage is the image we use to fire the event -->
<Image x:Name="myImage"></Image>
<Image x:Name="hiddenImage" Visibility="Collapsed"></Image>

Blackberry: Multiline ListView

I have made list view with checkboxes. I have read similar articles n many people have suggested to do changes in drawlistRow but it is not happening. Can u suggest me where should i change to make it a multi line list.The code snippet is :
Updated: I updated my code and it is still not working
public class CheckboxListField extends MainScreen implements ListFieldCallback, FieldChangeListener {
int mCheckBoxesCount = 5;
private Vector _listData = new Vector();
private ListField listField;
private ContactList blackBerryContactList;
private BlackBerryContact blackBerryContact;
private Vector blackBerryContacts;
private MenuItem _toggleItem;
ButtonField button;
BasicEditField mEdit;
CheckboxField cb;
CheckboxField[] chk_service;
HorizontalFieldManager hm4;
CheckboxField[] m_arrFields;
boolean mProgrammatic = false;
public static StringBuffer sbi = new StringBuffer();
VerticalFieldManager checkBoxGroup = new VerticalFieldManager();
LabelField task;
//A class to hold the Strings in the CheckBox and it's checkbox state (checked or unchecked).
private class ChecklistData
{
private String _stringVal;
private boolean _checked;
ChecklistData()
{
_stringVal = "";
_checked = false;
}
ChecklistData(String stringVal, boolean checked)
{
_stringVal = stringVal;
_checked = checked;
}
//Get/set methods.
private String getStringVal()
{
return _stringVal;
}
private boolean isChecked()
{
return _checked;
}
private void setStringVal(String stringVal)
{
_stringVal = stringVal;
}
private void setChecked(boolean checked)
{
_checked = checked;
}
//Toggle the checked status.
private void toggleChecked()
{
_checked = !_checked;
}
}
CheckboxListField()
{
_toggleItem = new MenuItem("Change Option", 200, 10)
{
public void run()
{
//Get the index of the selected row.
int index = listField.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.
listField.invalidate(index);
if (index != -1 && !blackBerryContacts.isEmpty())
{
blackBerryContact =
(BlackBerryContact)blackBerryContacts.
elementAt(listField.getSelectedIndex());
ContactDetailsScreen contactDetailsScreen =
new ContactDetailsScreen(blackBerryContact);
UiApplication.getUiApplication().pushScreen(contactDetailsScreen);
}
}
};
listField = new ListField();
listField.setRowHeight(getFont().getHeight() * 2);
listField.setCallback(this);
reloadContactList();
//CheckboxField[] cb = new CheckboxField[blackBerryContacts.size()];
for(int count = 0; count < blackBerryContacts.size(); ++count)
{
BlackBerryContact item =
(BlackBerryContact)blackBerryContacts.elementAt(count);
String displayName = getDisplayName(item);
CheckboxField cb = new CheckboxField(displayName, false);
cb.setChangeListener(this);
add(cb);
listField.insert(count);
}
blackBerryContacts.addElement(cb);
add(checkBoxGroup);
}
protected void makeMenu(Menu menu, int instance)
{
menu.add(new MenuItem("Get", 2, 2) {
public void run() {
for (int i = 0; i < checkBoxGroup.getFieldCount(); i++) {
//for(int i=0; i<blackBerryContacts.size(); i++) {
CheckboxField checkboxField = (CheckboxField)checkBoxGroup
.getField(i);
if (checkboxField.getChecked()) {
sbi.append(checkboxField.getLabel()).append("\n");
}
}
Dialog.inform("Selected checkbox text::" + sbi);
}
});
super.makeMenu(menu, instance);
}
private boolean reloadContactList()
{
try {
blackBerryContactList =
(ContactList)PIM.getInstance().openPIMList
(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration allContacts = blackBerryContactList.items();
blackBerryContacts = enumToVector(allContacts);
listField.setSize(blackBerryContacts.size());
return true;
} catch (PIMException e)
{
return false;
}
}
//Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
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());
//graphics.drawText("ROW", 0, y, 0, w);
//String rowNumber = "one";
//Draw the text.
graphics.drawText(rowString.toString(), 0, y, 0, w);
/*graphics.drawText("ROW " + rowNumber, y, 0, w);
graphics.drawText("ROW NAME", y, 20, w);
graphics.drawText("row details", y + getFont().getHeight(), 20, w); */
}
public void drawRow(Graphics g, int x, int y, int width, int height) {
// Arrange the cell fields within this row manager.
layout(width, height);
// Place this row manager within its enclosing list.
setPosition(x, y);
// Apply a translating/clipping transformation to the graphics
// context so that this row paints in the right area.
g.pushRegion(getExtent());
// Paint this manager's controlled fields.
subpaint(g);
g.setColor(0x00CACACA);
g.drawLine(0, 0, getPreferredWidth(), 0);
// Restore the graphics context.
g.popContext();
}
public static String getDisplayName(Contact contact)
{
if (contact == null)
{
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " " + displayName;
}
return displayName;
}
}
return displayName;
}
//Returns the object at the specified index.
public Object get(ListField list, int index)
{
return _listData.elementAt(index);
/*if (listField == list)
{
//If index is out of bounds an exception will be thrown,
//but that's the behaviour we want in that case.
//return blackBerryContacts.elementAt(index);
_listData = (Vector) blackBerryContacts.elementAt(index);
return _listData.elementAt(index);
}
return null;*/
}
//Returns the first occurence of the given String, bbeginning the search at index,
//and testing for equality using the equals method.
public int indexOfList(ListField list, String p, int s)
{
//return listElements.getSelectedIndex();
//return _listData.indexOf(p, s);
return -1;
}
//Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list)
{
return Graphics.getScreenWidth();
//return Display.getWidth();
}
public void fieldChanged(Field field, int context) {
boolean mProgrammatic = false;
if (!mProgrammatic) {
mProgrammatic = true;
CheckboxField cbField = (CheckboxField) field;
int index = blackBerryContacts.indexOf(cbField);
if (cbField.getChecked())
{
for(int i=0;i<blackBerryContacts.size();i++)
{
Dialog.inform("Selected::" + cbField.getLabel());
sbi=new StringBuffer();
sbi.append(cbField.getLabel());
}
}
mProgrammatic = false;
}
}
This code may be improved with:
Using ListField instead of VerticalFieldManager + CheckboxField array (ListField is much more faster, 100+ controls may slow down UI)
Using simple array instead of vector in list data (it's faster)
Moving contacts load from UI thread (we should aware of blocking UI thread with heavy procedures like IO, networking or work with contact list)
Actually using ListField with two line rows has one issue: we have to set the same height for all rows in ListField. So there always will be two lines per row, no matter if we will use second line or not. But it's really better than UI performance issues.
See code:
public class CheckboxListField extends MainScreen implements
ListFieldCallback {
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private Vector mContacts;
private MenuItem mMenuItemToggle = new MenuItem(
"Change Option", 0, 0) {
public void run() {
toggleItem();
};
};
private MenuItem mMenuItemGet = new MenuItem("Get", 0,
0) {
public void run() {
StringBuffer sbi = new StringBuffer();
for (int i = 0; i < mListData.length; i++) {
ChecklistData checkboxField = mListData[i];
if (checkboxField.isChecked()) {
sbi.append(checkboxField.getStringVal())
.append("\n");
}
}
Dialog.inform("Selected checkbox text::\n"
+ sbi);
}
};
// A class to hold the Strings in the CheckBox and it's checkbox state
// (checked or unchecked).
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;
}
}
CheckboxListField() {
// toggle list field item on navigation click
mListField = new ListField() {
protected boolean navigationClick(int status,
int time) {
toggleItem();
return true;
};
};
// set two line row height
mListField.setRowHeight(getFont().getHeight() * 2);
mListField.setCallback(this);
add(mListField);
// load contacts in separate thread
loadContacts.run();
}
protected Runnable loadContacts = new Runnable() {
public void run() {
reloadContactList();
// fill list field control in UI event thread
UiApplication.getUiApplication().invokeLater(
fillList);
}
};
protected Runnable fillList = new Runnable() {
public void run() {
int size = mContacts.size();
mListData = new ChecklistData[size];
for (int i = 0; i < mContacts.size(); i++) {
BlackBerryContact item = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(item);
mListData[i] = new ChecklistData(
displayName, false);
}
mListField.setSize(size);
}
};
protected void toggleItem() {
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
// Invalidate the modified row of the ListField.
mListField.invalidate(index);
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(mListField
.getSelectedIndex());
// process selected contact here
}
}
protected void makeMenu(Menu menu, int instance) {
menu.add(mMenuItemToggle);
menu.add(mMenuItemGet);
super.makeMenu(menu, instance);
}
private boolean reloadContactList() {
try {
ContactList contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
Enumeration allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
return true;
} catch (PIMException e) {
return false;
}
}
// Convert the list of contacts from an Enumeration to a Vector
private Vector enumToVector(Enumeration contactEnum) {
Vector v = new Vector();
if (contactEnum == null)
return v;
while (contactEnum.hasMoreElements()) {
v.addElement(contactEnum.nextElement());
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
Object obj = this.get(list, index);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
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);
String secondLine = "Lorem ipsum dolor sit amet, "
+ "consectetur adipiscing elit.";
graphics.drawText(secondLine, 0, y
+ getFont().getHeight(),
DrawStyle.ELLIPSIS, w);
} else {
graphics.drawText("No rows available.", 0, y,
0, w);
}
}
public static String getDisplayName(Contact contact) {
if (contact == null) {
return null;
}
String displayName = null;
// First, see if there is a meaningful name set for the contact.
if (contact.countValues(Contact.NAME) > 0) {
final String[] name = contact.getStringArray(
Contact.NAME, 0);
final String firstName = name[Contact.NAME_GIVEN];
final String lastName = name[Contact.NAME_FAMILY];
if (firstName != null && lastName != null) {
displayName = firstName + " " + lastName;
} else if (firstName != null) {
displayName = firstName;
} else if (lastName != null) {
displayName = lastName;
}
if (displayName != null) {
final String namePrefix = name[Contact.NAME_PREFIX];
if (namePrefix != null) {
displayName = namePrefix + " "
+ displayName;
}
return displayName;
}
}
return displayName;
}
// Returns the object at the specified index.
public Object get(ListField list, int index) {
Object result = null;
if (mListData.length > index) {
result = mListData[index];
}
return result;
}
// Returns the first occurrence of the given String,
// beginning the search at index, and testing for
// equality using the equals method.
public int indexOfList(ListField list, String p, int s) {
return -1;
}
// Returns the screen width so the list uses the entire screen width.
public int getPreferredWidth(ListField list) {
return Graphics.getScreenWidth();
// return Display.getWidth();
}
}
Have a nice coding!

How To Change the field on focus in blackberry

Hello Sir I m making an app in which i got stuck in a problem please help me out ...
in one page i m getting the data from server and displaying that data on the page now i m use Focusable for highlighting them ...now my requirement is that when focus come on any data the it should change the field taking that name on which focus is present ..
following is the code which is showing the data on the page now it is working on field change where i need to click the label field ....
static LabelField[] CrDrLabels;
public LowerCreditors() throws Exception {
super(VerticalFieldManager.VERTICAL_SCROLL);
CrDrLabels = new LabelField[CrDrList.VendorNameArr.length];
for (int i = 0; i < CrDrLabels.length; i++) {
final int t = i;
VerticalFieldManager hfm = new VerticalFieldManager(USE_ALL_WIDTH) {
protected void sublayout(int Width, int Height) {
// TODO Auto-generated method stub
super.sublayout(Width, Height);
setPositionChild(getField(0), 15, 0);
setPositionChild(getField(1), Display.getWidth()
- getFont().getAdvance(CrDrList.VendorValArr[t])
- 10, 0);
}
};
CrDrLabels[i] = new LabelField(CrDrList.VendorNameArr[i],
LabelField.FOCUSABLE | Field.USE_ALL_WIDTH) {
protected boolean navigationClick(int status, int time) {
fieldChanged(this, 0);
return true;
};
};
LabelField Value = new LabelField(CrDrList.VendorValArr[i]);
CrDrLabels[i].setPadding(0, 170, 0, 0);
hfm.add(CrDrLabels[i]);
hfm.add(Value);
add(hfm);
}
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
for (int i = 0; i < CrDrList.VendorNameArr.length; i++) {
getFieldWithFocus();
if (field == CrDrLabels[i]) {
String LN = CrDrLabels[i].getText();
CrDrList.cname1 = LN;
LabelField cname1 = CrDrLabels[i];
CrDrList.selLad = CrDrLabels[i];
}
}
}
and the the other code is
menu.add(new MenuItem("View last 5 days transaction", 20, 10) {
public void run() {
if(property.Status.equals("online"))
{
Viewlast5daystransaction();
}
else
{
Dialog.alert("Please login Online to access the data..");
}
}
String LedgerName = CrDrList.cname1;
private void Viewlast5daystransaction() {
//Dialog.alert("Last 5 Days Transaction");
int resCode = 0;
HttpConnection connection = null;
try {
connection = getConn(property.LedgerDetailsURL);
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
e1.printStackTrace();
}
try {
resCode = connection.getResponseCode();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(resCode==0)
{
Dialog.alert("Internet Connectivity not available.. Please try again later..");
TallyA TA;
try {
TA = new TallyA();
UiApplication.getUiApplication().popScreen();
UiApplication.getUiApplication().pushScreen(TA);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sPostdata = "{\"tok\":\""
+ CompanyList.tok;
System.out.println("Postedddddd Dataaaaaaaaa" + sPostdata);
try {
String response = LedgerSearchReport();
System.out.println("response" + response);
ParseBankdetails.parsebankdetails(response);
System.out.println("response : " + response);
if(response != null)
{
LastFiveDaysCr LF;
try {
LF = new LastFiveDaysCr();
UiApplication.getUiApplication().pushScreen(LF);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Dialog.alert("No Data..");
Creditiors LF;
try {
LF = new Creditiors();
UiApplication.getUiApplication().pushScreen(LF);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
in this field only i want that instead of field change there should be focus change ...
please help me on that ...
I think you should implement the logic in "onFoucus()" method ,instead of using "onfieldChanged()" for CrDrLabels[i];

Resources