How to open new class file on click of treeview parent and child item in blackberry? - 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.

Related

Java - Writing method for public int indexOf(T element) in a double linked list

Below I have the int indexOf(T element) method for a double linked list. I need help with the code to make sure it functions properly. The method should return the first occurence of the element in the list or -1 if element is not in the list. Below is the node class it uses. The IUDoubleLinkedList.java class implements IndexedUnsortedList.java which is where the indexOf method comes from. I tried using my indexOf method from my single linked list class but it's not the same so I hope to understand why it would be different and what code is used that is different between the the single and double linked list.
public class IUDoubleLinkedList<T> implements IndexedUnsortedList<T> {
private Node<T> head, tail;
private int size;
private int modCount;
public IUDoubleLinkedList() {
head = tail = null;
size = 0;
modCount = 0;
This is the indexOf(T element) method
#Override
public int indexOf(T element) {
// TODO Auto-generated method stub
return 0;
}
Below is the Node.java class it uses
public class Node<T> {
private Node<T> nextNode;
private T element;
private Node<T> prevNode;
/**
* Creates an empty node.
*/
public Node() {
nextNode = null;
element = null;
}
/**
* Creates a node storing the specified element.
*
* #param elem
* the element to be stored within the new node
*/
public Node(T element) {
nextNode = null;
this.element = element;
setPrevNode(null);
}
/**
* Returns the node that follows this one.
*
* #return the node that follows the current one
*/
public Node<T> getNextNode() {
return nextNode;
}
/**
* Sets the node that follows this one.
*
* #param node
* the node to be set to follow the current one
*/
public void setNextNode(Node<T> nextNode) {
this.nextNode = nextNode;
}
/**
* Returns the element stored in this node.
*
* #return the element stored in this node
*/
public T getElement() {
return element;
}
/**
* Sets the element stored in this node.
*
* #param elem
* the element to be stored in this node
*/
public void setElement(T element) {
this.element = element;
}
#Override
public String toString() {
return "Element: " + element.toString() + " Has next: " + (nextNode != null);
}
public Node<T> getPrevNode() {
return prevNode;
}
public void setPrevNode(Node<T> prevNode) {
this.prevNode = prevNode;
}
}
Check the following code, hope I helped you!
Insert item at head as well as tail end
public void insertItem(T elem) {
/* if head and tail both are null*/
if(head == null || tail == null) {
head = new Node<T>(elem);
tail = new Node<T>(elem);
}else {
Node<T> tempItem = new Node<T>();
tempItem.setElement(elem);
/* insert at head end /*
tempItem.setNextNode(head);
head.setPrevNode(tempItem);
head = tempItem;
Node<T> tempItem1 = new Node<T>();
tempItem1.setElement(elem);
/* append at tail end */
tail.setNextNode(tempItem1);
tempItem1.setPrevNode(tail);
tail = tempItem1;
}
size += 1;
}
Print item from head end
public void printItemsFromHead() {
while(head != null) {
System.out.print(head.getElement()+" --> ");
head = head.getNextNode();
}
}
Print item from tail end
public void printItemsFromTail() {
Node<T> temp = null;
while(tail != null) {
temp = tail;
System.out.print(tail.getElement()+" --> ");
tail = tail.getPrevNode();
}
/*System.out.println();
while(temp != null) {
System.out.print(temp.getElement()+" --> ");
temp = temp.getNextNode();
}*/
}
Implemention of indexOf function
#Override
public int indexOf(T element) {
int result = -1;
int headIndex = 0;
int tailIndex = size;
while(head != null && tail != null) {
if(head.getElement().equals(element)) {
result = headIndex;
break;
}
/*
if(tail.getElement().equals(element)) {
result = tailIndex;
break;
} */
head = head.getNextNode();
tail = tail.getPrevNode();
headIndex += 1;
tailIndex -= 1;
}
return result;
}
Driver class
public class Driver {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> void main(String[] args) {
UDoubleLinkedList uDoubleLinkedList = new UDoubleLinkedList();
uDoubleLinkedList.insertItem(1);
uDoubleLinkedList.insertItem(2);
uDoubleLinkedList.insertItem(3);
uDoubleLinkedList.insertItem(4);
uDoubleLinkedList.insertItem(5);
System.out.println(uDoubleLinkedList.indexOf(1));
}
}

Double Linked List

//I have a single linked list that looks like this
node head = new Node ();
head.info = 3;
head.next = new Node ();
head.next.info = 6 ();
head.next.next = new Node ();
head.next.next.info = 9;
head.next.next.next = null;
//How would I write a double linked list?
class Double Node
{
info;
doubleNode prev;
doubleNode next;
}
Here is the part for creating a double linked list and adding nodes to it.
You can update it by adding remove and insert functions as you want.
class Node{
Node prev;
Node next;
int value;
public Node(int value) {
this.value = value;
}
}
class DoubleLinkedList{
Node head;
Node tail;
public DoubleLinkedList(Node head) {
this.head = head;
this.tail = head;
head.next = null;
head.prev = null;
}
public void addNode(Node node){
tail.next = node;
node.prev = tail;
tail = node;
}
}
public class Main {
public static void main(String args[]){
Node head= new Node(3);
DoubleLinkedList list = new DoubleLinkedList(head);
list.addNode(new Node(5));
list.addNode(new Node(6));
list.addNode(new Node(7));
list.addNode(new Node(8));
}
}
This would be the idea:
node head = new Node();
head.info = 3;
node prev, actual, next;
prev = head;
actual.prev = prev;
actual.info = 6;
actual = actual.next = new Node();
actual.prev = prev;
actual = actual.next = new Node();
actual.info = 9;
...
Assuming that you will have the behavior in your example, you can automate it with a function, in c# would be something like:
function GetDoubleLinkedList(Node head, int from, int end, int jumps)
{
head.info = from;
node prev = head, actual, next;
for(var i = from+jumps; i <= end; i+=jumps)
{
actual.prev = prev;
actual.info = i;
actual = actual.next = new Node();
}
actual.info = end;
return head;
}
//...
//then you can do
node head = new Node();
head = GetDoubleLinkedList(head, 3, 9, 3);
//...
Double linked list are like single linked list with the exception that they have two pointer in the declaration of structure
a previous pointer and a next pointer
For sample implementation see this link
Here is an implementation of a DoubleLinkedList in Java (along with some examples that might help you understand how it's working):
public class Node {
public int value;
public Node prev;
public Node next;
public Node(int value) {
this.value = value;
this.prev = null;
}
public Node(int value, Node prev) {
this.value = value;
this.prev = prev;
}
public Node add(int value) {
if(this.next == null) {
this.next = new Node(value, this);
} else {
this.next.add(value);
}
return this;
}
public Node last() {
if(this.next == null) {
return this;
} else {
return this.next.last();
}
}
public String toString() {
String out = value+" ";
if(this.next != null) {
out += this.next.toString();
}
return out;
}
public static void main(String...arg) {
Node list = (new Node(3)).add(6).add(5).add(9);
System.out.println(list.toString());
//Output:3 6 5 9
System.out.println(list.last().toString());
//Output:9
System.out.println(list.last().prev.prev.toString());
//Output:6 5 9
}
}
You can use following DoubleLinkedList class.
public class DoubleLinkedList<T>
{
Node<T> start;
Node<T> end;
public void AddFirst(T dataToAdd)
{
Node<T> tmp = new Node<T>(dataToAdd);
if (start == null)
{
start = tmp;
end = start;
return;
}
start.previous = tmp;
tmp.next = start;
start = tmp;
if (start.next == null)
{
end = start;
}
}
public void AddLast(T dataToAdd)
{
if (start == null)
{
AddFirst(dataToAdd);
return;
}
Node<T> tmp = new Node<T>(dataToAdd);
end.next = tmp;
tmp.previous = end;
end = tmp;
}
public T RemoveFirst()
{
if (start == null) return default(T);
T saveVal = start.data;
start = start.next;
start.previous = null;
if (start == null) end = null;
return saveVal;
}
public T RemoveLast()
{
if (start == null) return default(T);
T saveVal = end.data;
end = end.previous;
end.next = null;
if (start == null) end = null;
return saveVal;
}
public void PrintAll()
{
Node<T> tmp = start;
while (tmp != null)
{
Console.WriteLine(tmp.data.ToString());
tmp = tmp.next;
}
}
}
And Use the following Node class
class Node<T>
{
public T data;
public Node<T> next;
public Node<T> previous;
public Node(T newData)
{
data = newData;
next = null;
previous = null;
}
}

Get data only one folder not for all folders in treeview - Blackberry

i want to show all folders(images, videos,files) with directories/files, currently only show images folder with files, but other folder are not show. I try to find solution but not found. Here is the code & its screenshot(http://postimg.org/image/wm5ypbk9d/).
FileManager.java
package com.rim.samples.device.mapactiondemo;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.KeypadListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.TreeField;
import net.rim.device.api.ui.component.TreeFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
public class FilesManager extends MainScreen {
FTPMessages _ftp = null;
String[] fileList;
// ..................
private final Bitmap openIcon = Bitmap.getBitmapResource("open.png");
private final Bitmap closedIcon = Bitmap.getBitmapResource("closed.png");
private final Bitmap movieIcon = Bitmap.getBitmapResource("movie.png");
private final Bitmap songIcon = Bitmap.getBitmapResource("song.png");
private final Bitmap playIcon = Bitmap.getBitmapResource("play.png");
private final Bitmap imgIcon = Bitmap.getBitmapResource("images.png");
String nodeTen;
int node10;
TreeField myTree;
String[] nodeData;
// ListField to be displayed - null - no Field displayed
// List of entries to be displayed - null or length = 0 means no entries
// protected so that another Thread can update this list....
protected ListDirectory[] _resultsList = null; // entries available for
// display
private ListDirectory _selectedEntry = null;
public FilesManager(FTPMessages ftp) {
super();
_ftp = ftp;
// Setting starting directory
try {
/*
* fileList = _ftp.list(); for (int i = 0; i < fileList.length; i++)
* { _ftp.cwd(fileList[i]); }
*/
_ftp.cwd("images");
_ftp.cwd("files");
_ftp.cwd("videos");
} catch (Exception e) {
}
this.setTitle("Server File List");
TreeCallback myCallback = new TreeCallback();
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. Do some default action or
// else fall through.
// Note: this will also detect empty folders, which
// might or
// might not be something your app has to handle
Dialog.alert("clicked " + getCookie(node));
// TODO: open player screen, etc.
return true;
}
}
return super.navigationClick(status, time);
}
};
myTree.setDefaultExpanded(false);
myTree.setRowHeight(openIcon.getHeight());
try {
node10 = myTree.addChildNode(0, _ftp.pwd());
} catch (Exception e) {
}
this.add(myTree);
refreshList();
}
private void refreshList() {
// TODO Auto-generated method stub
_resultsList = null;
String[] directory = null;
try {
directory = _ftp.list();
} catch (Exception e) {
}
if (directory != null && directory.length > 0) {
_resultsList = new ListDirectory[directory.length];
for (int i = 0; i < directory.length; i++) {
_resultsList[i] = new ListDirectory(directory[i],
ListDirectory.UNIX_SERVER);
}
}
if (_resultsList != null && _resultsList.length > 0) {
// we have some results
for (int i = 0; i < _resultsList.length; i++) {
String bb = directory[i];
String nodeFive = new String(bb);
this.myTree.addChildNode(node10, nodeFive);
}
} else {
}
}
private class TreeCallback implements TreeFieldCallback {
public void drawTreeItem(TreeField _tree, Graphics g, int node, int y,
int width, int indent) {
final int PAD = 8;
String text = (String) _tree.getCookie(node);
Bitmap icon = closedIcon;
if (text.endsWith(".mp3")) {
icon = songIcon;
} else if (text.endsWith(".avi")) {
icon = movieIcon;
} else if (text.endsWith(".png") || text.endsWith(".jpg")) {
icon = imgIcon;
} else if (_tree.getExpanded(node)) {
icon = openIcon;
}
g.drawBitmap(indent, y, icon.getWidth(), icon.getHeight(), icon, 0,
0);
// This assumes filenames all contain '.' character!
if (text.indexOf(".") > 0) {
// Leaf node, so this is a playable item (movie or song)
g.drawBitmap(_tree.getWidth() - playIcon.getWidth() - PAD, y
+ PAD, playIcon.getWidth(), playIcon.getHeight(),
playIcon, 0, 0);
}
int fontHeight = getFont().getHeight();
g.drawText(text, indent + icon.getWidth() + PAD,
y + (_tree.getRowHeight() - fontHeight) / 2);
}
}
}
The other classes that used with this code, download from that link(complete project classes)
http://remote.offroadstudios.com/files/filemanager.zip
you can also check files on server, ip:64.207.150.31:21, username:remote, password:123456789

Limited ListField items are drawn instead of complete list in Blackberry

I am trying to draw a list of all contacts saved in device. Everything is fine but when I select all contacts, I get only those contacts which are drawn on the screen. In other words, list drawing only those contacts which are visible on screen. To get the remaining contacts I have to scroll the list.
Here is my code:
public class CheckboxListField extends VerticalFieldManager implements ListFieldCallback, FieldChangeListener {
private static Vector selectedContacts ;
private ChecklistData[] mListData = new ChecklistData[] {};
private ListField mListField;
private static Vector mContacts;
private ContactList contactList;
private Enumeration allContacts;
private SendEmail sendEmail;
private boolean isChecked=false;
private BlackBerryContact contactItem;
private VerticalFieldManager _mainVFM = new VerticalFieldManager();
private int i;
private int j=0;
private String emails="";
private ButtonField _inviteButton;
private HorizontalFieldManager selectAllHFM;
private CustomButtonField selectAllButton;
private Bitmap _uncheckBmp;
private Bitmap _checkBmp;
private LabelField selectAllLabel;
private CheckboxField selectAllCheckBox;
private VerticalFieldManager contactListVFM;
private boolean listItemChecked=false;
private StringBuffer rowString;
private boolean getCBoxStatus;
// 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;
private String _telNumber;
ChecklistData(String stringVal, boolean checked) {
_stringVal = stringVal;
_checked = checked;
//_telNumber = telNumber;
}
// Get/set methods.
private String getStringVal() {
return _stringVal;
}
private boolean isChecked() {
return _checked;
}
// Toggle the checked status.
public void toggleChecked() {
_checked = !_checked;
}
}
public CheckboxListField() {
_mainVFM.add(createContactList(isChecked));
add(_mainVFM);
}
public VerticalFieldManager createContactList(boolean checked){
isChecked = checked;
selectedContacts = new Vector();
//INVITE BUTTON
contactListVFM = new VerticalFieldManager();
_inviteButton=new ButtonField("Invite Friend");
_inviteButton.setChangeListener(this);
_inviteButton.setMargin(2,0,10,0);
//SELECT ALL CHECKBOX
selectAllHFM = new HorizontalFieldManager();
_uncheckBmp = Bitmap.getBitmapResource("Uncheck.png");
_checkBmp = Bitmap.getBitmapResource("checked.png");
selectAllButton = new CustomButtonField(29, "", _uncheckBmp, _checkBmp, ButtonField.CONSUME_CLICK);
selectAllButton.setChangeListener(this);
selectAllButton.setMargin(5,5,5,5);
selectAllCheckBox = new CheckboxField("Select All", isChecked){
protected boolean navigationClick(int status,
int time) {
selectedContacts = new Vector();
emails = "";
boolean getCBoxStatus = selectAllCheckBox.getChecked();
if(listItemChecked == false){
if(_mainVFM.getFieldCount()!= 0){
_mainVFM.deleteAll();
_mainVFM.add(createContactList(getCBoxStatus));
}
}
return true;
}
};
selectAllCheckBox.setChangeListener(this);
selectAllLabel = new LabelField("Select All");
selectAllLabel.setMargin(5,5,5,5);
selectAllHFM.add(selectAllCheckBox);
//selectAllHFM.add(selectAllLabel);
// 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);
//contactListVFM.add(new NullField(NullField.FOCUSABLE));
contactListVFM.add(_inviteButton);
contactListVFM.add(selectAllHFM);
contactListVFM.add(new SeparatorField());
contactListVFM.add(mListField);
//LOAD CONTACTS
// load contacts in separate thread
loadContacts.run();
return contactListVFM;
}
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++) {
contactItem = (BlackBerryContact) mContacts
.elementAt(i);
String displayName = getDisplayName(contactItem);
// String telContact = getContact(item);
mListData[i] = new ChecklistData(
displayName, isChecked);
mListField.invalidate(i);
System.out.println(">>>>>>>>>"+mListData[i]);
}
mListField.setSize(size);
//invalidate();
}
};
protected void toggleItem() {
listItemChecked = true ;
selectAllCheckBox.setChecked(false);
listItemChecked =false ;
// Get the index of the selected row.
int index = mListField.getSelectedIndex();
System.out.println("..............."+index);
if (index != -1) {
// Get the ChecklistData for this row.
ChecklistData data = mListData[index];
// Toggle its status.
data.toggleChecked();
mListField.invalidate(index);
}
}
private boolean reloadContactList() {
try {
contactList = (ContactList) PIM
.getInstance()
.openPIMList(PIM.CONTACT_LIST,
PIM.READ_ONLY);
allContacts = contactList.items();
mContacts = enumToVector(allContacts);
mListField.setSize(mContacts.size());
System.out.println(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,>>>>>>>>>>"+mListField.getSize());
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()){
Contact contact = (Contact) allContacts.nextElement();
if(contactList.isSupportedField(Contact.EMAIL)&& (contact.countValues(Contact.EMAIL) > 0)) {
String emailID=contact.getString(Contact.EMAIL, 0);
if(emailID.length() !=0 && emailID != null ){
v.addElement(contact);
}
}
}
return v;
}
public void drawListRow(ListField list,
Graphics graphics, int index, int y, int w) {
rowString = new StringBuffer();
Object obj = this.get(list, index);
if (list.getSelectedIndex() != index) {
graphics.setBackgroundColor(index % 2 == 0 ||index==0 ? Color.WHITE
: Color.LIGHTGRAY);
graphics.clear();
//list.setFocus();
}
BlackBerryContact contact = (BlackBerryContact) mContacts
.elementAt(index);
String email= contact.getString(Contact.EMAIL, 0);
int vecIndex = selectedContacts.indexOf(email);
if (obj != null) {
ChecklistData currentRow = (ChecklistData) obj;
if (currentRow.isChecked()) {
if(vecIndex == -1){
selectedContacts.addElement(email);
}
rowString
.append(Characters.BALLOT_BOX_WITH_CHECK);
} else {
selectedContacts.removeElement(email);
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);
}
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];
}
System.out.println(",,,,,,,,,,,,,,,,,,,,,,,"+mListData.length);
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();
}
public void fieldChanged(Field field, int context) {
if(field==_inviteButton){
for(int n=0 ; n<selectedContacts.size() ; n++){
emails= emails + selectedContacts.elementAt(n)+",";
}
//}
String mailBody =": "+Jxa.loginUserName+" invited you on NaijaPings app. Please download NaijaPings Android app from here "+"http://appworld.blackberry.com/webstore/content/77264/?lang=en" ;
sendEmail=new SendEmail(mailBody);
sendEmail.Email(emails,Constant.emailSubject);
emails ="" ;
selectedContacts.removeAllElements();
}else if(field == selectAllCheckBox){
selectedContacts = new Vector();
emails = "";
getCBoxStatus = selectAllCheckBox.getChecked();
//selectedContacts.removeAllElements();
if(listItemChecked == false){
if(_mainVFM.getFieldCount()!= 0){
_mainVFM.deleteAll();
_mainVFM.add(createContactList(getCBoxStatus));
}
}
}
}
}
Here ,in drawListRow() , get() method is called only that many times that is number of contacts are visible on the screen. For remaining contact to add, I have to scroll the list.
In drawListRow() method I am adding those contacts into selectedContacts vector and than using those vector to get contact to send a mail. Contacts will be added only when particular list item will be drawn.
So, how I can get all selected contact without scrolling the list?
This is similar to the problem you had in one of your other recent questions. The problem is that drawListRow() is a callback designed to let you draw the rows that need drawing. It's not meant to do anything else, like assembling a list of contacts to email.
The BlackBerry OS tries to be efficient, so it will only ask you to drawListRow() for the rows that are actually visible to the user (on screen). Anything more would be wasteful.
So, if you want to assemble a list of all selected rows, you should do it somewhere else, not in drawListRow().
It looks to me like you can build a list of all currently selected rows by using this code, wherever you want:
public Vector getSelectedContacts() {
selectedContacts.removeAllElements();
for (int i = 0; i < mListData.length; i++) {
Object obj = mListData[i];
if (obj != null) {
BlackBerryContact contact = (BlackBerryContact) mContacts.elementAt(i);
String email = contact.getString(Contact.EMAIL, 0);
int vecIndex = selectedContacts.indexOf(email);
ChecklistData currentRow = (ChecklistData) obj;
if (currentRow.isChecked()) {
if(vecIndex == -1){
selectedContacts.addElement(email);
}
} else {
// this line is probably not actually needed, since we
// call removeAllElements() at the start of this method
selectedContacts.removeElement(email);
}
}
}
return selectedContacts;
}

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

Resources