How save best first three scores or only best score, I am new in programming.
I have score, but how define new score and old score.
public class HighScores extends Activity {
private TextView thighscore1;
private TextView thighscore2;
private TextView thighscore3;
public TextView name;
public int highscore1 =0;
public int highscore2 =0;
public int highscore3 =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_high);
name = (TextView) findViewById(R.id.Names);
thighscore1 = (TextView) findViewById(R.id.highscore1);
thighscore2 = (TextView) findViewById(R.id.highscore2);
thighscore3 = (TextView) findViewById(R.id.highscore3);
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey",
Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value
thighscore1.setText("" + score);
if(score > highscore2) {
highscore1 = score;
thighscore1.setText("" + highscore1);
}else{
highscore1=highscore1;
}
if(score > highscore3 && score < highscore1){
highscore2 = score;
thighscore2.setText("" + highscore2);
}else{
highscore2 = highscore2;
}
if (score > 0 && score < highscore2){
highscore3 = score;
thighscore3.setText("" + highscore3);
}else{
highscore3 = highscore3;
}
SharedPreferences sp = this.getSharedPreferences("MyKey",0);
String data = sp.getString("tag", "");
name.setText(""+ data);
}}
For setting scores in Preference:
SharedPreferences.Editor editor = getSharedPreferences("PreferenceName",MODE_PRIVATE).edit();
editor.putInt("Score1", highscore1);
editor.putInt("Score2", highscore2);
editor.putInt("Score3", highscore3);
editor.apply();
For retrieving scores from Preference:
SharedPreferences prefs = getSharedPreferences("PreferenceName",MODE_PRIVATE);
if(prefs.getString("text", null) != null) {
int score1 = prefs.getInt("Score1", 0); // 0 is the default value
int score2 = prefs.getInt("Score2", 0);
int score3 = prefs.getInt("Score3", 0);
}
More information on SharedPreferences
To delete any value from Preference
editor.remove("highscore1"); // will delete highscore1
I resolved my problem with score also have a name:
if (number > prefs.getInt("key", 0)) {
editor.putInt("key", number);
editor.putString("tag", value);
} else if (number < prefs.getInt("key", 0)) {
if (number > prefs.getInt("key1", 0)) {
editor.putInt("key1", number);
editor.putString("tag1", value1);
}
}
if (number < prefs.getInt("key1", 0)) {
editor.putInt("key2", number);
editor.putString("tag2", value2);
}
Related
We have an NxM grid, grid have one element named Bob. Bob can travel diagonally blocks only. The grid has some blocked blocks on which Bob can not travel. Write a function that returns on how many possible positions Bob can move. Solve this problem using BFS and submit the executable code in any programming language. In the following image example, Bob's positioning is at 9,3, and it can visit the places where Y is marked; hence your method should return 30.
Anybody any pseudocode or approach on how to solve this using BFS
Following solution is modified version of solution given by ( https://stackoverflow.com/users/10987431/dominicm00 ) on problem ( Using BFS to find number of possible paths for an object on a grid )
Map.java:
import java.awt.*;
public class Map {
public final int width;
public final int height;
private final Cell[][] cells;
private final Move[] moves;
private Point startPoint;
public Map(int[][] mapData) {
this.width = mapData[0].length;
this.height = mapData.length;
cells = new Cell[height][width];
// define valid movements
moves = new Move[]{
new Move(1, 1),
new Move(-1, 1),
new Move(1, -1),
new Move(-1, -1)
};
generateCells(mapData);
}
public Point getStartPoint() {
return startPoint;
}
public void setStartPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
startPoint.setLocation(p);
}
public Cell getStartCell() {
return getCellAtPoint(getStartPoint());
}
public Cell getCellAtPoint(Point p) {
if (!isValidLocation(p)) throw new IllegalArgumentException("Invalid point");
return cells[p.y][p.x];
}
private void generateCells(int[][] mapData) {
boolean foundStart = false;
for (int i = 0; i < mapData.length; i++) {
for (int j = 0; j < mapData[i].length; j++) {
/*
0 = empty space
1 = wall
2 = starting point
*/
if (mapData[i][j] == 2) {
if (foundStart) throw new IllegalArgumentException("Cannot have more than one start position");
foundStart = true;
startPoint = new Point(j, i);
} else if (mapData[i][j] != 0 && mapData[i][j] != 1) {
throw new IllegalArgumentException("Map input data must contain only 0, 1, 2");
}
cells[i][j] = new Cell(j, i, mapData[i][j] == 1);
}
}
if (!foundStart) throw new IllegalArgumentException("No start point in map data");
// Add all cells adjacencies based on up, down, left, right movement
generateAdj();
}
private void generateAdj() {
for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells[i].length; j++) {
for (Move move : moves) {
Point p2 = new Point(j + move.getX(), i + move.getY());
if (isValidLocation(p2)) {
cells[i][j].addAdjCell(cells[p2.y][p2.x]);
}
}
}
}
}
private boolean isValidLocation(Point p) {
if (p == null) throw new IllegalArgumentException("Point cannot be null");
return (p.x >= 0 && p.y >= 0) && (p.y < cells.length && p.x < cells[p.y].length);
}
private class Move {
private int x;
private int y;
public Move(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}}
Cell.java:
import java.util.LinkedList;
public class Cell {
public final int x;
public final int y;
public final boolean isWall;
private final LinkedList<Cell> adjCells;
public Cell(int x, int y, boolean isWall) {
if (x < 0 || y < 0) throw new IllegalArgumentException("x, y must be greater than 0");
this.x = x;
this.y = y;
this.isWall = isWall;
adjCells = new LinkedList<>();
}
public void addAdjCell(Cell c) {
if (c == null) throw new IllegalArgumentException("Cell cannot be null");
adjCells.add(c);
}
public LinkedList<Cell> getAdjCells() {
return adjCells;
}}
MapHelper.java:
class MapHelper {
public static int countReachableCells(Map map) {
if (map == null) throw new IllegalArgumentException("Arguments cannot be null");
boolean[][] visited = new boolean[map.height][map.width];
// subtract one to exclude starting point
return dfs(map.getStartCell(), visited) - 1;
}
private static int dfs(Cell currentCell, boolean[][] visited) {
visited[currentCell.y][currentCell.x] = true;
int touchedCells = 0;
for (Cell adjCell : currentCell.getAdjCells()) {
if (!adjCell.isWall && !visited[adjCell.y][adjCell.x]) {
touchedCells += dfs(adjCell, visited);
}
}
return ++touchedCells;
}}
Grid.java:
public class Grid{
public static void main(String args[]){
int[][] gridData = {
{0,0,0,0,0,0,0,0},
{0,1,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,1,0,0,1,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,1,0},
{0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,2,1,0,0,0}}; //2 is bobs position, 1 is blocked, 0 can be visited
Map grid = new Map(gridData);
MapHelper solution = new MapHelper();
System.out.println(solution.countReachableCells(grid));
}}
For original answer of similar problem visit (Using BFS to find number of possible paths for an object on a grid) for original answer.
This program should print out the values in order ascending order. But it only displays 957.0 repeatedly. How do I display the numbers in order?
import java.io.*;
import java.util.*;
class PriorityQ {
public int maxSize;
public double[] queArray;
public int nItems;
//------
public PriorityQ(int s){
maxSize = s;
queArray = new double[maxSize];
nItems = 0;
}
//-----
public void insert(double item){
int j;
if(nItems == 0){
queArray[nItems++] = item;
}
else{
for(j = nItems-1; j >= 0; j--){
if(item > queArray[j]){
queArray[j + 1] = item;
}
else{
break;
}
}
queArray[j + 1] = item;
nItems++;
}
}
//-----
public double remove(){
return queArray[--nItems];
}
//-----
public double peekMin(){
return queArray[nItems - 1];
}
//-----
public boolean isEmpty(){
return(nItems == 0);
}
//-----
public boolean isFull(){
return(nItems == maxSize);
}
}
//-----
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQ thePQ = new PriorityQ(5);
thePQ.insert(546);
thePQ.insert(687);
thePQ.insert(36);
thePQ.insert(98);
thePQ.insert(957);
while(!thePQ.isEmpty()){
double item = thePQ.remove();
System.out.print(item + " ");
}
System.out.println("");
}
}
You should save yourself the effort and use a priority queue with the generic type Double. If you wanted descending order you could even use a comparator that orders the highest value before the lowest, but you asked for ascending.
Your problem is that your array does contain many copies of 957.
This is because of this line in your code:
if(item > queArray[j]){
queArray[j + 1] = item;
}
Try:
import java.io.*;
import java.util.*;
public class PriorityQApp{
public static void main(String[] args) throws IOException{
PriorityQueue<Double> thePQ = new PriorityQueue<Double>(5);
thePQ.add(546);
thePQ.add(687);
thePQ.add(36);
thePQ.add(98);
thePQ.add(957);
while(thePQ.size() > 0){
double item = thePQ.poll();
System.out.print(item + " ");
}
System.out.println("");
}
}
Or I can fix your code to print out the queue in descending order leaving it to you to then make it print out in ascending order, the block I pointed to before should read like this instead:
if(item < queArray[j]){
queArray[j + 1] = queArray[j];
}
I want to scroll Horizontally in label Field.
I am adding this LabelField in Custom GridField Manager. Here is the code of Custom GridField Manager.
public class CustomGridFieldManager extends Manager {
private int[] columnWidths;
private int columns;
private int allRowHeight = -1;
public CustomGridFieldManager(int columns, long style) {
super(style);
this.columns = columns;
}
public CustomGridFieldManager(int[] columnWidths, long style) {
super(style);
this.columnWidths = columnWidths;
this.columns = columnWidths.length;
}
public CustomGridFieldManager(int[] columnWidths, int rowHeight, long style) {
this(columnWidths, style);
this.allRowHeight = rowHeight;
}
protected boolean navigationMovement(int dx, int dy, int status, int time) {
int focusIndex = getFieldWithFocusIndex();
while(dy > 0) {
focusIndex += columns;
if (focusIndex >= getFieldCount()) {
return false; // Focus moves out of this manager
}
else {
Field f = getField(focusIndex);
if (f.isFocusable()) { // Only move the focus onto focusable fields
f.setFocus();
dy--;
}
}
}
while(dy < 0) {
focusIndex -= columns;
if (focusIndex < 0) {
return false;
}
else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dy++;
}
}
}
while(dx > 0) {
focusIndex ++;
if (focusIndex >= getFieldCount()) {
return false;
}
else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dx--;
}
}
}
while(dx < 0) {
focusIndex --;
if (focusIndex < 0) {
return false;
}
else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dx++;
}
}
}
return true;
}
protected void sublayout(int width, int height) {
int y = 0;
if (columnWidths == null) {
columnWidths = new int[columns];
for(int i = 0; i < columns; i++) {
columnWidths[i] = width/columns;
}
}
Field[] fields = new Field[columnWidths.length];
int currentColumn = 0;
int rowHeight = 0;
for(int i = 0; i < getFieldCount(); i++) {
fields[currentColumn] = getField(i);
layoutChild(fields[currentColumn], columnWidths[currentColumn], height-y);
if (fields[currentColumn].getHeight() > rowHeight) {
rowHeight = fields[currentColumn].getHeight();
}
currentColumn++;
if (currentColumn == columnWidths.length || i == getFieldCount()-1) {
int x = 0;
if (this.allRowHeight >= 0) {
rowHeight = this.allRowHeight;
}
for(int c = 0; c < currentColumn; c++) {
long fieldStyle = fields[c].getStyle();
int fieldXOffset = 0;
long fieldHalign = fieldStyle & Field.FIELD_HALIGN_MASK;
if (fieldHalign == Field.FIELD_RIGHT) {
fieldXOffset = columnWidths[c] - fields[c].getWidth();
}
else if (fieldHalign == Field.FIELD_HCENTER) {
fieldXOffset = (columnWidths[c]-fields[c].getWidth())/2;
}
int fieldYOffset = 0;
long fieldValign = fieldStyle & Field.FIELD_VALIGN_MASK;
if (fieldValign == Field.FIELD_BOTTOM) {
fieldYOffset = rowHeight - fields[c].getHeight();
}
else if (fieldValign == Field.FIELD_VCENTER) {
fieldYOffset = (rowHeight-fields[c].getHeight())/2;
}
setPositionChild(fields[c], x+fieldXOffset, y + fieldYOffset);
x += columnWidths[c];
}
currentColumn = 0;
y += rowHeight;
}
if (y >= height) {
break;
}
}
int totalWidth = 0;
for(int i = 0; i < columnWidths.length; i++) {
totalWidth += columnWidths[i];
}
setExtent(totalWidth, Math.min(y, height));
}
}
In another Class, I use this custom GridField Manager Class.
int[] width = { (int) (Display.getWidth() / 2.9),
(int) (Display.getWidth() / 1.1) };
final CustomGridFieldManager gfm_transactioninfo = new CustomGridFieldManager(
width, 35, Manager.VERTICAL_SCROLL | Manager.FIELD_HCENTER
| FOCUSABLE) {
protected void paint(Graphics graphics) {
// TODO Auto-generated method stub
graphics.setColor(AppData.color_black);
super.paint(graphics);
}
};
gfm_transactioninfo.setMargin(10, 0, 0, 10);// set top and left margin
I add Labelfiled like this,
lbl_CustEmail = new LabelField("Customer Email", LabelField.FOCUSABLE);
lbl_CustEmail.setFont(label_font);
value_CustEmail = new LabelField(": " +trandtail[0].getFromEmail());
value_CustEmail.setFont(label_font);
gfm_transactioninfo.add(lbl_CustEmail);
gfm_transactioninfo.add(value_CustEmail);
If any one has any idea regarding How to scroll Horizontally then please help me. Thanks in Advance.
By customizing your grid view ,you may add one FocusableNullField before and after the label field. By doing so once the focus is on the first null field you can scroll horizontally to the next focusablenullfield and explicitly make labelfield scrollable.
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.
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;
}