Blackberry - get contacts list - blackberry

I wanted to get the list of all names and their corresponding email address from the contact list in blackberry JDE 4.7 can anyone help with the code for getting the above mentioned things..
Thanks in advance...

try this code:
public Scr() {
Vector v = getContacts();
Enumeration iterator = v.elements();
while (iterator.hasMoreElements()) {
String[] contact = (String[]) iterator.nextElement();
for (int i = 0; i < contact.length; i++)
add(new LabelField(contact[i]));
}
}
private Vector getContacts() {
Vector result = new Vector();
try {
BlackBerryContactList contactList = (BlackBerryContactList) PIM
.getInstance().openPIMList(PIM.CONTACT_LIST, PIM.READ_ONLY);
Enumeration enumx = contactList.items();
while (enumx.hasMoreElements()) {
BlackBerryContact c = (BlackBerryContact) enumx.nextElement();
String[] contact = new String[2];
if (contactList.isSupportedField(BlackBerryContact.NAME)) {
String[] name = c.getStringArray(BlackBerryContact.NAME, 0);
String firstName = name[Contact.NAME_GIVEN];
String lastName = name[Contact.NAME_FAMILY];
contact[0] = firstName + " " + lastName;
}
if (contactList.isSupportedField(BlackBerryContact.EMAIL)) {
StringBuffer emails = new StringBuffer();
int emailCount = c.countValues(BlackBerryContact.EMAIL);
for (int i = 0; i < emailCount; i++) {
String email = c.getString(BlackBerryContact.EMAIL, i);
if (email != null) {
emails.append(email.trim());
emails.append("; ");
}
}
contact[1] = emails.toString();
}
result.addElement(contact);
}
} catch (PIMException ex) {
ex.printStackTrace();
}
return result;
}

Related

linq to entity does not recognize the method

I need to call a method FormatCourseTitle() from linq query but receive error message "Linq to Entity does not recognize the method FormatCourseTitle..." How to solve this problem?
public ActionResult Index()
{
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = FormatCourseTitle(a.coursetitle) } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();
return View(searResults);
}
public class JoinModel
{
[Key]
public int Id { get; set; }
public Courselist Courses { get; set; }
public Contentsummary Summary { get; set; }
}
public string FormatCourseTitle(string courseTitle)
{
//find if last three characters are " or"
string[] words = courseTitle.Trim().ToLower().Split(' ');
int j = words.Count();
string tempStr = string.Empty;
if (words[j] == "or")
{
tempStr = courseTitle.Substring(0, courseTitle.Length - 3);
}
else
{
tempStr = courseTitle;
}
return tempStr;
}
You should use extension method as
public static class StringHelper
{
public static string FormatCourseTitle(this string courseTitle)
{
//find if last three characters are " or"
string[] words = courseTitle.Trim().ToLower().Split(' ');
int j = words.Count();
string tempStr = string.Empty;
if (words[j] == "or")
{
tempStr = courseTitle.Substring(0, courseTitle.Length - 3);
}
else
{
tempStr = courseTitle;
}
return tempStr;
}
}
Change query to
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = a.coursetitle.FormatCourseTitle() } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();
I find a way to add condition in linq query to solve this problem.
var searchResults = (from a in db.Courses
join b in db.Summary on
new { subject = a.subject, catalog = a.catalog, coursetitle = a.coursetitle.Trim().EndsWith(" or")?a.coursetitle.Substring(0,a.coursetitle.Length-3):a.coursetitle } equals
new { subject = b.Subject, catalog = b.Catalogno, coursetitle = b.CourseTitle } into ab
from b in ab.DefaultIfEmpty()
where a.Active == true
select new JoinModel
{
Courses = a,
Summary2020 = b
} ).ToList();

Get multiple nested partial views in MVC

I have one page which contains one multiple partial pages. In each partial view there will be again multiple partial pages. When I am getting this, it will add data table to ds contains three tables. How can I show it in hierarchical order?
In my ds three tables come from DB shows particular record. How can I display this?
THis is my DAL:
public static ConsignmentNote GetConsignmentNoteByID(int id)
{
ConsignmentNote consignmentnote = null;
SqlConnection sqlConnection = null;
sqlConnection = SqlConnectionHelper.GetConnectionConnectionString();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
cmd = new SqlCommand("GetConsignmentNoteByCNNoteId", sqlConnection);
cmd.Parameters.Add(new SqlParameter("#ConsignmentNoteID", id));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(ds);
//First table data
if (ds.Tables[0].Rows.Count > 0)
{
DataRow row = ds.Tables[0].Rows[0];
consignmentnote = new ConsignmentNote(row);
}
else
{
consignmentnote = new ConsignmentNote();
}
//Second table data
consignmentnote.LstAdditionalCN = new List<AdditionalCN>();
int rowIndexCN = 1;
if (ds.Tables[1].Rows.Count > 0)
{
int i = 0;
foreach (DataRow acnRow in ds.Tables[i].Rows)
{
AdditionalCN objACN = new AdditionalCN();
objACN.ConsignmentNoteRelID = acnRow["ConsignmentNoteRelID"] as Int32? ?? 0;
objACN.ConsignmentNoteID = acnRow["ConsignmentNoteID"] as Int32? ?? 0;
objACN.ConsignmentNoteNumber = acnRow["ConsignmentNoteNumber"] as string ?? null;
objACN.CNDate = acnRow["CNDate"] as DateTime? ?? DateTime.MinValue;
objACN.ConsignerID = (acnRow["ConsignerID"] as Int32? ?? 0).ToString();
objACN.ConsigneeID = (acnRow["ConsigneeID"] as Int32? ?? 0).ToString();
objACN.LocationFrom = acnRow["LocationFrom"] as string ?? null;
objACN.LocationTo = acnRow["LocationTo"] as string ?? null;
if (rowIndexCN == 1)
{
//insert to default CNI
consignmentnote.ConsignmentNoteRelID = objACN.ConsignmentNoteRelID;
consignmentnote.ConsignmentNoteNumber = objACN.ConsignmentNoteNumber;
}
else
{
//insert to additional CNI
consignmentnote.LstAdditionalCN.Add(objACN);
}
rowIndexCN++;
}
}
consignmentnote.LstAdditionalInvoice = new List<AdditionalInvoice>();
int rowIndexCNInvoice = 1;
if (ds.Tables[2].Rows.Count > 0)
{
foreach (DataRow acnRow in ds.Tables[2].Rows)
{
AdditionalInvoice objACN = new AdditionalInvoice();
objACN.ConsignmentNoteLineItemID = acnRow["ConsignmentNoteLineItemID"] as Int32? ?? 0;
objACN.ConsignmentNoteID = acnRow["ConsignmentNoteID"] as Int32? ?? 0;
objACN.ConsignmentNoteRelID = acnRow["ConsignmentNoteRelID"] as Int32? ?? 0;
objACN.ProjectPO = (acnRow["ProjectPO"] as Int32? ?? 0).ToString();
objACN.InvoiceNum = (acnRow["InvoiceNum"] as Int32? ?? 0).ToString();
objACN.InvoiceDate = acnRow["InvoiceDate"] as DateTime? ?? DateTime.MinValue;
objACN.Pkgs = acnRow["Pkgs"] as string ?? null;
objACN.Description = acnRow["Description"] as string ?? null;
objACN.ActualWeight = acnRow["ActualWeight"] as string ?? null;
objACN.ChargedWeight = acnRow["ChargedWeight"] as string ?? null;
objACN.InvoiceValue = acnRow["InvoiceValue"] as decimal? ?? 0;
if (rowIndexCNInvoice == 1)
{
//insert to default CNI
consignmentnote.ConsignmentNoteRelID = objACN.ConsignmentNoteRelID;
consignmentnote.ConsignmentNoteID = objACN.ConsignmentNoteID;
}
else
{
//insert to additional CNI
consignmentnote.LstAdditionalInvoice.Add(objACN);
}
rowIndexCNInvoice++;
}
}
}
catch (Exception x)
{
throw x;
}
finally
{
}
return consignmentnote;
}

Loop optimization (Multi level Menu) ASP.NET

I'm trying create a function to generate HTML file for multi-language menu. The code can work but only problem is its taking too long to compile. The flow is, this function will be called in the Global.asax file (process before start the program)
I suspect it caused by the looping process. So please advice me about the optimization. Thank you in advance. Here is the code.
public static void GenerateMenu(string strPath)
{
string[] tempCateHTML = new string[] { "_temp_menu_en.cshtml", "_temp_menu_bm.cshtml", "_temp_menu_ch.cshtml" }; //temporary file names
string[] cateHTML = new string[] { "_menu_en.cshtml", "_menu_bm.cshtml", "_menu_ch.cshtml" };
for (int i = 0; i < 3; i++)
{
using (EFContext ctx = new EFContext())
{
List<int> parentId = new List<int>();
List<Category> parentCategory = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = 0").ToList();
StringWriter sWriter = new StringWriter();
using (HtmlTextWriter wt = new HtmlTextWriter(sWriter))
{
foreach (Category cate in parentCategory)
{
string[] columnParent = new string[] { cate.Category_Name, cate.Category_NameBM, cate.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li); //<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A); //<a>
wt.Write(columnParent[i]);
wt.RenderEndTag();//</a>
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
List<Category> childCategoryL1 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", cate.CategoryID).ToList();
foreach (Category root in childCategoryL1)
{
string[] columnChild1 = new string[] { root.Category_Name, root.Category_NameBM, root.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild1[i]);
wt.RenderEndTag();//</a>
List<Category> childCategoryL2 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", root.CategoryID).ToList();
if (childCategoryL2.Count > 0)
{
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
foreach (Category child1 in childCategoryL2)
{
string[] columnChild2 = new string[] { child1.Category_Name, child1.Category_NameBM, child1.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild2[i]);
wt.RenderEndTag();//</a>
List<Category> childCategoryL3 = ctx.Database.SqlQuery<Category>
("select CategoryId, category_name, category_nameBM, category_nameCH from dbo.lCategories where thread_parent = {0}", child1.CategoryID).ToList();
if (childCategoryL3.Count > 0)
{
wt.RenderBeginTag(HtmlTextWriterTag.Ul);//<ul>
foreach (Category child2 in childCategoryL3)
{
string[] columnChild3 = new string[] { child2.Category_Name, child2.Category_NameBM, child2.Category_NameCH };
wt.RenderBeginTag(HtmlTextWriterTag.Li);//<li>
wt.AddAttribute(HtmlTextWriterAttribute.Href, "#");
wt.RenderBeginTag(HtmlTextWriterTag.A);//<a>
wt.Write(columnChild3[i]);
wt.RenderEndTag();//</a>
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
}
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
}
wt.RenderEndTag();//</li>
}
wt.RenderEndTag();//</ul>
wt.RenderEndTag();//</li>
}
}
string menuHTML = sWriter.ToString();
string filePath = Path.Combine(strPath, #"Views\Shared\CacheData\CateMenu\");
new FileInfo(filePath).Directory.Create(); //create new folder
var menuPath = String.Format("{0}{1}", filePath, tempCateHTML[i]); //create multiple HTML files for multiple language
using (FileStream fs = new FileStream(menuPath, FileMode.Append, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(menuHTML);
sw.Flush();
sw.Close();
fs.Close();
}
if (!File.Exists(filePath + cateHTML[i]))
{
using (File.Create(filePath + cateHTML[i]))
{
//create dummy file if the file doesnt exists
}
}
File.Replace(menuPath, filePath + cateHTML[i], filePath + cateHTML[i] + ".bac");
}
}
}
it's a long process. So really Thank you for the time
Actuall I've already found the solution for my problem. The solution was built tree menu based on this method. Thank you for the help.

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!

blackberry: adding checkboxes in a list

I have fetched contact list successfully. But I am not able to add check boxes with that list. I have made separate program from checkbox and its working. but not with the contact list. Can anybody tell me here where should I add checkboxes? Here is the code:
public final class ContactsScreen extends MainScreen implements ListFieldCallback {
private ListField listField;
private ContactList blackBerryContactList;
private Vector blackBerryContacts;
public ContactsScreen(){
CheckboxField checkBox1 = new CheckboxField();
setTitle(new LabelField( "Contacts", LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH ));
listField = new ListField();
listField.setCallback(this);
add(listField);
add(new RichTextField("Size" +(listField)));
reloadContactList();
}
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;
}
}
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 fieldVar, Graphics graphics, int index, int y, int width){
if ( listField == fieldVar && index < blackBerryContacts.size())
{
add(new RichTextField(blackBerryContacts.size()));
BlackBerryContact item = (BlackBerryContact)blackBerryContacts.elementAt(index);
String displayName = getDisplayName(item);
graphics.drawText(displayName, 0, y, 0, width);
}
}
public Object get(ListField fieldVar, int index)
{
if (listField == fieldVar) {
return blackBerryContacts.elementAt(index);
}
return null;
}
public int getPreferredWidth(ListField fieldVar ) {
return Display.getWidth();
}
public int indexOfList(ListField fieldVar, String prefix, int start)
{
return -1; // not implemented
}
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;
}
} return displayName;
}
}
ListField is not designed for this. Its list item is not a Manager, so you can't add any child fields to it. In other words this is not possible with ListField on BB. ListField is a way to represent on UI a long list without eating too much RAM (since in this case there is the only UI object - the ListField).
If your list is not too long (10 - 20 items) then consider using VerticalFieldManager instead of ListField. If list is long && you really need check boxes on it then consider using VerticalFieldManager + list pagination.

Resources