blackberry lazyloading in clumsy layout - blackberry

I am using a customlistfield by extending VerticalFieldManager, and for the row I am usingf another CustoRowManager that extends Manager. The CustomRowManager has 2 TextField and a BitmapField . This list is implemented for a live xml feed. For loading the bitmapfield I am displaying placeholders which is then replaced by the actual image from background thread. I am not able to figure out how I should replace place holders with the bitmapfield. using invalidate() is one option, but on which element I should perform it.
public class CustomList extends VerticalFieldManager{
private int totalHeight = 0;
private int screenHeight = 0;
private int scrollPosition = 0;
protected void sublayout(int width, int height)
{
width = 480;
height = 230;
super.sublayout(width,height);
setExtent(width, height);
}
protected boolean navigationClick(int status, int time)
{
int index;
System.out.println("CLICKED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
if ((status & KeypadListener.STATUS_FOUR_WAY) == KeypadListener.STATUS_FOUR_WAY)
{
index = this.getFieldWithFocusIndex();
UiApplication.getUiApplication().pushScreen(new TopNewsScreen(_vec, index));
}
return true;
}
Bitmap _bmp = null;
BitmapField _bmF = null;
Object _Obj = null;
TopNews _topNews = null;
String _headStr = null, _metaStr = null;
CustTextField _headNews = null, _metaData = null;
CustomRow _custRow = null;
Vector _vec;
public CustomList(Vector _vec,long _property)
{
super(_property);
this._vec = new Vector();
this._vec = _vec;
int _size = _vec.size();
int i ;
for(i = 0; i <_size; i++)
{
_headStr = new String();
_metaStr = new String();
_bmp = Bitmap.getBitmapResource("img/1.jpg");
_bmF = new BitmapField(_bmp);
_topNews = (TopNews)_vec.elementAt(i);
_headStr = _topNews.getHeadline();
_metaStr = _topNews.getMetaData();
int _newsLeng = _headStr.length(), alert = 0;
if(_newsLeng <= 35)
{
alert = 0;
}else if(_newsLeng>35&&_newsLeng<=70)
{
alert = 1;
}else {
alert = 2;
_headStr = this.truncate(_headStr,70);
}
_custRow = new CustomRow(alert);
_headNews = new CustTextField(_headStr,25,0x05235b,TextField.NON_FOCUSABLE);
_metaData = new CustTextField(_metaStr,15,0x666666,TextField.NON_FOCUSABLE);
_custRow.add(_headNews);
_custRow.add(_metaData);
_custRow.add(_bmF);
super.add(_custRow);
}
}
String truncate(String value, int length)
{
if (value != null && value.length() > length)
value = value.substring(0, length);
return value;
}
}
class CustomRow extends Manager implements FocusChangeListener{
private int _headLeng;
private NullField _focus = null;
CustomRow(int _headLeng)
{
super(Manager.FOCUSABLE|
Manager.NO_HORIZONTAL_SCROLL
|Manager.NO_VERTICAL_SCROLL);
this._headLeng = _headLeng;
_focus = new NullField(NullField.FOCUSABLE);
_focus.setFocusListener(CustomRow.this);
this.add(_focus);
}
protected void sublayout(int width, int height)
{
if(_headLeng==0)
{
layoutChild(getField(0),0,0);
setPositionChild(getField(0),0 , 0);
layoutChild(getField(1),360,20);
setPositionChild(getField(1),10 , 10);
layoutChild(getField(2),300, 20);
setPositionChild(getField(2), 10, 65);
layoutChild(getField(3),90,65);
setPositionChild(getField(3), 380, 10);
}else
{
/* layoutChild(getField(0),0,0);
setPositionChild(getField(0),0 , 0);
layoutChild(getField(1),360,20);
setPositionChild(getField(1),10 , 10);
layoutChild(getField(2),300, 20);
setPositionChild(getField(2), 10, 50);
layoutChild(getField(3),90,65);
setPositionChild(getField(3), 380, 10); */
layoutChild(getField(0),0,0);
setPositionChild(getField(0),0 , 0);
layoutChild(getField(1),360,20);
setPositionChild(getField(1),10 , 10);
layoutChild(getField(2),300, 20);
setPositionChild(getField(2), 10, 65);
layoutChild(getField(3),90,65);
setPositionChild(getField(3), 380, 10);
}
height = 80;
width = 480;
setExtent(width, height);
}
protected void paint(Graphics graphics)
{
graphics.setColor(Color.GRAY);
graphics.drawLine(10, 79, Display.getWidth()-10, 79);
super.paint(graphics);
}
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
this.getManager().invalidate();
}
protected void paintBackground(Graphics g) {
int prevBg = g.getBackgroundColor();
if (_focus.isFocus()) {
g.setBackgroundColor(Color.LIGHTBLUE);
} else {
g.setBackgroundColor(Color.WHITE);
}
g.clear();
g.setBackgroundColor(prevBg);
}
}

the below link has answer for the question, I should change the name to Blackberry lazyloading.
http://supportforums.blackberry.com/t5/Java-Development/Clumsy-layout-invalidate/m-p/1398763

Related

How to scroll Horizontally in labelField in Blackberry

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.

Increase LabelField value as slider is moved

I have created a SliderField class in order to show a drag-able slider in my BlackBerry application. The slider is basically used to set interval for location updates (via GPS) in the app. The app is built on OS 5.0 and so no API was found for the SliderField. The problem
I am facing is that I need to increase the integer value in a label as the slider is moved. For instance, if the integer value in a label is 1 and the user moves the slider the value should increase to 5,10,15 etc. I do not know how to link moving the slider to increasing the value in the label field. Can anyone please help? I am adding the SliderField object to the screen as below:
Bitmap sliderBack = Bitmap.getBitmapResource( "progress51.png" );
Bitmap sliderFocus = Bitmap.getBitmapResource( "progress51.png" );
Bitmap sliderThumb = Bitmap.getBitmapResource( "butt.png" );
SliderField theSlider = new SliderField( sliderThumb, sliderBack, sliderFocus,20, 1, 1, 1 );
secondHFM.add(theSlider)
Below is my code for the SliderField class.
public class SliderField extends Field
{
Bitmap _imageThumb;
Bitmap _imageSlider;
Bitmap _imageSliderLeft;
Bitmap _imageSliderCenter;
Bitmap _imageSliderRight;
Bitmap _imageSliderFocus;
Bitmap _imageSliderFocusLeft;
Bitmap _imageSliderFocusCenter;
Bitmap _imageSliderFocusRight;
private int _numStates;
private int _currentState;
private boolean _selected;
private int _xLeftBackMargin;
private int _xRightBackMargin;
private int _thumbWidth;
private int _thumbHeight;
private int _totalHeight;
private int _totalWidth;
private int _rop;
private int _backgroundColours[];
private int _backgroundSelectedColours[];
private int _defaultSelectColour = 0x977DED;
private int _defaultBackgroundColour = 0x000000;
private int _defaultHoverColour = 0x999999;
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin )
{
this( thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin
, long style )
{
this( thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, style );
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, Bitmap sliderBackgroundFocus
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin )
{
this( thumb, sliderBackground, sliderBackgroundFocus, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, Bitmap sliderBackgroundFocus
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin
, long style )
{
super( style );
if( initialState > numStates || numStates < 2 ){
}
_imageThumb = thumb;
_imageSlider = sliderBackground;
_imageSliderFocus = sliderBackgroundFocus;
_numStates = numStates;
setState( initialState );
_xLeftBackMargin = xLeftBackMargin;
_xRightBackMargin = xRightBackMargin;
_rop = _imageSlider.hasAlpha() ? Graphics.ROP_SRC_ALPHA : Graphics.ROP_SRC_COPY;
_thumbWidth = thumb.getWidth();
_thumbHeight = thumb.getHeight();
initBitmaps();
}
public SliderField( Bitmap thumb
, Bitmap sliderBackground
, int numStates
, int initialState
, int xLeftBackMargin
, int xRightBackMargin
, int[] colours
, int[] selectColours )
{
this(thumb, sliderBackground, sliderBackground, numStates, initialState, xLeftBackMargin, xRightBackMargin, FOCUSABLE );
if( colours.length != numStates+1 ){
throw new IllegalArgumentException();
}
_backgroundColours = colours;
_backgroundSelectedColours = selectColours;
}
public void initBitmaps()
{
int height = _imageSlider.getHeight();
_imageSliderLeft = new Bitmap( _xLeftBackMargin, height );
_imageSliderCenter = new Bitmap( _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height);
_imageSliderRight = new Bitmap( _xRightBackMargin, height );
copy( _imageSlider, 0, 0, _xLeftBackMargin, height, _imageSliderLeft );
copy( _imageSlider, _xLeftBackMargin, 0, _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height, _imageSliderCenter);
copy( _imageSlider, _imageSlider.getWidth() - _xRightBackMargin, 0, _xRightBackMargin, height, _imageSliderRight);
_imageSliderFocusLeft = new Bitmap( _xLeftBackMargin, height );
_imageSliderFocusCenter = new Bitmap( _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height);
_imageSliderFocusRight = new Bitmap( _xRightBackMargin, height );
copy( _imageSliderFocus, 0, 0, _xLeftBackMargin, height, _imageSliderFocusLeft );
copy( _imageSliderFocus, _xLeftBackMargin, 0, _imageSlider.getWidth() - _xRightBackMargin - _xLeftBackMargin, height, _imageSliderFocusCenter);
copy( _imageSliderFocus, _imageSlider.getWidth() - _xRightBackMargin, 0, _xRightBackMargin, height, _imageSliderFocusRight);
}
private void copy(Bitmap src, int x, int y, int width, int height, Bitmap dest) {
int[] argbData = new int[width * height];
src.getARGB(argbData, 0, width, x, y, width, height);
for(int tx = 0; tx < dest.getWidth(); tx += width) {
for(int ty = 0; ty < dest.getHeight(); ty += height) {
dest.setARGB(argbData, 0, width, tx, ty, width, height);
}
}
}
public void setState(int newState) {
if( newState > _numStates ){
throw new IllegalArgumentException();
} else {
_currentState = newState;
invalidate();
}
}
public int getState() {
return _currentState;
}
public int getNumStates() {
return _numStates;
}
public int getColour() {
if(_backgroundSelectedColours != null) {
return _backgroundSelectedColours[getState()];
}
return 0x000000;
}
public int getPreferredWidth() {
return _totalWidth;
}
public int getPreferredHeight() {
return _totalHeight;
}
protected void layout( int width, int height ) {
if (width < 0 || height < 0)
throw new IllegalArgumentException();
_totalWidth = width;
_totalHeight = Math.max(_imageSlider.getHeight(), _imageThumb.getHeight());
setExtent( _totalWidth, _totalHeight );
}
public void paint( Graphics g )
{
int sliderHeight = _imageSlider.getHeight();
int sliderBackYOffset = ( _totalHeight - sliderHeight ) >> 1;
int backgroundColor = _defaultBackgroundColour;
if( _backgroundSelectedColours != null || _backgroundColours != null ) {
if( _selected ) {
backgroundColor = _backgroundSelectedColours != null ? _backgroundSelectedColours[getState()] : _defaultSelectColour;
} else if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) {
backgroundColor = _backgroundColours != null ? _backgroundColours[getState()] : _defaultHoverColour;
} else {
backgroundColor = _defaultBackgroundColour;
}
}
g.setColor( backgroundColor );
g.fillRect( 1, sliderBackYOffset + 1, _totalWidth - 2, sliderHeight - 2 );
if(g.isDrawingStyleSet(Graphics.DRAWSTYLE_FOCUS)) {
paintSliderBackground( g, _imageSliderFocusLeft, _imageSliderFocusCenter, _imageSliderFocusRight );
} else {
paintSliderBackground( g, _imageSliderLeft, _imageSliderCenter, _imageSliderRight );
}
int thumbXOffset = ( ( _totalWidth - _thumbWidth ) * _currentState ) / _numStates;
g.drawBitmap( thumbXOffset, ( _totalHeight - _thumbHeight ) >> 1, _thumbWidth, _thumbHeight, _imageThumb, 0, 0 );
}
private void paintSliderBackground( Graphics g, Bitmap left, Bitmap middle, Bitmap right )
{
int sliderHeight = _imageSlider.getHeight();
int sliderBackYOffset = ( _totalHeight - sliderHeight ) >> 1;
g.drawBitmap( 0, sliderBackYOffset, _xLeftBackMargin, sliderHeight, left, 0, 0 );
g.tileRop( _rop, _xRightBackMargin, sliderBackYOffset, _totalWidth - _xLeftBackMargin - _xRightBackMargin, sliderHeight, middle, 0, 0 );
g.drawBitmap( _totalWidth - _xRightBackMargin, sliderBackYOffset, _xRightBackMargin, sliderHeight, right, 0, 0 );
}
public void paintBackground( Graphics g )
{
}
protected void drawFocus( Graphics g, boolean on )
{
boolean oldDrawStyleFocus = g.isDrawingStyleSet( Graphics.DRAWSTYLE_FOCUS );
try {
if( on ) {
g.setDrawingStyle( Graphics.DRAWSTYLE_FOCUS, true );
}
paint( g );
} finally {
g.setDrawingStyle( Graphics.DRAWSTYLE_FOCUS, oldDrawStyleFocus );
}
}
protected boolean touchEvent(TouchEvent message)
{
boolean isConsumed = false;
boolean isOutOfBounds = false;
int x = message.getX(1);
int y = message.getY(1);
if(x < 0 || y < 0 || x > getExtent().width || y > getExtent().height) {
isOutOfBounds = true;
}
switch(message.getEvent()) {
case TouchEvent.CLICK:
case TouchEvent.MOVE:
if(isOutOfBounds) return true;
_selected = true;
int stateWidth = getExtent().width / _numStates;
int numerator = x / stateWidth;
int denominator = x % stateWidth;
if( denominator > stateWidth / 2 ) {
numerator++;
}
_currentState = numerator;
invalidate();
isConsumed = true;
break;
case TouchEvent.UNCLICK:
if(isOutOfBounds) {
_selected = false;
return true;
}
_selected = false;
stateWidth = getExtent().width / _numStates;
numerator = x / stateWidth;
denominator = x % stateWidth;
if( denominator > stateWidth / 2 ) {
numerator++;
}
_currentState = numerator;
invalidate();
fieldChangeNotify(0);
isConsumed = true;
break;
}
return isConsumed;
}
protected boolean navigationMovement(int dx, int dy, int status, int time)
{
if( _selected )
{
if(dx > 0 || dy > 0) {
incrementState();
fieldChangeNotify( 0 );
return true;
} else if(dx < 0 || dy < 0) {
decrementState();
fieldChangeNotify( 0 );
return true;
}
}
return super.navigationMovement( dx, dy, status, time);
}
public void decrementState() {
if(_currentState > 0) {
_currentState--;
invalidate();
}
}
public void incrementState() {
if(_currentState < _numStates) {
_currentState++;
invalidate();
}
}
protected boolean invokeAction(int action) {
switch(action) {
case ACTION_INVOKE: {
toggleSelected();
return true;
}
}
return false;
}
protected boolean keyChar( char key, int status, int time ) {
if( key == Characters.SPACE || key == Characters.ENTER ) {
toggleSelected();
return true;
}
return false;
}
protected boolean trackwheelClick( int status, int time ) {
if( isEditable() ) {
toggleSelected();
return true;
}
return super.trackwheelClick(status, time);
}
private void toggleSelected() {
_selected = !_selected;
invalidate();
}
public void setDirty( boolean dirty )
{
}
public void setMuddy( boolean muddy )
{
}
}
If you use the code below, you will get your actual requirement,you can get the slider current value into your screen class by invoking getValue() method on sliderfield reference..
Implement FieldChangeListener interface and try to override fieldChanged() method.
Use HorizontalFieldManager class and setStatus() method,
if you want to display your slider bar at bottom of your screen,other wise you can display it normally.
Here the Code:
public class SliderScreen extends MainScreen implements FieldChangeListener
{
private SliderField slider;
private HorizontalFieldManager hm;
public SliderField(){
slider = new SliderField(
Bitmap.getBitmapResource("slider2_thumb_normal.png"),
Bitmap.getBitmapResource("slider2_progress_normal.png"),
Bitmap.getBitmapResource("slider2_base_normal.png"),
Bitmap.getBitmapResource("slider2_thumb_focused.png"),
Bitmap.getBitmapResource("slider2_progress_focused.png"),
Bitmap.getBitmapResource("slider2_base_focused.png"), 8, 4,
8, 8, FOCUSABLE);
slider.setChangeListener(this);
hm = new HorizontalFieldManager();
hm.add(slider);
setStatus(hm);
}
public void fieldChanged(Field field, int context) {
try {
if (field == slider) {
int value = slider.getValue();
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
I have done simple example of how to use this code,Check it
public final class MyScreen extends MainScreen implements FieldChangeListener//,FocusChangeListener
{
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
SliderField slider;
slider = new SliderField(
Bitmap.getBitmapResource( "slider_thumb_normal.png" ), Bitmap.getBitmapResource( "slider_progress_normal.png" ), Bitmap.getBitmapResource( "slider_base_normal.png" ),
Bitmap.getBitmapResource( "slider_thumb_focused.png" ), Bitmap.getBitmapResource( "slider_progress_focused.png" ), Bitmap.getBitmapResource( "slider_base_focused.png"),
Bitmap.getBitmapResource( "slider_thumb_pressed.png" ), Bitmap.getBitmapResource( "slider_progress_pressed.png" ), Bitmap.getBitmapResource( "slider_base_pressed.png"),
10, 0, 12, 12, FOCUSABLE );
slider.setPadding( 20, 20, 20, 20 );
slider.setBackground( BackgroundFactory.createSolidBackground( 0xD3D3D3 ) );
slider.setChangeListener(this);
//slider.focusChangeNotify(0);
add( slider );
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if(field instanceof SliderField)
{
SliderField temp = (SliderField)field;
System.out.println("Temp value is"+temp.getValue());
}
}
}

How to custom go newline when calling drawtext()?

This is a listfield.
public class Custom_ListField extends ListField {
private String[] title, category, date, imagepath;
private int[] newsid, catsid;
private List_News newslist;
private Bitmap imagebitmap[], localimage = Bitmap
.getBitmapResource("image_base.png");
private BrowserField webpage;
private Custom_BrowserFieldListener listener;
private boolean islatest;
private Vector content = null;
private ListCallback callback = null;
private int currentPosition = 0;
public Custom_ListField(Vector content, boolean islatest) {
this.content = content;
this.islatest = islatest;
newsid = new int[content.size()];
title = new String[content.size()];
category = new String[content.size()];
date = new String[content.size()];
imagepath = new String[content.size()];
catsid = new int[content.size()];
imagebitmap = new Bitmap[content.size()];
for (int i = 0; i < content.size(); i++) {
newslist = (List_News) content.elementAt(i);
newsid[i] = newslist.getID();
title[i] = newslist.getNtitle();
category[i] = newslist.getNewCatName();
date[i] = newslist.getNArticalD();
imagepath[i] = newslist.getImagePath();
if (!imagepath[i].toString().equals("no picture")) {
imagebitmap[i] = Util_ImageLoader.loadImage(imagepath[i]);
} else {
imagebitmap[i] = localimage;
}
catsid[i] = newslist.getCatID();
}
initCallbackListening();
this.setRowHeight(localimage.getHeight() + 10);
}
private void initCallbackListening() {
callback = new ListCallback();
this.setCallback(callback);
}
private class ListCallback implements ListFieldCallback {
public ListCallback() {
setBackground(Config_GlobalFunction
.loadbackground("background.png"));
}
public void drawListRow(ListField listField, Graphics graphics,
int index, int y, int width) {
currentPosition = index;
graphics.drawBitmap(
Display.getWidth() - imagebitmap[index].getWidth() - 5,
y + 3, imagebitmap[index].getWidth(),
imagebitmap[index].getHeight(), imagebitmap[index], 0, 0);
graphics.setColor(Color.WHITE);
graphics.drawRect(0, y, width, imagebitmap[index].getHeight() + 10);
graphics.setColor(Color.BLACK);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 20));
graphics.drawText(title[index], 5, y + 3, 0, Display.getWidth()
- imagebitmap[index].getWidth() - 10);
graphics.setColor(Color.GRAY);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 15));
graphics.drawText(date[index], 5, y + 6
+ Font.getDefault().getHeight() + 3);
if (islatest) {
graphics.setColor(Color.RED);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 15));
graphics.drawText(category[index], Font.getDefault()
.getAdvance(date[index]) + 3, y + 6
+ Font.getDefault().getHeight() + 3);
}
}
public Object get(ListField listField, int index) {
return content.elementAt(index);
}
public int getPreferredWidth(ListField listField) {
return Display.getWidth();
}
public int indexOfList(ListField listField, String prefix, int start) {
return content.indexOf(prefix, start);
}
}
public int getCurrentPosition() {
return currentPosition;
}
protected boolean navigationClick(int status, int time) {
int index = getCurrentPosition();
if (catsid[index] == 9) {
if (Config_GlobalFunction.isConnected()) {
webpage = new BrowserField();
listener = new Custom_BrowserFieldListener();
webpage.addListener(listener);
MainScreen aboutus = new Menu_Aboutus();
aboutus.add(webpage);
Main.getUiApplication().pushScreen(aboutus);
webpage.requestContent("http://www.orientaldaily.com.my/index.php?option=com_k2&view=item&id="
+ newsid[index] + ":&Itemid=223");
} else
Config_GlobalFunction.Message(Config_GlobalFunction.nowifi, 1);
} else
Main.getUiApplication().pushScreen(
new Main_NewsDetail(newsid[index]));
return true;
}
}
Please look at the
graphics.setColor(Color.BLACK);
graphics.setFont(Font.getDefault().derive(Font.BOLD, 20));
graphics.drawText(title[index], 5, y + 3, 0, Display.getWidth()
- imagebitmap[index].getWidth() - 10);
This will only draw the text one line only. I did researched and found out there isn't built in function and must custom a function make the text auto next line.
The function something like this
private int numberoflines(int availablespace){
...
return numberlines
}
The links Rupak shows are good, although one of them references the generic Java problem (and proposes a Swing result that would need to be changed for BlackBerry), and the other references an external (non stack overflow) link.
If you want another option, and don't want the algorithm to figure out where to make the line breaks, you can use this. This code assumes you put '\n' characters into your strings, where you want to split the text into multiple lines. You would probably put this code in the paint() method:
// store original color, to reset it at the end
int oldColor = graphics.getColor();
graphics.setColor(Color.BLACK);
graphics.setFont(_fieldFont);
int endOfLine = _text.indexOf('\n');
if (endOfLine < 0) {
graphics.drawText(_text, _padding, _top);
} else {
// this is a multi-line label
int top = _top;
int index = 0;
int textLength = _text.length();
while (index < textLength) {
// draw one line at a time
graphics.drawText(_text,
index, // offset into _text
endOfLine - index, // number of chars to draw
_padding, // x
top, // y
(int) (DrawStyle.HCENTER | DrawStyle.TOP | Field.USE_ALL_WIDTH), // style flags
_fieldWidth - 2 * _padding); // width available
index = endOfLine + 1;
endOfLine = _text.indexOf('\n', index);
if (endOfLine < 0) {
endOfLine = textLength;
}
top += _fieldFont.getHeight() + _top; // top padding is set equal to spacing between lines
}
}
graphics.setColor(oldColor);
And here you would initialize some of the variables I use in that. I think these are right, based on the code you posted, but you'll need to double-check:
String _text = title[index]; // text to draw
int _padding = 5; // left and right side padding around text
int _top = y + 3; // the y coordinate of the top of the text
Font _fieldFont = Font.getDefault().derive(Font.BOLD, 20);
// the total width reserved for the text, which includes room for _padding:
int _fieldWidth = Display.getWidth() - imagebitmap[index].getWidth();

Blackberry BitmapField from SD card

I want to show a image from the SD card in a BitmapField. How to do that? Can anyone give me some sample code for that?
This may be Help full.
public Bitmap getImage(){
Bitmap bitmapImage=null;
try{
InputStream input;
FileConnection fconn = (FileConnection) Connector.open("file:///store/home/user/dirname/imgname.png", Connector.READ_WRITE);
input = fconn.openInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int j = 0;
while((j=input.read()) != -1) {
baos.write(j);
}
byte[] byteArray = baos.toByteArray();
bitmapImage = Bitmap.createBitmapFromBytes(byteArray,0,byteArray.length,1);
}catch(Exception ioe){
System.out.println(ioe);
}
return bitmapImage;
}
Enjoy..
Hi Guys above code is useful for BB OS >= 5.0
I'm using a code which can used for OS 4.2 or higher.
private Bitmap resizeBitmap(Bitmap image, int width, int height)
{
int rgb[] = new int[image.getWidth()*image.getHeight()];
image.getARGB(rgb, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
int rgb2[] = rescaleArray(rgb, image.getWidth(), image.getHeight(), width, height);
Bitmap temp2 = new Bitmap(width, height);
temp2.setARGB(rgb2, 0, width, 0, 0, width, height);
return temp2;
}
private int[] rescaleArray(int[] ini, int x, int y, int x2, int y2)
{
int out[] = new int[x2*y2];
for (int yy = 0; yy < y2; yy++)
{
int dy = yy * y / y2;
for (int xx = 0; xx < x2; xx++)
{
int dx = xx * x / x2;
out[(x2 * yy) + xx] = ini[(x * dy) + dx];
}
}
return out;
}
Try this sample code:
public class LoadingScreen extends MainScreen implements FieldChangeListener
{
private VerticalFieldManager ver;
private ButtonField showImage;
private BitmapField bitmapField;
public LoadingScreen()
{
ver=new VerticalFieldManager(USE_ALL_WIDTH);
showImage=new ButtonField("Show Image",Field.FIELD_HCENTER);
showImage.setChangeListener(this);
ver.add(showImage);
bitmapField=new BitmapField(null,Field.FIELD_HCENTER);
bitmapField.setPadding(10, 0, 10, 0);
ver.add(bitmapField);
add(ver);
}
public void fieldChanged(Field field, int context)
{
if(field==showImage)
{
selectImageFromSDCARD();
}
}
private void selectImageFromSDCARD()
{
String PATH="";
if(SDCardTest.isSDCardAvailable())//sdcard available then
PATH = System.getProperty("fileconn.dir.memorycard.photos");//The default stored Images Path;
else
PATH = System.getProperty("fileconn.dir.photos");//The default stored Images Path;
FilePicker filePicker=FilePicker.getInstance();
filePicker.setPath(PATH);
filePicker.setListener(new Listener()
{
public void selectionDone(String url)
{
System.out.println("======================URL: "+url);
try
{
FileConnection file = (FileConnection)Connector.open(url);
if(file.exists())
{
InputStream inputStream = file.openInputStream();
byte[] data=new byte[inputStream.available()];
data=IOUtilities.streamToBytes(inputStream);
Bitmap bitmap=Bitmap.createBitmapFromBytes(data, 0, data.length,1);//Here we get the Image;
Bitmap scaleBitmap=new Bitmap(400, 300);//Now we are scaling that image;
bitmap.scaleInto(scaleBitmap, Bitmap.FILTER_LANCZOS);
bitmapField.setBitmap(scaleBitmap);
}
else
{
bitmapField.setBitmap(Bitmap.getBitmapResource("icon.png"));
}
}
catch (IOException e)
{
bitmapField.setBitmap(Bitmap.getBitmapResource("icon.png"));
}
}
});
filePicker.show();
}
protected boolean onSavePrompt() //It doesn't show the "Save","Discard","Cancel" POPUP;
{
return true;
}
public boolean onMenu(int instance) //It doesn't show the Menu;
{
return true;
}
}
If you have any doubts refer this Blog: Get Image From SDcard

Not able to show the events against same time one after other in horizontal manager in Blackberry

I am trying to get events from Blackberry Calendar. I am trying to show the events occurring at the same time one after other
like
8:00 e1
8:00 e2
as in native Calendar
But the following code shows the output as
8:00 e1 e2
in my code i have 24 hfm added to single vfm.
int size1 = 2;
horizontalFieldManager_left22 = new HorizontalFieldManager[size1];
for (int y = 0; y < size1; y++) {
horizontalFieldManager_left22[y] = new HorizontalFieldManager() {
protected boolean navigationClick(int status, int time) {
Field field = getFieldWithFocus();
Vector data = getData(listEvent);
String currentData = desc22.getText();
String currentTime = time22.getText();
if (currentData != null && currentData != "") {
UiApplication.getUiApplication().pushScreen(new EventScreen(data,currentData,currentTime));
}
return super.navigationClick(status, time);
}
protected boolean keyChar (char key, int status, int time) {
Field field = getFieldWithFocus();
return
super.keyChar(key, status, time);
}
};
int size = eventVector7.size();
LabelField[] labelField = new
LabelField[size];
for (int x = 0; x < eventVector7.size(); x++) {
labelField[x] = new
LabelField("", Field.FOCUSABLE);
String data = (String)
eventVector7.elementAt(x);
labelField[x].setText(data);
horizontalFieldManager_left22[y].add(time22);
horizontalFieldManager_left22[y].add(min22);
horizontalFieldManager_left22[y].add(new LabelField(" "));
horizontalFieldManager_left22[y].add(labelField[x]);
}
}
for (int z = 0; z < size1; z++) {
vfm.add(horizontalFieldManager_left22 [z]);
vfm.add(new SeparatorField());
}
import java.util.Hashtable;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class ListAllEvents extends MainScreen {
// -----------------------------------------------------------------
VerticalFieldManager mainManager;
VerticalFieldManager listVFM;
HorizontalFieldManager rowHFM[];
int row_height;
LabelField[] eventTimeLabel;
LabelField[] eventNameLabel;
public ListAllEvents() {
createUI();
createEventHashtable();
}
// -------------- Create UI --------------------------------
public void createUI() {
mainManager = new VerticalFieldManager(
VerticalFieldManager.VERTICAL_SCROLL
| VerticalFieldManager.VERTICAL_SCROLLBAR
| VerticalFieldManager.USE_ALL_HEIGHT
| VerticalFieldManager.FIELD_LEFT | DrawStyle.LEFT) {
protected void sublayout(int maxWidth, int maxHeight) {
int displayWidth = Display.getWidth();
int displayHeight = Display.getHeight();
super.sublayout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
public void paint(Graphics g) {
g.setBackgroundColor(Color.WHITE);
g.clear();
super.paint(g);
}
};
add(mainManager);
}
// ----------------------------Create List
// ----------------------------------------
public void createList(Hashtable eventHashtable) {
listVFM = new VerticalFieldManager();
rowHFM = new HorizontalFieldManager[eventHashtable.size()];
eventTimeLabel = new LabelField[eventHashtable.size()];
eventNameLabel = new LabelField[eventHashtable.size()];
row_height = 90;
int j = 0;
int row_count = 0;
if (eventHashtable.size() > 0) {
EventItem ei = null;
for (int i = 0; i < eventHashtable.size(); i++) {
Object obj = eventHashtable.get(new Integer(i));
final EventItem item = (EventItem) obj;
if (item != null) {
String str_event_time = item.event_time;
String str_event_name = item.event_name;
rowHFM[row_count] = new HorizontalFieldManager(
HorizontalFieldManager.USE_ALL_HEIGHT) {
protected void sublayout(int maxWidth, int maxHeight) {
int displayWidth = Display.getWidth();
int displayHeight = 80;
super.sublayout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
rowHFM[row_count].setPadding(2, 2, 2, 2);
eventTimeLabel[row_count] = new LabelField(str_event_time) {
protected void layout(int maxWidth, int maxHeight) {
int displayWidth = (int) (Display.getWidth() / 2);
int displayHeight = maxHeight;
super.layout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
eventTimeLabel[row_count].setPadding(5, 0, 0, 2);
eventNameLabel[row_count] = new LabelField(str_event_name) {
protected void layout(int maxWidth, int maxHeight) {
int displayWidth = (int) (Display.getWidth() / 2);
int displayHeight = maxHeight;
super.layout(displayWidth, displayHeight);
setExtent(displayWidth, displayHeight);
}
};
eventNameLabel[row_count].setPadding(5, 0, 0, 2);
rowHFM[row_count].add(eventTimeLabel[row_count]);
rowHFM[row_count].add(eventNameLabel[row_count]);
listVFM.add(rowHFM[row_count]);
}
}
}
listVFM.setPadding(5, 2, 5, 2);
mainManager.add(listVFM);
}
public void createEventHashtable() {
String event_time1 = "8:00";
String event_time2 = "8:00";
String event_name1 = "Event 1";
String event_name2 = "Event 2";
Hashtable eventHashtable = new Hashtable();
eventHashtable.put(new Integer(0), new EventItem(event_time1,
event_name1));
eventHashtable.put(new Integer(1), new EventItem(event_time2,
event_name2));
createList(eventHashtable);
}
}
public class EventItem {
String event_time;
String event_name;
public EventItem(String event_time, String event_name) {
this.event_name = event_name;
this.event_time = event_time;
}
}

Resources