issue with parsing JSON Data in Blackberry - blackberry

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

Related

Excel Array Java

I imported my excel file into Java. I am now trying to randomly pick 5 people from my data. How would I go about doing that... Here is my code that I have so far.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class Rewards {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = "C:/Users/Jordan/Desktop/Project5.csv";
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
while((fileName = br.readLine()) != null) {
lineNumber++;
String[] result = fileName.split(",");
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'd start with a Random instance. How else can you do anything pseudo-randomly in any programming language?

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

Json parsing in Blackberry 5.0

i am developing app in blackberry version 5.0, and i had import all library which require for json in 5.0.
i had download library from this url
http://supportforums.blackberry.com/t5/Java-Development/JSON-library/td-p/573687
even i not getting response, what i had miss in this code please help me.
Below is my code For json parsing.
package mypackage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import JSON_ME_Library.src.org.json.me.JSONArray;
import JSON_ME_Library.src.org.json.me.JSONException;
import JSON_ME_Library.src.org.json.me.JSONObject;
import net.rim.device.api.ui.UiApplication;
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.container.MainScreen;
public final class MyScreen extends MainScreen
{
String url="http://www.appymail.com/iphone-messenger/456842/";
public MyScreen()
{
setTitle("Json Parsing Sample");
String aa=jsonresponse(url);
if(aa.equalsIgnoreCase(""))
{
add(new LabelField("NO res"));
}
else
{
parseJSONResponceInBB(aa);
}
}
void parseJSONResponceInBB(String jsonInStrFormat)
{
try {
JSONObject json = new JSONObject(jsonInStrFormat);
JSONArray jArray= json.getJSONArray("messages");
//JSONArray arr=jArray.getJSONArray(0);
for(int i=0;i<jArray.length();i++)
{
JSONObject j = jArray.getJSONObject(i);
String from = j.getString("id");
add(new LabelField("id=="+from));
String to =j.getString("title");
add(new LabelField("title=="+to));
String message=j.getString("body");
add(new LabelField("Body=="+message));
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
public static String jsonresponse (String url)
{
String response = null;
HttpConnection httpConnection = null;
InputStream inStream = null;
int code;
StringBuffer stringBuffer = new StringBuffer();
try {
httpConnection = (HttpConnection) Connector.open(url, Connector.READ);
httpConnection.setRequestMethod(HttpConnection.GET);
code = httpConnection.getResponseCode();
if(code == HttpConnection.HTTP_OK)
{
inStream=httpConnection.openInputStream();
int c;
while((c=inStream.read())!=-1)
{
stringBuffer.append((char)c);
}
response=stringBuffer.toString();
System.out.println("Response Getting from Server is ================" + response);
}
else
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.inform("Connection error");
}
});
}
}
catch (Exception e)
{
System.out.println("caught exception in jsonResponse method"+e.getMessage());
}
finally
{
// if (outputStream != null)
// {
// outputStream.close();
// }
if (inStream != null)
{
try {
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (httpConnection != null )
{
try {
httpConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
}
Hello dear you need to use url extension for blackberry
so please try to change this line
String aa=jsonresponse(url);
as
String aa=jsonresponse(url+";interface=wifi");
After successfully completed download data from url then once check String aa getting any value or not? if it get data then follow
try this if it is working fine then go through this following link
Guide for URL extensions
Enter Url in
String url="Your url";
String request=jsonresponse(url+";interface=wifi");
String response = parseJSONResponceInBB(request);
if(response .equalsIgnoreCase(""))
{
add(new LabelField("NO res"));
}
else
{
add(new LabelField(response ));
}

BlackBerry HttpCOnnection

/* Hi Iam developing an application where the BB app needs to post data to server. The Http connection works fine on Blackberry emulator, but when i try to test it on a real device the application cannot post data to server. the following is my code:
*/
package com.sims.datahandler;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import com.sims.commonmethods.CommonMethods;
import com.sims.screens.MenuScreen;
/**
*
* #author SaiKrishnaPawar
*
*/
public class GPRSHandler extends Thread {
private String data;
private String url;
private String msgKey;
private String mobileNumber;
public String sendGPRSRequest() {
HttpConnection httpConn = null;
DataOutputStream oStrm = null;
DataInputStream is = null;
byte[] resp = null;
String responseData;
try {
// Creating httpconnection object to handle GPRS request
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language", "en-US");
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
oStrm = httpConn.openDataOutputStream();
byte dataArray[] = (mobileNumber + "&" + msgKey + data).getBytes();
// byte dataArray[] = (msgKey + data).getBytes();
CommonMethods.getSystemOutput("msg key and data:::"+mobileNumber + msgKey + data);
for (int i = 0; i < dataArray.length; i++) {
oStrm.writeByte(dataArray[i]);
}
DataInputStream din = httpConn.openDataInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = din.read()) != -1) {
baos.write(ch);
}
resp = baos.toByteArray();
responseData = new String(resp);
baos.close();
din.close();
httpConn.close();
return responseData.trim();
} catch (IOException ex) {
CommonMethods.getSystemOutput("IO Exception in run method of gprs handler::" + ex.getMessage());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
int choice = Dialog.ask(Dialog.D_OK, "No Connectivity");
exitApp(choice);
}
});
} catch (NullPointerException nex) {
CommonMethods.getSystemOutput("NullPointerException:" + nex.getMessage());
} catch (SecurityException e) {
CommonMethods.getSystemOutput("SecurityException:" + e.getMessage());
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.ask(Dialog.OK, "Security Exception");
UiApplication.getUiApplication().pushScreen(new MenuScreen());
}
});
} finally {
try {
if (is != null) {
is.close();
}
if (oStrm != null) {
oStrm.close();
}
if (httpConn != null) {
httpConn.close();
}
} catch (Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.ask(Dialog.OK, "ERROR in While Connecting GPRS Connection");
UiApplication.getUiApplication().pushScreen(new MenuScreen());
}
});
}
}
return null;
}
public void setData(String data) {
this.data = data;
}
public void setMsgKey(String msgKey) {
this.msgKey = msgKey;
}
public void setUrl(String url) {
this.url = url + ";deviceside=false";
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
private void exitApp(int choice) {
System.exit(0);
}
}
httpConn = (HttpConnection) Connector.open(url);
instead of this you can write//
url = url + ";deviceside=false";
httpConn = (HttpConnection) Connector.open(url);
Please add network extension in this line
httpConn = (HttpConnection) Connector.open(url);
at the end of the url please check did you add url extension
for suppose you are using wifi then you have to add
httpConn = (HttpConnection) Connector.open(url+";interface=wifi");
this is working for interface if you want to other types of networks then just refer my answer here
"Tunnel Failed" exception in BlackBerry Curve 8520

blackberry GET request with Java Me

i am trying to get data sending GET request to a php service, but unfortunately i am not getting any result, i am using Blackberry Simulator 9800, here is my code,
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = "";
String url = "http://www.devbrats.com/testing/ActorRated/Service/cities.php";
try{
conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE, true);
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";
}
} catch(Exception ex){
ex.printStackTrace();
} finally{
try {
if(in != null){
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Please tell me what is the problem with it,
You will have to use this : http://www.blackberry.com/developers/docs/5.0.0api/net/rim/device/api/io/transport/ConnectionFactory.html
To properly create a network connection with the right parameter.
If you are not using OS5+ use this : http://www.versatilemonkey.com/HttpConnectionFactory.java
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A class extending the MainScreen class, which provides default standard
* behavior for BlackBerry GUI applications.
*/
public final class MyScreen extends MainScreen {
private LabelField lbl;
/**
* Creates a new MyScreen object
*/
public MyScreen() {
setTitle("MyTitle");
new Thread(new ConnectThread(this)).start();
lbl = new LabelField();
this.add(lbl);
}
public void update(Object object) {
synchronized (UiApplication.getEventLock()){
lbl.setText((String)object);
}
}
private class ConnectThread implements Runnable {
private MainScreen screen;
public ConnectThread(MainScreen screen) {
this.screen = screen;
}
public void run() {
HttpConnection conn = null;
InputStream in = null;
StringBuffer buff = new StringBuffer();
String result = "";
String url = "http://www.devbrats.com/testing/ActorRated/Service/cities.php";
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();
}
((MyScreen)screen).update(result);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Resources