Get request for Millennial Media Advertisement in my Blackberry app - blackberry

I am trying to make a blackberry get request for advertisement from millennial media, I would love some help I cant seems to get it to work. This is what I have:
String url ="http://ads.mp.mydas.mobi/getAd?apid=157899&auid=ddd25abbb993f79454b12827c803fbafab2ad89b";
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection(); conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
buff.append(IOUtilities.streamToBytes(in));
result = buff.toString();
}
else {
result = "Error in connection" + conn.getResponseCode();
((ButterflyScreen)screen).update(result);
}
catch (Exception ex) {ex.printStackTrace();
}
finally {
try{ if (in !=null)
{in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is my complete code for the class am trying to implement the get request.
import java.io.*;
import java.rmi.*;
import javax.microedition.io.HttpConnection;
import net.rim.blackberry.api.browser.Browser;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.ButtonField;
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;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.decor.BorderFactory;
import com.ctpl.butterfly.custom.HrefField;
/**
* A class extending the MainScreen class,This is Home Screen on App.
*/
public final class ButterflyScreen extends MainScreen {
private ButtonField btnSetting;
private LabelField lblMsgNameOfApp, lblMsgDesc, lblHeading;
private HrefField lblMsgWebLink;
private Bitmap borderBitmap;
ButterflyScreen screen;
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = "";
/**
* Creates a new ButterflyScreen object
*/
public ButterflyScreen() {
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
this.getMainManager().setBackground(BackgroundFactory.createLinearGradientBackground(0x0099CCFF,
0x0099CCFF,0x00336699,0x00336699)
);
lblHeading = new LabelField(StringRes.APP_NAME) {
protected void paint(Graphics graphics) {
graphics.setColor(Color.WHITE);
super.paint(graphics);
}
};
HorizontalFieldManager topPannel = new HorizontalFieldManager(
Field.FIELD_HCENTER | Field.USE_ALL_WIDTH) {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(maxWidth, maxHeight);
int x = getWidth() / 2;
x = x - lblHeading.getWidth() / 2;
int y = 0;
setPositionChild(lblHeading, x, y);
setBackground(BackgroundFactory.createBitmapBackground(Bitmap.getBitmapResource("footer_back.png")));
}
};
lblHeading.setFont(lblHeading.getFont().derive(Font.BOLD));
topPannel.add(lblHeading);
setTitle(topPannel);
lblMsgNameOfApp = new LabelField(StringRes.WORLD+" \n") {
protected void paint(Graphics graphics) {
graphics.setColor(Color.PURPLE);
super.paint(graphics);
}
};
lblMsgDesc = new LabelField(StringRes.WELCOME_SCREEN_MESSAGE+" \n");
lblMsgWebLink = new HrefField("© Carib Tech Production Limited");
lblMsgWebLink.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
Browser.getDefaultSession().displayPage("http://caribtechprod.com");
}
});
btnSetting = new ButtonField(StringRes.SETTING_SCREEN);
btnSetting.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
UiApplication.getUiApplication().pushScreen(new SettingWaitScreen());
}
});
setDescScreen();
}
private void setDescScreen() {
VerticalFieldManager vfmForCenterDisplay = new VerticalFieldManager(Field.USE_ALL_WIDTH | Field.USE_ALL_HEIGHT | Field.FIELD_HCENTER | Field.FIELD_VCENTER ) {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(maxWidth, maxHeight);
int topSpace = (Display.getHeight() / 8);
setPadding(topSpace, 0, 0, 0);
}
};
vfmForCenterDisplay.setBackground(BackgroundFactory.createLinearGradientBackground(0x0099CCFF,
0x0099CCFF,0x00336699,0x00336699)
);
// Please verify this image src
borderBitmap = Bitmap.getBitmapResource("img/rounded-border.png");
VerticalFieldManager vfmBasicInfoWithBorder = new VerticalFieldManager() {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(maxWidth, maxHeight);
Background background = BackgroundFactory.createSolidBackground(Color.WHITE);
setBackground(background);
}
};
vfmBasicInfoWithBorder.setPadding(0, 0, 5, 5);
vfmBasicInfoWithBorder.add(lblMsgNameOfApp);
vfmBasicInfoWithBorder.add(new LabelField());
vfmBasicInfoWithBorder.add(lblMsgDesc);
vfmBasicInfoWithBorder.add(new LabelField());
vfmBasicInfoWithBorder.add(lblMsgWebLink);
HorizontalFieldManager hfm1 = new HorizontalFieldManager(Field.FIELD_HCENTER);
hfm1.add(btnSetting);
vfmBasicInfoWithBorder.setBorder(BorderFactory.createBitmapBorder(new XYEdges(12, 12, 12, 12), borderBitmap));
***String url ="http://ads.mp.mydas.mobi/getAd?apid=157899&auid=ddd25abbb993f79454b12827c803fbafab2ad89b";
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection(); conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
buff.append(IOUtilities.streamToBytes(in));
result = buff.toString();
}
else {
result = "Error in connection" + conn.getResponseCode();
((ButterflyScreen)screen).update(result);
}
catch (Exception ex) {ex.printStackTrace();
}
finally {
try{ if (in !=null)
{in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}***
VerticalFieldManager verticalFieldManager = new VerticalFieldManager(Field.FIELD_HCENTER|Field.FIELD_VCENTER);
add(verticalFieldManager);
VerticalFieldManager vfm = new VerticalFieldManager
(VerticalFieldManager.NO_VERTICAL_SCROLL
| VerticalFieldManager.NO_VERTICAL_SCROLLBAR
| VerticalFieldManager.USE_ALL_WIDTH);
HorizontalFieldManager hfm = new HorizontalFieldManager
(HorizontalFieldManager.FIELD_HCENTER
| HorizontalFieldManager.FIELD_VCENTER);
hfm.add(verticalFieldManager);
vfm.add(hfm);
add(vfm);
//vfmForCenterDisplay.add(new ButtonField("test"));
vfmForCenterDisplay.add(vfmBasicInfoWithBorder);
vfmForCenterDisplay.add(hfm1);
add(vfmForCenterDisplay);
}
**private void update(String string) {
// TODO Auto-generated method stub
VerticalFieldManager verticalFieldManager = new VerticalFieldManager(Field.FIELD_HCENTER|Field.FIELD_VCENTER);{
VerticalFieldManager vfm = new VerticalFieldManager
(VerticalFieldManager.NO_VERTICAL_SCROLL
| VerticalFieldManager.NO_VERTICAL_SCROLLBAR
| VerticalFieldManager.USE_ALL_WIDTH);
HorizontalFieldManager hfm = new HorizontalFieldManager
(HorizontalFieldManager.FIELD_HCENTER
| HorizontalFieldManager.FIELD_VCENTER);
hfm.add(verticalFieldManager);
vfm.add(hfm);
add(vfm);
}
}**
public boolean onClose()
{
setDirty(false);
return true;
}
}
I have place *** at place that am not sure about, I need your help with this please.

Related

Setting selected value in editfield?

I have made a custom auto suggest list.
I want to set the selcted value in edit field.
I am using this Place holder text on a AutoCompleteField in blackberry
CustomAutoCompleteField.js
package mypackage;
import net.rim.device.api.collection.util.BasicFilteredList;
import net.rim.device.api.collection.util.BasicFilteredListResult;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.AutoCompleteField;
import net.rim.device.api.ui.component.ListField;
class CustomAutoCompleteField extends AutoCompleteField {
private int yOffset = 0;
private int xOffset = 0;
public CustomAutoCompleteField(BasicFilteredList filteredList) {
super(filteredList);
}
protected void paint(Graphics g) {
super.paint(g);
if (xOffset == 0) {
// initialize text offsets once
xOffset = getEditField().getContentLeft();
yOffset = getEditField().getContentTop();
}
String text = getEditField().getText();
if (text == null || text.length() == 0) {
int oldColor = g.getColor();
g.setColor(Color.GRAY);
g.drawText("enter text", xOffset, yOffset);
g.setColor(oldColor);
}
}
public void onSelect(Object selection, int SELECT_TRACKWHEEL_CLICK) {
ListField _list = getListField();
if (_list.getSelectedIndex() > -1) {
final String selectedText = getEditField().getText();
if(selectedText!=null){
final BasicFilteredListResult result = (BasicFilteredListResult) selection;
Application.getApplication().invokeLater(new Runnable() {
public void run() {
selectedText.setText(result._object.toString());
}
});
// selectedText.setText(result._object.toString());
}
}
}
protected void sublayout(int maxWidth, int maxHeight) {
// TODO Auto-generated method stub
super.sublayout(250, 250);
}
}
myscreen.js
public final class MyScreen extends MainScreen
{
/**
* Creates a new MyScreen object
*/
public MyScreen()
{
// Set the displayed title of the screen
BasicFilteredList filterList = new BasicFilteredList();
String[] days = {"Monday(TAS)","Tuesday-(PAQ)","Wednesday-(MAN)",
"Thursday","Friday","Saturday","Sunday(I_)"};
filterList.addDataSet(1,days,"days",BasicFilteredList.COMPARISON_IGNORE_CASE);
HorizontalFieldManager hr =new HorizontalFieldManager();
LabelField userName= new LabelField("hjsdhas");
hr.add(userName);
CustomAutoCompleteField autoCompleteField = new CustomAutoCompleteField(filterList);
hr.add(autoCompleteField);
add(hr);
}
}
CustomAutoCompleteField.java is my custom java class and I call the class from myscreen.java class

Bitmap Image not displaying from a URL link Blackberry

For some reason my blackberry application crashes whenever i try to display a bitmap image from a URL using the internet.
I found the downloadImage() function very easy to understand and to follow compared to others on stackoverflow. The others didnt have any examples on how to implement their function. I have have tested the function downloadImage many times and all failed.
Please give explanation with code example. Thanks.
Anyway, The compiler stops at this point here:
g.drawBitmap(10, y + 6, 50, 50, imageBmp, 0, 0);
Here is the entire code:
package parsepack;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.ListField;
import net.rim.device.api.ui.component.ListFieldCallback;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.xml.parsers.DocumentBuilder;
import net.rim.device.api.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class xmlparsing extends UiApplication implements ListFieldCallback, FieldChangeListener
{
public static void main(String[] args) throws IOException
{
xmlparsing app = new xmlparsing();
app.enterEventDispatcher();
}
public long mycolor ;
Connection _connectionthread;
private static ListField _list;
private static Vector listElements = new Vector();
private static Vector listPrice = new Vector();
private static Vector listAbstract = new Vector();
private static Vector listIcon = new Vector();
private Vector listInfoVector = new Vector();
public MainScreen screen = new MainScreen();
Bitmap imageBmp = null;
VerticalFieldManager mainManager;
VerticalFieldManager subManager;
UiApplication ui = UiApplication.getUiApplication();
public xmlparsing() throws IOException
{
super();
pushScreen(screen);
final Bitmap backgroundBitmap = Bitmap.getBitmapResource("blackbackground.png");
mainManager = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL | Manager.NO_VERTICAL_SCROLLBAR )
{
public void paint(Graphics graphics)
{
graphics.drawBitmap(0, 0, Display.getWidth(),Display.getHeight(),backgroundBitmap, 0, 0);
super.paint(graphics);
}
};
subManager = new VerticalFieldManager(Manager.VERTICAL_SCROLL | Manager.VERTICAL_SCROLLBAR )
{
protected void sublayout( int maxWidth, int maxHeight )
{
int displayWidth = Display.getWidth();
int displayHeight = Display.getHeight();
super.sublayout( displayWidth, displayHeight);
setExtent( displayWidth, displayHeight);
}
};
screen.add(mainManager);
_list = new ListField()
{
public void paint(Graphics graphics)
{
graphics.setColor((int) mycolor);
super.paint(graphics);
}
protected boolean navigationClick(int status, int time)
{
try
{
//navigate here to another screen
ui.pushScreen(new ResultScreen());
}
catch(Exception e)
{
System.out.println("Exception:- : navigationClick() "+e.toString());
}
return true;
}
};
mycolor = 0x00FFFFFF;
_list.invalidate();
_list.setEmptyString("* Feeds Not Available *", DrawStyle.HCENTER);
_list.setRowHeight(70);
_list.setCallback(this);
mainManager.add(subManager);
listElements.removeAllElements();
listPrice.removeAllElements();
listAbstract.removeAllElements();
listIcon.removeAllElements();
_connectionthread = new Connection();
_connectionthread.start();
}
private class Connection extends Thread
{
public Connection()
{
super();
}
public void run() {
Document doc;
StreamConnection conn = null;
InputStream is = null;
try {
conn = (StreamConnection) Connector.open("http://imforchange.org/international-movement-for-change/testing/data.xml"+";deviceside=true");
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setIgnoringElementContentWhitespace(true);
docBuilderFactory.setCoalescing(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.isValidating();
is = conn.openInputStream();
doc = docBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList list1 = doc.getElementsByTagName("eventName");
for (int i = 0; i < list1.getLength(); i++) {
Node textNode = list1.item(i).getFirstChild();
listElements.addElement(textNode.getNodeValue());
}
NodeList list2 = doc.getElementsByTagName("eventPrice");
for (int i = 0; i < list2.getLength(); i++) {
Node textNode = list2.item(i).getFirstChild();
listPrice.addElement(textNode.getNodeValue());
}
NodeList list3 = doc.getElementsByTagName("eventAbstract");
for (int i = 0; i < list3.getLength(); i++) {
Node textNode = list3.item(i).getFirstChild();
listAbstract.addElement(textNode.getNodeValue());
}
NodeList list4 = doc.getElementsByTagName("eventIcon");
for (int i = 0; i < list4.getLength(); i++) {
Node textNode = list4.item(i).getFirstChild();
listIcon.addElement(textNode.getNodeValue());
}
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if (is != null) {
try { is.close();
} catch (IOException ignored) {}
} if (conn != null) {
try { conn.close(); }
catch (IOException ignored) {}
} } UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_list.setSize(listElements.size());
subManager.add(_list);
screen.invalidate();
}
});
}
}
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
String text = (String)listElements.elementAt(index);
String price = (String)listPrice.elementAt(index);
String textAbstract = (String)listAbstract.elementAt(index);
int yPos = 0+y;
g.drawLine(0, yPos, w, yPos);
g.drawText(text, 5, 15+y, 0, w);
g.drawText("$"+price, 5, 15+y, DrawStyle.RIGHT, w-7);
g.drawText(textAbstract, 5, 40+y, 0, w);
// image to display
String imageUrl = (String)listIcon.elementAt(index);
imageBmp = downloadImage(imageUrl);
g.drawBitmap(10, y + 6, 50, 50, imageBmp, 0, 0);
}
public Object get(ListField list, int index)
{
return listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
/*Regarding the warning about insert(), that's just because you're not using it anywhere.
* It look like you've added that method to allow code outside the xmlparsing class to
* be able to insert items into the list. Maybe that's what you want, but you just
* haven't yet written the other code to use that method. I see you having at least a few choices:
*/
public void insert(String toInsert, int index) {
listElements.addElement(toInsert);
}
public void fieldChanged(Field field, int context) {
}
public static Bitmap downloadImage(String url)
{
InputStream iStream = null;
EncodedImage bitmap;
HttpConnection httpConnection = null;
try
{
httpConnection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
httpConnection.setRequestMethod(HttpConnection.GET);
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpConnection.HTTP_OK) {
iStream = httpConnection.openInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
int len = 0, imageSize = 0;
while (-1 != (len = iStream.read(buffer))) {
byteArrayOutputStream.write(buffer);
imageSize += len;
}
byteArrayOutputStream.flush();
byte[] imageData = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
bitmap = EncodedImage.createEncodedImage(imageData, 0, imageSize);
Bitmap bmp = bitmap.getBitmap();
return bmp;
}
}
catch (Exception e)
{
}
return null;
}
}
If you want to Display an Image on BlackBerry Screen from a WebURL. First you need to get a BitMap refrence.
You can Check the below Code:
The Code will take input as WebURL and It will return a Bitmap reference.
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
public class GetImage {
public static Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
// System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
}
And Finally,If you want to Display the Image on BlackBerry Screen, use the below method
g.drawBitmap(xpos, ypos, w, h, image, 0, 0);//pass the Bitmap reference Here
I see your method: downloadImage(String url). Its a lengthy code. No need that much;
Try this method:
public static Bitmap getImage(String url)
{
Bitmap image;
HttpConnection connection=null;
InputStream is=null;
try
{
connection=(HttpConnection)Connector.open(Utility.escapeHTML(url));
int response=connection.getResponseCode();
if(response==HttpConnection.HTTP_OK)
{
is=connection.openInputStream();
byte[] data=IOUtilities.streamToBytes(is);
connection.close();
image=Bitmap.createBitmapFromBytes(data,0,data.length,1);
}
else
{
image=ResourceList.dummyBit;//noimage.png
}
}
catch (Exception e)
{
image=ResourceList.dummyBit;//noimage.png
}
finally
{
try
{
if (is != null)
is.close();
if (connection != null)
connection.close();
}
catch (Exception e) {}
}
return image;
}
try this and let me know.
the escapeHTML(String str) method is below:
public static String escapeHTML(String s)
{
StringBuffer sb = new StringBuffer();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
switch (c) {
case ' ': sb.append("%20"); break;
default: sb.append(c); break;
}
}
return sb.toString();
}

wrapContent of Custom HorizontalFieldManager Blackberry

I am developing an app in which I need to display products in an expandable list. So I have tried an example which was given in stackoverflow... So, it is working good, but my problem is the divider that will not wrap (expand) based on content expanding, like in screen ...
as you can see, in the screen the date2 field is not displayed properly ..
for that, is there any scrolling facility or can this expand automatically?
Here is my code
import net.rim.device.api.system.Bitmap;
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.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.Touchscreen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.NullField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
class UiMainscreen extends MainScreen implements FieldChangeListener
{
private CustomListField cu_field[];
private Bitmap image=null;
int size=8;
public UiMainscreen() {
VerticalFieldManager vmanager=new VerticalFieldManager(VERTICAL_SCROLL|VERTICAL_SCROLLBAR){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(),Display.getHeight());
}
};
cu_field=new CustomListField[size];
for(int i=0;i<size;i++){
image=Bitmap.getBitmapResource("sample_"+i+".jpg");
cu_field[i]=new CustomListField("BlackBerry models that had a built-in mobile phone, were the first models that natively ran Java, and transmitted data over the normal 2G cellular network. RIM began to advertise these devices as email-capable mobile phones rather than as 2-way pagers.", image, "jan2011", 100, 100,Color.LIGHTGREEN);
cu_field[i].setChangeListener(this);
vmanager.add(new SeparatorField());
vmanager.add(cu_field[i]);
}
add(vmanager);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
for(int i=0;i<size;i++){
if(field==cu_field[i]){
final int k=i;
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("You click on Item No "+k);
}
});
}
}
}
}
class CustomListField extends HorizontalFieldManager{
private Bitmap scale_image;
private int width=0;
private int height=0;
private int background_color=0;
private BitmapField bitmap_field;
private boolean flag=false;
Bitmap logingBg;
public CustomListField(String title, Bitmap image, String date,int image_width,int image_height,int background_color){
super(NO_HORIZONTAL_SCROLL|USE_ALL_WIDTH);
this.background_color=background_color;
width=image_width;
height=image_width;
if(image!=null){
scale_image=new Bitmap(image_width, image_height);
image.scaleInto(scale_image, Bitmap.FILTER_LANCZOS);
bitmap_field=new BitmapField(scale_image);
flag=false;
bitmap_field.setMargin(5, 5, 5, 5);
add(bitmap_field);
}
VerticalFieldManager vmanager=new VerticalFieldManager(USE_ALL_WIDTH|Field.FIELD_VCENTER){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(), height);
setExtent(Display.getWidth(), height);
}
};
///////////////////////////////////////////
/* Bitmap logingBg = Bitmap.getBitmapResource("myorderdatebackground.png");
HorizontalFieldManager hfm = new HorizontalFieldManager(USE_ALL_WIDTH);
HorizontalFieldManager hfm2 = new HorizontalFieldManager(Field.FIELD_HCENTER);
ButtonField btnext = new ButtonField("btn");
CustomButtonField btnSignIn = new CustomButtonField(0, "", logingBg,
logingBg, Field.FOCUSABLE, Color.WHITE);
hfm2.add(btnext);
hfm.add(btnSignIn);
hfm.add(hfm2);
vmanager.add(hfm);*/
logingBg = Bitmap.getBitmapResource("myorderdatebackground.png");
HorizontalFieldManager HFM = new HorizontalFieldManager(USE_ALL_WIDTH) {
public void paint(Graphics g) {
//g.setBackgroundColor(Color.BLUE);
g.clear();
g.drawBitmap(0, 0, Display.getWidth(),
logingBg.getHeight(), logingBg, 0, 0);
super.paint(g);
}
};
HorizontalFieldManager lableRegistHFM = new HorizontalFieldManager(
FIELD_VCENTER);
LabelField RegistrationLbl = new LabelField("My Orders",Field.FIELD_HCENTER);
FontFamily fontFamily[] = FontFamily.getFontFamilies();
Font font11 = fontFamily[1].getFont(FontFamily.CBTF_FONT, 12);
font11 = fontFamily[1].getFont(Font.BOLD, 18);
RegistrationLbl.setFont(font11);
RegistrationLbl.setMargin(0, 0, 0, (Display.getWidth() / 3));
lableRegistHFM.add(RegistrationLbl);
HFM.add(lableRegistHFM);
vmanager.add(HFM);
/**************************************************************/
LabelField title_lbl=new LabelField("Title: "+title,Field.NON_FOCUSABLE|DrawStyle.ELLIPSIS);
vmanager.add(title_lbl);
LabelField date_lbl=new LabelField("Date: "+date,Field.NON_FOCUSABLE);
vmanager.add(date_lbl);
LabelField date_lbl3=new LabelField("Date2: "+date,Field.NON_FOCUSABLE);
vmanager.add(date_lbl3);
LabelField date_lbl4=new LabelField("Date2: "+date,Field.NON_FOCUSABLE);
vmanager.add(date_lbl4);
Font fon=title_lbl.getFont();
int title_height=fon.getHeight();
Font font=date_lbl.getFont();
int date_height=font.getHeight();
int pad=title_height+date_height;
title_lbl.setPadding((height-pad)/2, 0, 0, 0);
add(vmanager);
add(new NullField(FOCUSABLE));
}
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(), height);
setExtent(Display.getWidth(), height);
}
protected void paint(Graphics graphics) {
if(flag)
graphics.setBackgroundColor(background_color);
graphics.clear();
super.paint(graphics);
}
protected void onFocus(int direction) {
super.onFocus(direction);
flag=true;
invalidate();
}
protected void onUnfocus() {
invalidate();
flag=false;
}
protected boolean navigationClick(int status, int time) {
if(Touchscreen.isSupported()){
return false;
}else{
fieldChangeNotify(1);
return true;
}
}
protected boolean touchEvent(TouchEvent message)
{
if (TouchEvent.CLICK == message.getEvent())
{
FieldChangeListener listener = getChangeListener();
if (null != listener)
this.setFocus();
listener.fieldChanged(this, 1);
}
return super.touchEvent(message);
}
}
The issue is here:
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(), height);
setExtent(Display.getWidth(), height);
}
You're giving manager height less that it needs for content (only image_width).
Also here is possible error:
width=image_width;
height=image_width;
You should use image_height for the height.
And sure you could use scrolling for VerticalManager - add style VERTICAL_SCROLL to constructor. But as user I will find the User Experience (UX) strange in this case.

Multiline line text box with border in Blackberry

I am new to blackberry,This is my first question.I am doing one sample app for this i require multi line textbox.i googled about this,I found the code below.
VerticalFieldManager vfm =new VerticalFieldManager(Manager.VERTICAL_SCROLL)
{
public void paint(Graphics g)
{
g.drawRoundRect(0, 0,getWidth(), getHeight(),12,12);
super.paint(g);
}
public void sublayout(int width, int height)
{
if (managerWidth == 0) {
managerWidth = width;
}
if (managerHeight == 0) {
managerHeight = height;
}
super.sublayout(managerWidth, managerHeight);
setExtent(managerWidth,managerHeight);
}
};
editField = new EditField(){
public void paint(Graphics g) {
getManager().invalidate();
super.paint(g);
}
};
vfm.add(editField);
vfm.setBackground(BackgroundFactory.createSolidBackground(Color.WHITE));
add(vfm);
It works fine,if the text is less than Field height,if the text is greater than the field height.The text is crossing the border.How i fix that problem.Please help me.
You need to implement your own custom field.
Documentation can be found here: "Create a custom field"
You can use EditField from Blackberry APIs and use:
yourEditField.setBorder(yourBorder);
You will have then an edit field with a border and which accepts several lines
package nativeapp;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.Dialog;
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;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;
import net.rim.device.api.ui.decor.Border;
import net.rim.device.api.ui.decor.BorderFactory;
public class LoginScreen extends MainScreen {
/**
* Login page
*/
private ButtonField btnLogin;
//private EditField txtUserID;
CustomTextBox txtUserID;
CustomTextBox txtPassword;
// private PasswordEditField txtPassword;
private CheckboxField Chkbox;
private LabelField RememberMe;
public LoginScreen() {
super(NO_VERTICAL_SCROLL);
txtUserID = new CustomTextBox() {
protected void paint(Graphics g) {
// Border roundedBorder = BorderFactory
// .createRoundedBorder(new XYEdges(9, 9, 9, 9),
// Color.GRAY, Border.STYLE_SOLID);
// setBorder(roundedBorder);
// setBackground(BackgroundFactory
// .createSolidBackground(Color.WHITE));
if (getText().length() == 0) {
g.setColor(Color.GRAY);
g.drawText("UserName", 0, 0);
}
g.setColor(Color.BLACK);
//g.drawRect(0, 0, (int) (Display.getWidth() / 1.5),
//txtUserID.getHeight()/* (int)(Display.getHeight()/9) */);
super.paint(g);
}
};
txtPassword = new CustomTextBox() {
protected void paint(Graphics g) {
Border roundedBorder = BorderFactory
.createRoundedBorder(new XYEdges(9, 9, 9, 9),
Color.GRAY, Border.STYLE_SOLID);
setBorder(roundedBorder);
setBackground(BackgroundFactory
.createSolidBackground(Color.WHITE));
if (getText().length() == 0) {
g.setColor(Color.GRAY);
g.drawText("txtPassword", 0, 0);
}
g.setColor(Color.BLACK);
super.paint(g);
}
};
// btnLogin = new ButtonField("SignIn");
btnLogin = new ButtonField("Sign In", Field.FIELD_HCENTER);
Chkbox = new CheckboxField();
// Chkbox.setMargin(0, 0, 0, 30);
RememberMe = new LabelField("Remember Me");
// RememberMe.setMargin(10, 0, 0, 0);
FieldChangeListener login = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
String uname = txtUserID.getText().toString().trim();
String pword = txtPassword.getText().toString().trim();
if (!uname.equalsIgnoreCase("")
&& !uname.equalsIgnoreCase(null)
&& !pword.equalsIgnoreCase("")
&& !pword.equalsIgnoreCase(null)) {
boolean lgnStatus = (new httpClient()).loginStatus(uname,
pword, DataURL.smartURLloginchk);
if (lgnStatus) {
PersistentsStore ps = new PersistentsStore();
ps.setObject(DataURL.UserName, uname);
ps.setObject(DataURL.PassWord, pword);
UiApplication.getUiApplication().popScreen(
LoginScreen.this);
UiApplication.getUiApplication().pushScreen(
new WelcomeScreen());
} else {
Dialog.inform("Invalid UserID or Password");
}
} else {
Dialog.inform("UserID and Password shouldnot be Empty");
}
}
};
FieldChangeListener cancel = new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
}
};
btnLogin.setChangeListener(login);
// btnCancel.setChangeListener(cancel);
setLoginScreen();
}
private void setLoginScreen() {
VerticalFieldManager vfmForCenterDisplay = new VerticalFieldManager(
Field.FIELD_HCENTER | Field.FIELD_VCENTER | Field.USE_ALL_WIDTH
| Field.USE_ALL_HEIGHT) {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(maxWidth, maxHeight);
}
};
Background background = BackgroundFactory.createBitmapBackground(Bitmap
.getBitmapResource("bground.png"));
vfmForCenterDisplay.setBackground(background);
int topSpace = (Display.getHeight() / 4);
vfmForCenterDisplay.setPadding(topSpace, 0, 0, 0);
VerticalFieldManager vfmBasicInfoWithBorder1 = new VerticalFieldManager(
FIELD_HCENTER | FIELD_VCENTER) {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(250, 95);
}
};
BitmapField bitmapField = new BitmapField(
Bitmap.getBitmapResource("loginbg_01.png")) {
protected void layout(int width, int height) {
setExtent(250, 95);
}
};
vfmBasicInfoWithBorder1.add(bitmapField);
VerticalFieldManager vfmBasicInfoWithBorder2 = new VerticalFieldManager(
FIELD_HCENTER | FIELD_VCENTER) {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(250, 95);
}
};
vfmBasicInfoWithBorder2.setBackground(BackgroundFactory
.createBitmapBackground(Bitmap
.getBitmapResource("loginbg_02.jpg")));
VerticalFieldManager vfmBasicInfoWithBorder3 = new VerticalFieldManager(
FIELD_HCENTER | FIELD_VCENTER) {
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(250, 95);
setExtent(250, 95);
}
};
vfmBasicInfoWithBorder3.setBackground(BackgroundFactory
.createBitmapBackground(Bitmap
.getBitmapResource("loginbg_03.png")));
vfmBasicInfoWithBorder3.add(btnLogin);
// btnLogin.setMargin(0, 0, 0, 0);
// HorizontalFieldManager hfm1 = new HorizontalFieldManager(
// Field.FIELD_HCENTER);
HorizontalFieldManager hfm2 = new HorizontalFieldManager(
Field.FIELD_VCENTER);
hfm2.add(txtUserID);
// txtUserID.setMargin(0, 0, 0, 0);
HorizontalFieldManager hfm3 = new HorizontalFieldManager(FIELD_HCENTER
& FIELD_VCENTER);
hfm3.add(txtPassword);
// txtPassword.setMargin(0, 0, 0, 10);
HorizontalFieldManager hfm4 = new HorizontalFieldManager(
Field.FIELD_HCENTER);
hfm4.add(Chkbox);
Chkbox.setMargin(0, 0, 0, 10);
hfm4.add(RememberMe);
RememberMe.setMargin(0, 0, 0, 10);
// HorizontalFieldManager hfm5 = new
// HorizontalFieldManager(FIELD_HCENTER
// & FIELD_VCENTER) {
// protected void sublayout(int maxWidth, int maxHeight) {
// super.sublayout(250, 95);
// }
// };
// hfm5.add(btnLogin);
// btnLogin.setMargin(0, 0, 0, 0);
// hfm5.add(btnCancel);
// hfm5.setPadding(new XYEdges(0, 0, 0, ((250 - (70 + 75)) / 2)));
// btnCancel.setMargin(0, 0, 0, 15);
// vfmBasicInfoWithBorder1.add(hfm1);
vfmBasicInfoWithBorder2.add(hfm2);
vfmBasicInfoWithBorder2.add(hfm3);
vfmBasicInfoWithBorder3.add(hfm4);
// vfmBasicInfoWithBorder3.add(hfm5);
vfmForCenterDisplay.add(vfmBasicInfoWithBorder1);
vfmForCenterDisplay.add(vfmBasicInfoWithBorder2);
vfmForCenterDisplay.add(vfmBasicInfoWithBorder3);
add(vfmForCenterDisplay);
}
}

Splash screen with progress indicator on Blackberry

I am trying to design a splash screen with an activity indicator on it.
I am successfully creating a splash screen but my indicator is not being added to it,
it is being hidden below the image while i am setting its layout.
How can I fix this?
Here is my code:
package mypackage;
import java.util.Timer;
import java.util.TimerTask;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.progressindicator.ActivityIndicatorController;
import net.rim.device.api.ui.component.progressindicator.ActivityIndicatorModel;
import net.rim.device.api.ui.component.progressindicator.ActivityIndicatorView;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
//import net.rim.device.api.ui.extension.container.EyelidFieldManager;
public final class SplashScreen extends SplashScreenPage
{
public SplashScreen()
{
super(Bitmap.getBitmapResource("splash-blackberry.png"),2);
}
}
class SplashScreenPage extends MainScreen
{
VerticalFieldManager vfm= new VerticalFieldManager(Field.FIELD_VCENTER);
HorizontalFieldManager hfm = new HorizontalFieldManager(Field.FIELD_VCENTER)
{
protected void sublayout( int maxWidth, int maxHeight )
{
super.sublayout(360,60);
setExtent(360, 60);
Field field = getField(0);
layoutChild(field,140, 60);
setPositionChild(field, 100,200);
}
public void paint(Graphics graphics)
{
//Draw the background image and then call paint.
// super.paint(graphics);
//graphics.clear();
// graphics.setBackgroundColor(0x000000);
//graphics.drawBitmap(0, 0, 360, 480, popup, 0, 0);
// super.paint(graphics);
// graphics.clear();
// graphics.drawBitmap(0, 0, 360, 480, popup, 0, 0);
}
};
ActivityIndicatorView view = new ActivityIndicatorView(Field.USE_ALL_WIDTH);
ActivityIndicatorModel model = new ActivityIndicatorModel();
ActivityIndicatorController controller = new ActivityIndicatorController();
boolean notlogged = false;
Bitmap popup;
SplashScreenPage screen1 = this;
private Timer splashTimer = new Timer();
private TimerTask splashTask;
int count = 0;
int screenWidth = Display.getWidth();
int screenHeight = Display.getHeight();
int yCoord;
int xCoord;
boolean showSplash = true;
boolean splashDisplayed = false;
//SplashScreen page is here
public SplashScreenPage(Bitmap popup, final int seconds)
{
view.setController(controller);
view.setModel(model);
view.setLabel("Loading");
controller.setModel(model);
controller.setView(view);
model.setController(controller);
Bitmap bitmap = Bitmap.getBitmapResource("images.jpeg");
view.createActivityImageField(bitmap, 5, Field.FIELD_BOTTOM);
// add(view);
add(hfm);
hfm.add(view);
// add(vfm);
// vfm.add(Bitmap.getBitmapResource("splash-blackberry.png"));
this.popup = popup;
xCoord = (screenWidth - popup.getWidth()) / 2;
yCoord = (screenHeight - popup.getHeight()) / 2;
splashTask = new TimerTask() {
public void run() {
if (showSplash && !splashDisplayed) {
count++;
if (count == seconds * 15) {
showSplash = false;
splashDisplayed = true;
splashTimer.cancel();
invalidate();
synchronized (Application.getEventLock()){
UiApplication.getUiApplication().pushScreen(new secondscreen());
notlogged = true;
}
}
}
}
};
splashTimer.scheduleAtFixedRate(splashTask, 100, 100);
}
protected void paint(Graphics graphics) {
super.paint(graphics);
if (showSplash && !splashDisplayed) {
graphics.drawBitmap(xCoord, yCoord, popup.getWidth(), popup.getHeight(), popup, 0, 0);
// super.paint(graphics);
// graphics.clear();
}
}
protected void onUiEngineAttached(boolean attached) {
showSplash = true;
invalidate();
super.onUiEngineAttached(attached);
}
protected boolean navigationMovement(int dx, int dy, int status, int time) {
return DismissSplash();
}
protected boolean navigationClick(int status, int time) {
return DismissSplash();
}
protected boolean keyChar(char c, int status, int time) {
return DismissSplash();
}
private boolean DismissSplash() {
if (showSplash) {
showSplash = false;
splashDisplayed = true;
invalidate();
return true;
}else{
return false;
}
}
public void onExposed() {
if( notlogged)
UiApplication.getUiApplication().popScreen(this);
}
}
In your HorizontalFieldManager that you are adding view to, you need to make sure you are calling super.paint() because it called subpaint() which will tell its child Fields (view in this case) to paint themselves. I see that you have it commented out, so you've probably been messing with that. Also, be sure that you do your background painting before you call super.paint() so you don't cover up the ActivityIndicatorView with your own painting.
Would it be possible for you to go through and clean up the code (removing the commented out code that isn't important) to a point where you would expect it to work so it is a littler easier to distinguish between "trying anything you can" code and "working" code.

Resources