Network Connection Failed after 10 minutes on blackberry - blackberry

I've implemented timer task on background application.
I've collected current lat and long. and send to server each 30 seconds.
I've used below code to send the information to server. It sends successfully..
My problem is, after i've checked 10 minutes, I'm unable to send. it throws a No Network error. I've checked browser too but no network.
If reset the device, its working again well. But the same problem occurs after 5 or 10 mins.
How to resolve this?
My code is,
try
{
StreamConnection connection = (StreamConnection) Connector.open(url+suffix);
((HttpConnection) connection).setRequestMethod(HttpConnection.GET);
int responseCode = ((HttpConnection) connection).getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
showDialog("Unexpected response code :"+ responseCode);
connection.close();
return;
}
((HttpConnection) connection).getHeaderField("Content-type");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream responseData = connection.openInputStream();
byte[] buffer = new byte[1000];
int bytesRead = responseData.read(buffer);
while (bytesRead > 0) {
baos.write(buffer, 0, bytesRead);
bytesRead = responseData.read(buffer);
}
baos.close();
connection.close();
String s = new String(baos.toByteArray());
showDialog("Responce from server "+s);
}
catch (IOException e)
{
}

Usually, when you have some problem where it works a few times, and then stops working, and you need to reset the device, you've done something that has used up all available resources, without releasing them when you're done.
When performing repeated network operations, you should clean up your streams and connections after each use.
Normally, the proper way to write network code is to declare network variables outside a try block, assign and use them inside the try, while catching any IOExceptions thrown. Then, you use a finally block to clean up your resources, no matter whether the code finished successfully or not.
I'll also note that when debugging network problems, you don't want to have a catch() handler that simply traps exceptions and does nothing with them. Print out a message to the console (for testing) or log the error to a file.
Finally, I can't see your showDialog() method, but if it's displaying a UI to the user/tester, you need to do that on the UI thread. But, the network code that you show above should be run on a background thread to keep the UI responsive. So, inside showDialog(), just make sure you use code to modify the UI on the UI thread.
So, a better implementation might be this:
private void requestFromServer() {
StreamConnection connection = null;
ByteArrayOutputStream baos = null;
InputStream responseData = null;
try
{
connection = (StreamConnection) Connector.open(url+suffix);
((HttpConnection) connection).setRequestMethod(HttpConnection.GET);
int responseCode = ((HttpConnection) connection).getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
showDialog("Unexpected response code :"+ responseCode);
return;
}
((HttpConnection) connection).getHeaderField("Content-type");
baos = new ByteArrayOutputStream();
responseData = connection.openInputStream();
byte[] buffer = new byte[1000];
int bytesRead = responseData.read(buffer);
while (bytesRead > 0) {
baos.write(buffer, 0, bytesRead);
bytesRead = responseData.read(buffer);
}
String s = new String(baos.toByteArray());
showDialog("Responce from server "+s);
}
catch (IOException e)
{
System.out.println("Network error: " + e.getMessage());
}
finally
{
try {
if (connection != null) {
connection.close();
}
if (baos != null) {
baos.close();
}
if (responseData != null) {
responseData.close();
}
} catch (IOException e) {
// nothing to do here
}
}
}
private void showDialog(final String msg) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(msg);
}
});
}

Related

org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool [duplicate]

This question already has answers here:
httpclient exception "org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection"
(10 answers)
Closed 8 years ago.
I use Multi-thread to scan the different URL in the same time in java. There was the bug,if the sum of request time exceed 100,000. I have already close which i should close. Here the code from my servlet
private String proyGetHttp(String url) throws ParseException, IOException,
InterruptedException {
String content = "";
getMethod = new HttpGet(url);
HttpResponse response = null;
HttpEntity httpEntity = null;
boolean success = false;
while (!success) {
System.out.println("url:" + url + ",connect...");
try {
response = client.execute(getMethod);
httpEntity = response.getEntity();
StringBuffer sb = new StringBuffer();
if (httpEntity != null) {
BufferedReader in = null;
InputStream instream = httpEntity.getContent();
try {
in = new BufferedReader(new InputStreamReader(instream));
String lineContent = "";
while(lineContent != null){
sb.append(lineContent);
lineContent = in.readLine();
}
} catch (Exception ex)
getMethod.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
try { instream.close(); in.close();} catch (Exception ignore) {}
}
}
content = sb.toString();
success = true;
System.out.println("connect successfully...");
} catch (Exception e) {
e.printStackTrace();
getMethod.abort();
System.out.println("connect fail, please waitting...");
Thread.sleep(sleepTime);
}finally{
getMethod.releaseConnection();
}
}
return content;
}
Here code create the default client
PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
cm.setMaxTotal(100);
DefaultHttpClient client = null;
client = new DefaultHttpClient(cm);
client.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 5000);
I have the same problem and I found the fix. This timeout is because of a connection leak. In my case, I'm using httpDelete method and not consuming the response. Instead, I'm checking the status of the response.
The fix is, the response entity need to be consumed. In order to ensure the proper release of system resources, one must close the content stream associated with the entity.
So I used EntityUtils.consumeQuietly(response.getEntity()); which ensures that the entity content is fully consumed and the content stream, if exists, is closed.

Deferring persistence as device is being used in BlackBerry when listening file change

I tried to listen file change event in BlackBerry base on FileExplorer example, but whenever I added or deleted file, it always showed "Deferring persistence as device is being used" and I can't catch anything .Here is my code:
public class FileChangeListenner implements FileSystemJournalListener{
private long _lastUSN; // = 0;
public void fileJournalChanged() {
long nextUSN = FileSystemJournal.getNextUSN();
String msg = null;
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN)
{
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);
// We didn't find an entry
if (entry == null)
{
break;
}
// Check if this entry was added or deleted
String path = entry.getPath();
if (path != null)
{
switch (entry.getEvent())
{
case FileSystemJournalEntry.FILE_ADDED:
msg = "File was added.";
break;
case FileSystemJournalEntry.FILE_DELETED:
msg = "File was deleted.";
break;
}
}
}
_lastUSN = nextUSN;
if ( msg != null )
{
System.out.println(msg);
}
}
}
Here is the caller:
Thread t = new Thread(new Runnable() {
public void run() {
new FileChangeListenner();
try {
Thread.sleep(5000);
createFile();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
Create file method worked fine:
private void createFile() {
try {
FileConnection fc = (FileConnection) Connector
.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file
// may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and output:
0:00:44.475: Deferring persistence as device is being used.
0:00:46.475: AG,+CPT
0:00:46.477: AG,-CPT
0:00:54.476: VM:+GC(f)w=11
0:00:54.551: VM:-GCt=9,b=1,r=0,g=f,w=11,m=0
0:00:54.553: VM:QUOT t=1
0:00:54.554: VM:+CR
0:00:54.596: VM:-CR t=5
0:00:55.476: AM: Exit net_rim_bb_datatags(291)
0:00:55.478: Process net_rim_bb_datatags(291) cleanup started
0:00:55.479: VM:EVTOv=7680,w=20
0:00:55.480: Process net_rim_bb_datatags(291) cleanup done
0:00:55.481: 06/25 03:40:41.165 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
0:00:55.487: 06/25 03:40:41.171 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
I also tried to remove the thread or create or delete file in simulator 's sdcard directly but it doesn't help. Please tell me where is my problem. Thanks
You instantiate the FileChangeListenner, but you never register it, and also don't keep it as a variable anywhere. You probably need to add this call
FileChangeListenner listener = new FileChangeListenner();
UiApplication.getUiApplication().addFileSystemJournalListener(listener);
You also might need to keep a reference (listener) around for as long as you want to receive events. But maybe not (the addFileSystemJournalListener() call might do that). But, you at least need that call to addFileSystemJournalListener(), or you'll never get fileJournalChanged() called back.

None of code can establish http connection over BIS

I am new in developing Blackberry Application.
In these three days, I already searched and learned in both forum and tutorial from the RIM itself. But none of them can solve my problem. >.<
So. I already tried some different methods to establish http connection over BIS in 4.6.
These are the following codes:
1.
HttpConnection httpConnection;
String url = "myURL;deviceside=true";
try{
httpConnection = (HttpConnection) Connector.open(url);
Dialog.inform(">.<");
}
catch(Exception e)
{
Dialog.inform(e.getMessage());
}
From the code #1 above, none of the dialogs are displayed.
String url = "myURL";
try {
StreamConnection s = (StreamConnection)Connector.open(url);
InputStream input = s.openInputStream();
Dialog.inform("sblm byte");
byte[] data = new byte[256];
int len = 0;
StringBuffer raw = new StringBuffer();
Dialog.inform("stlh buat byte");
while( -1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
Dialog.inform("stlh while");
response = raw.toString();
Dialog.inform(response);
input.close();
s.close();
}
catch(Exception e) { }
As well as code #1, this code above also doesnt pop up any dialog.
I am desperately need the right guide for establishing simple http connection. Is there any technique that I missed? Do I need any signature for this? Do I need extra setting in both my Blackberry device (BB 8900 with OS 5.00) or in my compiler, Eclipse?
Thank you.
Try this code.
try {
HttpConnection httpConnection=(HttpConnection)Connector.open(url);
httpConnection.setRequestMethod(HttpConnection.GET);
if(httpConnection.getResponseCode()==HttpConnection.HTTP_OK)
{
InputStream is=httpConnection.openInputStream();
int ch;
StringBuffer buffer=new StringBuffer();
while((ch=is.read())!=-1)
{
buffer.append((char)ch);
}
}
} catch (IOException e) {
System.out.println("Exception From Thread"+e);
e.printStackTrace();
}
}

wifi doesn't work in own apps, but works in blackberry's browser

we have just started to write Blackberry apps and got strange situation. Our apps work with mobile internet (GPRS, 3G, EDGE) but are not working using wifi connection.
I have tried to change all the settings. But still usually it is just "Tunnel failure" or "connection timed out" errors. The same is with HTTPDemo example.
Could someone help and explain what it is with Blackberry and WiFi?
StreamConnection s = null;
s = (StreamConnection)Connector.open(getUrl() +";interface=wifi");
HttpConnection httpConn = (HttpConnection)s;
int status = httpConn.getResponseCode();
if (status == HttpConnection.HTTP_OK)
{
// Is this html?
String contentType = httpConn.getHeaderField(HEADER_CONTENTTYPE);
boolean htmlContent = (contentType != null && contentType.startsWith(CONTENTTYPE_TEXTHTML));
InputStream input = s.openInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
StringBuffer raw = new StringBuffer();
while ( -1 != (len = input.read(data)) )
{
// Exit condition for the thread. An IOException is
// thrown because of the call to httpConn.close(),
// causing the thread to terminate.
if ( _stop )
{
httpConn.close();
s.close();
input.close();
}
raw.append(new String(data, 0, len));
size += len;
}
raw.insert(0, "bytes received]\n");
raw.insert(0, size);
raw.insert(0, '[');
content = raw.toString();
if ( htmlContent )
{
content = prepareData(raw.toString());
}
input.close();
}
else
{
content = "response code = " + status;
}
s.close();
}
catch (IOCancelledException e)
{
System.out.println(e.toString());
return;
}
catch (IOException e)
{
errorDialog(e.toString());
return;
}
Connecting the following way works for me
HttpConnection connection = null;
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connection = (HttpConnection) Connector.open(url+ ";interface=wifi",
Connector.READ_WRITE,true);
} else {
connection = (HttpConnection) Connector.open(url+";deviceside=true", Connector.READ_WRITE,true);
}
Please refer the following resource for in-depth understanding and various methods.
Sample HTTP Connection code and BIS-B Access By peter_strange

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