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();
}
Related
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.
I am new in BB trying to parse Json file and just want to print the Json responce in a Dialog. But it raises an error regarding No Application Instance and is also getting IllegalStateException. I use GET url method for it.
I Have also add permission in UiApplication like ..
UIApplicationScreen
public static void main(String[] args) {
ApplicationPermissions permRequest = ApplicationPermissionsManager.getInstance().getApplicationPermissions();
permRequest = new ApplicationPermissions();
permRequest.addPermission( ApplicationPermissions.PERMISSION_INTERNET );
ApplicationPermissionsManager.getInstance().invokePermissionsRequest( permRequest );
UiFunApplication app = new UiFunApplication();
app.enterEventDispatcher();
Here is MainScreen Code....
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 net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONArray;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONObject;
public class UiMainscreen extends MainScreen {
public UiMainscreen() {
Dialog.alert("asdasd");
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
// String url = "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
String url = "http://docs.blackberry.com/sampledata.json";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
Dialog.alert("response is ::"+response);
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
}
}
}
Update::
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 net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
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.container.MainScreen;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONArray;
import com.rim.samples.jsonme.cakeorder.org.json.me.JSONObject;
public class UiMainscreen extends MainScreen implements FieldChangeListener {
public UiMainscreen() {
ButtonField loginButton;
loginButton = new ButtonField("Go", ButtonField.CONSUME_CLICK);
loginButton.setChangeListener(this);
add(loginButton);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if (field instanceof ButtonField) {
Dialog.alert("Message");
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
// String url =
// "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
String url = "http://docs.blackberry.com/sampledata.json";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
Dialog.alert("response is ::" + response);
/*
* JSONObject resObject = new JSONObject(response); String
* key = resObject.getString("vehicleType");
*
* Vector resultsVector = new Vector(); JSONArray jsonArray
* = resObject.getJSONArray("name"); if (jsonArray.length()
* > 0) { for (int i = 0; i < jsonArray.length();i++) {
* Vector elementsVector = new Vector(); JSONObject jsonObj
* = jsonArray.getJSONObject(i);
* elementsVector.addElement(jsonObj
* .getString("experiencePoints"));
* elementsVector.addElement
* (jsonObj.getString("Insert Json Array Element Key2"));
* resultsVector.addElement(elementsVector); } }
*/
}
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Dialog.alert(e.getMessage());
}
}
}
}
}
}
Try this code -
final ButtonField b=new ButtonField("JSON");
add(b);
FieldChangeListener listener=new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
if(field==b){
try {
String httpURL = "http://docs.blackberry.com/sampledata.json";
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
Dialog.alert(responce);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
b.setChangeListener(listener);
I am trying to save a path to an image in the persistent store to show the image when a user chooses a specific product from a history list(one image per product, taken by the user). Now the problem I am having is that when I load the app to the phone for the first time and try adding an entry to the persistent store, it throws an error a bit after and the app freezes. However when I come back, and add an image again, it works just fine and the images always load when I choose each specific product.
This is leading me to believe that the culprit is the first store8.commit() that I'm doing, for some reason it throws an exception : No Stack Trace, when debugging. Here is my code:
public class Storage extends Application {
private static final long PERSISTENT_KEY8 = 0x2c4c45c139ee9728L;
static PersistentObject store8 = PersistentStore.getPersistentObject(PERSISTENT_KEY8);
private static Vector pics;
/**
* Picture Section ***********************************************************
*/
public static void savePicture(){
store8.setContents(new Vector());
store8.commit();
if(pics == null){
pics = new Vector();
}
synchronized(store8) {
store8.setContents(pics);
store8.commit();
}
}
public static String getPicture(String productName){
if(pics.size()==0){
return "";
}else{
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
return product.getPic();
}
}
return "";
}
}
public static void removePicture(String productName){
if(pics.size()==0){
return;
}else{
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
pics.removeElementAt(i);
}
}
}
}
public static void loadPicture(){
pics = (Vector)store8.getContents();
if(pics == null){
pics = new Vector();
}
}
public static void setPicture(Pics pro){
if(pics.size()!=0){
for(int j = 0; j< pics.size() ; j++){
Pics product = (Pics)pics.elementAt(j);
if(pro.getProductName().equals(product.getProductName())){
pics.removeElementAt(j);
}
}
}
pics.addElement(pro);
}
}
So that is the class that contains my methods to save the image. Now for the other class where I am manipulating it:
public class ProductImage extends MainScreen implements FieldChangeListener, AppLaunchResource {
private ImageButtonField logo;
private ButtonField newImage, chooseExisting;
public static BitmapField takenPicture;
//public static String picPath ="";
private String currentPicture = "";
private String currentProduct ="";
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
this.setTitle(new LabelField("Add An Image", Field.FIELD_HCENTER));
if(ToolbarManager.isToolbarSupported())
{
Toolbar tb = new Toolbar();
setToolbar(tb.createToolBar());
}
else{
Toolbar tb = new Toolbar();
add(tb.createNavBar());
}
try{
Storage.loadPicture();
}catch(NullPointerException e){
e.printStackTrace();
}
newImage = new ButtonField("Take Photo", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) (net.rim.device.api.system.Display.getWidth());
}
};
chooseExisting= new ButtonField("Change Image", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) (net.rim.device.api.system.Display.getWidth());
}
};
newImage.setChangeListener(this);
chooseExisting.setChangeListener(this);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
VerticalFieldManager vfMain = new VerticalFieldManager();
vfMain.add(new SeparatorField());
vfMain.add(newImage);
vfMain.add(chooseExisting);
vfMain.add(takenPicture);
add(vfMain);
currentPicture = Storage.getPicture(currentProduct);
showPicture();
}
public void choosePicture(){
String imageExtensions[] = {"jpg", "jpeg",
"bmp", "png", "gif"};
FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
fps.pickFile();
String theFile = fps.getFile();
UiApplication.getUiApplication().pushScreen(fps);
if (theFile == null)
{
Dialog.alert("Screen was dismissed. No file was selected.");
}
else
{
try{
String path= "file:///" + theFile;
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
if(Display.getHeight()>Display.getWidth()){
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
else{
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP(Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
UiApplication.getUiApplication().popScreen(fps);
takenPicture.setBitmap(eImage.getBitmap());
Storage.setPicture(new Pics(currentProduct, path));
try{
Storage.savePicture();
}catch(Exception e){
e.printStackTrace();
}
}
catch(Exception e){
}
Dialog.alert("Picture Saved");
}
}
public void showPicture(){
if(currentPicture != ""){
try{
String path= currentPicture;
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
if(Display.getHeight()>Display.getWidth()){
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
else{
int scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()),
Fixed32.toFP(Display.getWidth()));
int scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()),
Fixed32.toFP(Display.getHeight()));
eImage=eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
takenPicture.setBitmap(eImage.getBitmap());
}
catch(Exception e){
}
}
}
public void fieldChanged(Field field, int context) {
if(field == logo){
}
else if(field == newImage){
takePicture();
}
else if(field == chooseExisting){
choosePicture();
}
}
}
I removed many parts of this class, sorry if it is long, there are basically 4 Storage method calls in this code and I believe they are all in the right place.. but again im having the problem on first load, not afterwards.
Can anyone see what Im doing wrong here? I have had this problem for a week
Thanks for any help provided!
Try something like this:
public class Storage extends Application{
private static final long PERSISTENT_KEY8 = 0x2c4c45c139ee9728L;
static PersistentObject store8 = null;
private static Vector pics = null;
static{
store8 = PersistentStore.getPersistentObject(PERSISTENT_KEY8)
pics = (Vector)store8.getContents();
if(pics == null){
pics = new Vector();
store8.setContents(pics);
store8.commit();
}
}
public static void savePicture(){
try{
synchronized(store8){
store8.setContents(pics);
store8.commit();
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static int findPicture(String productName){
for(int i = 0; i < pics.size(); i++){
Pics product = (Pics)pics.elementAt(i);
if(product.getProductName().equals(productName)){
return i;
}
}
return -1;
}
public static String getPicture(String productName){
int idx = findPicture(productName);
if(idx != -1){
return ((Pics)pics.elementAt(idx)).getPic();
}
return "";
}
public static void removePicture(String productName){
int idx = findPicture(productName);
if(idx != -1){
pics.removeElementAt(idx);
}
}
public static void setPicture(Pics pro){
removePicture(pro.getProductName());
pics.addElement(pro);
}
}
.
public class ProductImage extends MainScreen implements FieldChangeListener, AppLaunchResource {
private ImageButtonField logo;
private ButtonField newImage, chooseExisting;
public static BitmapField takenPicture;
//public static String picPath ="";
private String currentPicture = "";
private String currentProduct = "";
public ProductImage(String productName){
super(VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
currentProduct = productName;
createGUI();
}
public void createGUI(){
deleteAll();
setTitle(new LabelField("Add An Image", Field.FIELD_HCENTER));
Toolbar tb = new Toolbar();
if(ToolbarManager.isToolbarSupported()){
setToolbar(tb.createToolBar());
}
else{
add(tb.createNavBar());
}
newImage = new ButtonField("Take Photo", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) Display.getWidth();
}
};
chooseExisting = new ButtonField("Change Image", ButtonField.CONSUME_CLICK){
public int getPreferredWidth() {
return (int) Display.getWidth();
}
};
newImage.setChangeListener(this);
chooseExisting.setChangeListener(this);
EncodedImage enc = EncodedImage.getEncodedImageResource("camera.png");
EncodedImage sizeEnc = ImageResizer.sizeImage(enc, Display.getHeight(), Display.getHeight());
takenPicture = new BitmapField(enc.getBitmap());
VerticalFieldManager vfMain = new VerticalFieldManager();
vfMain.add(new SeparatorField());
vfMain.add(newImage);
vfMain.add(chooseExisting);
vfMain.add(takenPicture);
add(vfMain);
currentPicture = Storage.getPicture(currentProduct);
showPicture();
}
public void choosePicture(){
String imageExtensions[] = {"jpg", "jpeg", "bmp", "png", "gif"};
FileSelectorPopupScreen fps = new FileSelectorPopupScreen(null, imageExtensions);
fps.pickFile();
String theFile = fps.getFile();
if (theFile == null){
Dialog.alert("Screen was dismissed. No file was selected.");
return;
}
EncodedImage eImage = loadImage("file:///" + theFile);
if(eImage != null){
takenPicture.setBitmap(eImage.getBitmap());
Storage.setPicture(new Pics(currentProduct, path));
Storage.savePicture();
Dialog.alert("Picture Saved");
}
}
private EncodedImage loadImage(String path){
try{
byte[] data = getData(path);
//Encode and Resize image
EncodedImage eImage = EncodedImage.createEncodedImage(data,0,data.length);
int scaleFactorX, scaleFactorY;
if(Display.getHeight()>Display.getWidth()){
scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(Display.getWidth()));
scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP((Display.getWidth()*Display.getWidth())/Display.getHeight()));
}
else{
scaleFactorX = Fixed32.div(Fixed32.toFP(eImage.getWidth()), Fixed32.toFP(Display.getWidth()));
scaleFactorY = Fixed32.div(Fixed32.toFP(eImage.getHeight()), Fixed32.toFP(Display.getHeight()));
}
return eImage.scaleImage32(scaleFactorX, scaleFactorY);
}
catch (Exception e){
return null;
}
}
public void showPicture(){
if(currentPicture != ""){
EncodedImage eImage = loadImage(currentPicture);
if (eImage != null){
takenPicture.setBitmap(eImage.getBitmap());
}
}
}
public void fieldChanged(Field field, int context){
if(field == logo){
}
else if(field == newImage){
takePicture();
}
else if(field == chooseExisting){
choosePicture();
}
}
}
My XML is in following format
<users>
<user uid="1" dispname ="Yogesh C" statid="1" statmsg = "Busy">Yogesh Chaudhari</user>
<user uid="2" dispname ="Sameer S" statid="2" statmsg = "Available">Yogesh Chaudhari</user>
</users>
In my BlackBerry app, I want to change the value of a particualar attribute, such as statmsg for uid 2. Is it possible to do this using a SAX parser? My aim is to update the XML and restore it.
I used the following code for parsing my XML using SAX:
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import net.rim.device.api.ui.UiApplication;
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;
public class SaxParseUrl extends UiApplication {
public SaxParseUrl() {
pushScreen(new Pars());
}
public static void main(String[] args) {
SaxParseUrl app = new SaxParseUrl();
app.enterEventDispatcher();
}
}
class Pars extends MainScreen implements ContentHandler
{
boolean name;
Pars() {
try {
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setContentHandler(this);
FileConnection conn = (FileConnection)Connector.open("file:///store/home/user/employee.xml");
InputStream is = conn.openDataInputStream();
InputSource iss = new InputSource(is);
parser.parse(iss);
} catch (Exception e) {
debug("file:///store/home/user/SAXParser.txt","Exception in pars() :"+e);
}
}
public void startElement(String nsURI, String strippedName, String tagName,
Attributes attributes) throws SAXException {
try {
debug("file:///store/home/user/SAXParser.txt","startElement");
if (tagName.equalsIgnoreCase("user"))
{
debug("file:///store/home/user/SAXParser.txt","Inside startElement");
name = true;
String uid = attributes.getValue("uid");
String dispname = attributes.getValue("dispname");
String statid = attributes.getValue("statid");
String statmsg = attributes.getValue("statmsg");
attributes.
//LabelField lb = new LabelField(uid+"==>"+dispname+"==>"+statid+"==>"+statmsg);
LabelField lb = new LabelField("uid ==>"+uid+"\ndispname==>"+dispname+"\nstatid==>"+statid+"\nstatmsg==>"+statmsg);
add(lb);
}
} catch (Exception e) {
System.out.println(e);
}
}
public void characters(char[] ch, int start, int length) {
debug("file:///store/home/user/SAXParser.txt","characters");
if (name) {
try {
System.out.println("Title: " + new String(ch, start, length));
LabelField lb=new LabelField(""+ new String(ch, start, length));
HorizontalFieldManager sr=new HorizontalFieldManager();
sr.add(lb);
add(sr);
//v_cid.addElement(new String(ch, start, length));
//System.out.println("the elements of vector: " + v_cid);
// name = false;
//Enumeration e = v_cid.elements();
//System.out.println("The elements of vector: " + v_cid);
//while (e.hasMoreElements()) {
//System.out.println("The elements are: " + e.nextElement());
//}*/
} catch (Exception e) {
System.out.println(e);
}
}
}
public void endDocument() throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endDocument");
}
public void endElement(String uri, String localName, String tagName)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endElement");
}
public void endPrefixMapping(String prefix) throws SAXException {
debug("file:///store/home/user/SAXParser.txt","endPrefixMapping");
}
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","ignorableWhitespace");
}
public void processingInstruction(String target, String data)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","processingInstruction");
}
public void setDocumentLocator(Locator locator) {
debug("file:///store/home/user/SAXParser.txt","setDocumentLocator");
}
public void skippedEntity(String name) throws SAXException {
}
public void startDocument() throws SAXException {
debug("file:///store/home/user/SAXParser.txt","startDocument");
}
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
debug("file:///store/home/user/SAXParser.txt","startPrefixMapping");
}
public static void debug(String strFileName,String strData)
{
FileConnection fc = null;
StringBuffer strbufData = null;
OutputStream ops = null;
try
{
fc = (FileConnection)Connector.open(strFileName,Connector. READ_WRITE);
//create the file if it doesnt exist
if(!fc.exists())
{
fc.create();
}
InputStream is = fc.openDataInputStream();
strbufData = new StringBuffer();
int intCh;
while((intCh = is.read())!= -1)
{
strbufData.append((char)intCh);
}
strbufData.append("\n\n"+strData);
String strFileContent = new String(strbufData.toString());
byte byteData[] = strFileContent.getBytes();
ops = fc.openOutputStream();
ops.write(byteData);
}
catch(Exception e)
{
Dialog.alert("Exception in writing logs :"+e);
}
finally
{
if(ops != null)
{
try
{
ops.close();
}catch(Exception e)
{
}
}
if(fc != null)
{
try
{
fc.close();
}catch(Exception e)
{
}
}
}
}
}
How can I display scroll like marquee text in Blackberry using J2ME? That moves from left to right or vertically?
Any help will be very much appreciated.
its really easy to display.
check the code below .
import java.util.Timer;
import java.util.TimerTask;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
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.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
public class MarqueeApp extends UiApplication {
public MarqueeApp() {
pushScreen(new MarqueeScreen());
}
public static void main(String[] args) {
(new MarqueeApp()).enterEventDispatcher();
}
}
class MarqueeScreen extends MainScreen {
public MarqueeScreen() {
setTitle(new LabelField("hi"));
MarqueeLabel testLabel1 = new MarqueeLabel("This is a marquee",
Field.FOCUSABLE);
add(testLabel1);
MarqueeLabel testLabel2 = new MarqueeLabel("This is a long long " +
"long long long long long long long long long long long " +
"long long marquee", Field.FOCUSABLE);
add(testLabel2);
}
}
class MarqueeLabel extends LabelField {
int currentChar = 0;
String currentText = null;
Font ourFont;
private Timer _scrollTimer;
private TimerTask _scrollTimerTask;
public MarqueeLabel(String text, long style) {
super(text, style);
}
public void paint(Graphics graphics) {
currentText = this.getText();
if (currentChar < currentText.length()) {
currentText = currentText.substring(currentChar);
}
graphics.drawText(currentText, 0, 0, DrawStyle.ELLIPSIS, 200);
super.paint(graphics);
}
public void layout(int width, int height) {
ourFont = this.getFont();
setExtent(500, ourFont.getHeight());
}
protected void onDisplay() {
startScroll();
}
protected void onUnfocus() {
startScroll();
}
private void startScroll() {
// Start scrolling
final String fullText = this.getText();
if (_scrollTimer == null) {
_scrollTimer = new Timer();
_scrollTimerTask = new TimerTask() {
public void run() {
currentChar = currentChar + 4;
if (currentChar > fullText.length()) {
currentChar = 0;
}
invalidate();
}
};
_scrollTimer.scheduleAtFixedRate(_scrollTimerTask, 0, 300);
}
}
protected void onFocus(int direction) {
if (_scrollTimer != null) {
_scrollTimerTask.cancel();
_scrollTimer.cancel();
_scrollTimer = null;
_scrollTimerTask = null;
}
}
protected boolean navigationMovement(int dx, int dy,
int status, int time) {
currentText = this.getText();
int oldCurrentChar = currentChar;
if (Math.abs(dx) > Math.abs(dy)) {
// horizontal scroll
if (dx > 0) {
currentChar = Math.min(currentText.length() - 1,
currentChar + 1);
} else if (dx < 0) {
currentChar = Math.max(0, currentChar - 1);
}
if (oldCurrentChar != currentChar) {
this.invalidate();
}
return true;
} else {
return super.navigationMovement(dx, dy, status, time);
}
}
}