BlackBerry java.io.IOException: null - blackberry

I am using following code for getting contents of a web page
String url = "http://abc.com/qrticket.asp?qrcode="
+ "2554";
try {
url += ";deviceside=true;interface=wifi;ConnectionTimeout=" + 50000;
HttpConnection connection = (HttpConnection) Connector.open(url,
Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.GET);
// connection.openDataOutputStream();
InputStream is = connection.openDataInputStream();
String res = "";
int chr;
while ((chr = is.read()) != -1) {
res += (char) chr;
}
is.close();
connection.close();
showDialog(parseData(res));
} catch (IOException ex) {
ex.printStackTrace();
showDialog("http: " + ex.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
showDialog("unknown: " + ex.getMessage());
}
public void showDialog(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(text);
}
});
}
public String parseData(String str) {
String[] data = split(str, "//");
StringBuffer builder = new StringBuffer();
for (int i = 0; i < data.length; i++) {
System.out.println("data:" + data[i]);
String[] vals = split(data[i], ">>");
if (vals.length > 1) {
System.out.println(vals[0]);
builder.append(vals[0].trim()).append(": ")
.append(vals[1].trim()).append("\n");
} else {
builder.delete(0, builder.toString().length()).append(
vals[0].trim());
break;
}
}
return builder.toString();
}
public String[] split(String splitStr, String delimiter) {
// some input validation
if (delimiter == null || delimiter.length() == 0) {
return new String[] { splitStr };
} else if (splitStr == null) {
return new String[0];
}
StringBuffer token = new StringBuffer();
Vector tokens = new Vector();
int delimLength = delimiter.length();
int index = 0;
for (int i = 0; i < splitStr.length();) {
String temp = "";
if (splitStr.length() > index + delimLength) {
temp = splitStr.substring(index, index + delimLength);
} else {
temp = splitStr.substring(index);
}
if (temp.equals(delimiter)) {
index += delimLength;
i += delimLength;
if (token.length() > 0) {
tokens.addElement(token.toString());
}
token.setLength(0);
continue;
} else {
token.append(splitStr.charAt(i));
}
i++;
index++;
}
// don't forget the "tail"...
if (token.length() > 0) {
tokens.addElement(token.toString());
}
// convert the vector into an array
String[] splitArray = new String[tokens.size()];
for (int i = 0; i > splitArray.length; i++) {
splitArray[i] = (String) tokens.elementAt(i);
}
return splitArray;
}
This is working absolutely fine in simulator but giving 'http:null' (IOException) on device, I dont know why??
How to solve this problem?
Thanks in advance

I think the problem might be the extra connection suffixes you're trying to add to your URL.
http://abc.com/qrticket.asp?qrcode=2554;deviceside=true;interface=wifi;ConnectionTimeout=50000
According to this BlackBerry document, the ConnectionTimeout parameter isn't available for Wifi connections.
Also, I think that if you're using Wifi, your suffix should simply be ";interface=wifi".
Take a look at this blog post on making connections on BlackBerry Java, pre OS 5.0. If you only have to support OS 5.0+, I would recommend using the ConnectionFactory class.
So, I would try this with the url:
http://abc.com/qrticket.asp?qrcode=2554;interface=wifi
Note: it's not clear to me whether your extra connection parameters are just ignored, or are actually a problem. But, since you did get an IOException on that line, I would try removing them.

The problem was that no activation of blackberry internet service. After subscription problem is solved.
Thanks alto all of you especially #Nate

Related

duplicate SSID in scanning wifi result

i'm trying to make an app that can create a list of available wifi access point. here's part of the code i used:
x = new BroadcastReceiver()
{
#Override
public void onReceive(Context c, Intent intent)
{
results = wifi.getScanResults();
size = results.size();
if (results != null) {
for (int i=0; i<size; i++){
ScanResult scanresult = wifi.getScanResults().get(i);
String ssid = scanresult.SSID;
int rssi = scanresult.level;
String rssiString = String.valueOf(rssi);
textStatus.append(ssid + "," + rssiString);
textStatus.append("\n");
}
unregisterReceiver(x); //stops the continuous scan
textState.setText("Scanning complete!");
} else {
unregisterReceiver(x);
textState.setText("Nothing is found. Please make sure you are under any wifi coverage");
}
}
};
both textStatus and textState is a TextView.
i can get this to work but sometimes the result shows duplicate SSID but with different signal level, in a single scan. there might be 3-4 same SSIDs but with different signal level.
is it really different SSIDs and what differs them? can anyone explain?
Are you having several router modems for the same network? For example: A company has a big wireless network with multiple router modems installed in several places so every room has Wifi. If you do that scan you will get a lot of results with the same SSIDs but with different acces points, and thus different signal level.
EDIT:
According to Walt's comment you can also have multiple results despite having only one access point if your modem is dual-band.
use below code to to remove duplicate ssids with highest signal strength
public void onReceive(Context c, Intent intent) {
ArrayList<ScanResult> mItems = new ArrayList<>();
List<ScanResult> results = wifiManager.getScanResults();
wifiListAdapter = new WifiListAdapter(ConnectToInternetActivity.this, mItems);
lv.setAdapter(wifiListAdapter);
int size = results.size();
HashMap<String, Integer> signalStrength = new HashMap<String, Integer>();
try {
for (int i = 0; i < size; i++) {
ScanResult result = results.get(i);
if (!result.SSID.isEmpty()) {
String key = result.SSID + " "
+ result.capabilities;
if (!signalStrength.containsKey(key)) {
signalStrength.put(key, i);
mItems.add(result);
wifiListAdapter.notifyDataSetChanged();
} else {
int position = signalStrength.get(key);
ScanResult updateItem = mItems.get(position);
if (calculateSignalStength(wifiManager, updateItem.level) >
calculateSignalStength(wifiManager, result.level)) {
mItems.set(position, updateItem);
wifiListAdapter.notifyDataSetChanged();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is my simple Solution please and it is work for me
private void scanWifiListNew() {
wifiManager.startScan();
List<ScanResult> wifiList = wifiManager.getScanResults();
mWiFiList = new ArrayList<>();
for(ScanResult result: wifiList){
checkItemExists(mWiFiList, result);
}
setAdapter(mWiFiList);
}
private void printList(List<ScanResult> list){
for(ScanResult result: list){
int level = WifiManager.calculateSignalLevel(result.level, 100);
System.out.println(result.SSID + " Level is " + level + " out of 100");
}
}
private void checkItemExists(List<ScanResult> newWiFiList, ScanResult resultNew){
int indexToRemove = -1;
if(newWiFiList.size() > 0) {
for (int i = 0; i < newWiFiList.size(); i++) {
ScanResult resultCurrent = newWiFiList.get(i);
if (resultCurrent.SSID.equals(resultNew.SSID)) {
int levelCurrent = WifiManager.calculateSignalLevel(resultCurrent.level, 100);
int levelNew = WifiManager.calculateSignalLevel(resultNew.level, 100);
if (levelNew > levelCurrent) {
indexToRemove = i;
break;
}else indexToRemove = -2;
}
}
if(indexToRemove > -1){
newWiFiList.remove(indexToRemove);
newWiFiList.add(indexToRemove,resultNew);
}else if(indexToRemove == -1)newWiFiList.add(resultNew);
} else newWiFiList.add(resultNew);
}
private void setAdapter(List<ScanResult> list) {
listAdapter = new WifiListAdapter(getActivity().getApplicationContext(), list);
wifiListView.setAdapter(listAdapter);
}

How to reuse j2me kxml parser?

I am useing kxml parser for my j2me application. I am reading the file from phone memory and parsing the xml file to display the data(have various level of filter). On each filter i need to read the data from this file. For first time i created the parser and every time i re-assign this parser1(reference-original) to the paerser2(used to parse data). For first time i got the correct answer, but second time i haven't got the file content it shows null as data.
Here is my code:
FileConnection fc = (FileConnection)Connector.open(rmsObj.rmsData.elementAt(0).toString());
InputStream in = fc.openInputStream();
InputStreamReader is = new InputStreamReader(in);
commonAppObj.externParser = new XmlParser(is);
commonAppObj class file.
protected void fileread() {
try {
if(externParser != null){
parser = externParser;
fileparser(parser);
}else{
InputStream in = this.getClass().getResourceAsStream(this.dataBase);
InputStreamReader is = new InputStreamReader(in);
parser = new XmlParser(is);
fileparser(parser);
}
} catch (IOException ioe) {
} finally {
parser = null;
}
}
private void fileparser(XmlParser parser){
try {
ParseEvent event = null;
dataflag = 0;
dataflagS = 0;
System.out.println("findtags = " + findtags);
while (((event = parser.read()).getType() != Xml.END_DOCUMENT) && (dataflag != 1)) {
if (event.getType() == Xml.START_TAG) {
String name = event.getName();
if (name != null && name.equals(findtags)) {
dataflag = 0;
parseAddressTag(parser);
}
name = null;
}
event = null;
}
} catch (IOException ioe) {
} finally {
parser = null;
}
}
}
If your InputStream returns true in a call to markSupported you may reset it at the end of fileparser method, but first you need to call mark right after creating it.
if (in.markSupported()) {
in.mark(in.available());
}

ScriptBundle not including other script depending on the ordering

I'm trying to combine all scripts into one.. I have two folders, the main folder 'scripts' and the other 'scripts/other'.
When I try:
BundleTable.Bundles.Add(new ScriptBundle("~/scripts/all").Include("~/Scripts/*.js", "~/Scripts/other/*.js"));
scripts from 'scripts/other' are not included.
but when I invert the order:
BundleTable.Bundles.Add(new ScriptBundle("~/scripts/all").Include("~/Scripts/other/*.js", "~/Scripts/*.js"));
it works!!
Someone can tell me why?
Can you try calling the IncludeDirectory methods directly and seeing if you see the same issue?
ScriptBundle("~/scripts/all").IncludeDirectory("~/Scripts", "*.js").IncludeDirectory("~/Scripts/other", "*.js"));
If this works, then it's possible we have a bug here.
I don't know what is happening, but this is the code inside the System.Web.Optimization.Bundle:
// System.Web.Optimization.Bundle
public Bundle Include(params string[] virtualPaths)
{
for (int i = 0; i < virtualPaths.Length; i++)
{
string text = virtualPaths[i];
Exception ex = Bundle.ValidateVirtualPath(text, "virtualPaths");
if (ex != null)
{
throw ex;
}
if (text.Contains('*'))
{
int num = text.LastIndexOf('/');
string text2 = text.Substring(0, num);
if (text2.Contains('*'))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, OptimizationResources.InvalidPattern, new object[]
{
text
}), "virtualPaths");
}
string text3 = "";
if (num < text.Length - 1)
{
text3 = text.Substring(num + 1);
}
PatternType patternType = PatternHelper.GetPatternType(text3);
ex = PatternHelper.ValidatePattern(patternType, text3, "virtualPaths");
if (ex != null)
{
throw ex;
}
this.IncludeDirectory(text2, text3);
}
else
{
this.IncludeFile(text);
}
}
return this;
}

j2me openOutputStream stream already open

Im having difficulties with the HttpConnection posting data to my server. The first time everything goes well. The second time it says; 'Stream already open', but i close everything after the response.
Here is my code:
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.location.*;
import java.io.*;
class GetSnowheights
{
HttpConnection http = null;
QualifiedCoordinates q = null;
public String result = "Geen data";
private boolean running;
public GetSnowheights(QualifiedCoordinates q) {
try
{
/*
this.http = (HttpConnection)Connector.open("http://www.diamond4it.nl/bb/");
this.http.setRequestMethod(HttpConnection.POST);
this.http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
*/
//Internet.getInstance();
this.http = Internet.getConnection();
}catch(Exception err){
err.printStackTrace();
}
this.q = q;
this.result = "Running";
}
public void GetResult(){
StringBuffer sb = new StringBuffer();
this.result = "GetResult";
if(this.http != null){
OutputStream os = null;
InputStream is = null;
try
{
//Send request
os = this.http.openOutputStream();
String data = "lat=1&lng=1";
//String data = "lat=" + this.q.getLatitude() + "&lng=" + this.q.getLongitude();
os.write(data.getBytes());
os.flush();
os.close();
this.result = "dataSend";
//Check response and read data
int res = this.http.getResponseCode();
this.result = "Result: " + res;
if(res == 200){
is = this.http.openInputStream();
int ch;
// Check the Content-Length first
long len = this.http.getLength();
if(len!=-1) {
for(int i = 0;i<len;i++){
if((ch = is.read())!= -1){
sb.append((char)ch);
}
}
} else {
// if the content-length is not available
while ((ch = is.read()) != -1){
sb.append((char)ch);
}
}
is.close();
}
this.result = sb.toString();
}catch(Exception err){
//err.printStackTrace();
this.result = err.toString() + "\r\n" + err.getMessage();
}finally{
if(is != null){
try{
is.close();
}catch(Exception err){
err.printStackTrace();
}
}
if(os != null){
try{
//os.flush();
os.close();
}catch(Exception err){
err.printStackTrace();
}
}
/*
if(http != null){
try{
http.close();
}catch(Exception err){
err.printStackTrace();
}
}
*/
}
}else{
this.result = "No connection";
}
}
}
2 ideas:
Why have you commented out the http.close() in finally block? We should always close HttpConnections.
Don't you call GetResult() from several threads simultaneously? If yes, then make the method synchronized by adding synchronized keyword in its definition.
P.S. I find the design of the class a bit misleading. It's very easy to make a mistake by incorrect usage of it. I'd combine GetSnowheights and GetResult into the only synchronized method.

Retriving url from webservice and how to connect to that url

i am new to black berry.i am doing one task,i have one webservice to show some url.i need to retrive it and connect to that url.i tried with two threads one is to retrive url and other is to connect to url which is in webservice but it shows nullpointer exception.please help me.
Thank You.
since you have not posted any code, it's very difficult to diagnose the problem. But look at the following code which tries to open an absolute url. This can be helpful.
Use this method for both of your connection (Web Service and URL returned from Web Service). Be sure to call this method in a separate thread otherwise it will freeze the UI.
public static ResponseBean sendRequestAndReceiveResponse(
String method, String absoluteURL, String bodyData, boolean readResponseBody)
throws IOException
{
ResponseBean responseBean = new ResponseBean();
HttpConnection httpConnection = null;
try
{
String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi
//String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
//String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP
if(DeviceInfo.isSimulator()) // if simulator is running
formattedURL = absoluteURL;
httpConnection = (HttpConnection) Connector.open(formattedURL);
httpConnection.setRequestMethod(method);
if (bodyData != null && bodyData.length() > 0)
{
OutputStream os = httpConnection.openOutputStream();
os.write(bodyData.getBytes("UTF-8"));
}
int responseCode = httpConnection.getResponseCode();
responseBean.setResponseCode(responseCode);
if (readResponseBody)
{
responseBean.setBodyData(readBodyData(httpConnection));
}
}
catch (IOException ex)
{
System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw ex;
}
catch(Exception ex)
{
System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw new IOException(ex.toString());
}
finally
{
if (httpConnection != null)
httpConnection.close();
}
return responseBean;
}
public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
{
if(httpConnection == null)
return null;
StringBuffer bodyData = new StringBuffer(256);
InputStream inputStream = httpConnection.openDataInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
while ( -1 != (len = inputStream.read(data)) )
{
bodyData.append(new String(data, 0, len,"UTF-8"));
size += len;
}
if (inputStream != null)
{
inputStream.close();
}
return bodyData;
}

Resources