Internet issue in blackberry - blackberry

I am developing a blackberry app for sending messages through internet . i have succesfully completed the project, but now i am getting error "to check the net connection even if the net connection is available.
I have closed my http connection .but still the issue persist .
Sometimes it works alright but after somtime it throws the error ".
In one word it is not getting the internet connection .
Please help me.
this is my code
InputStream in=null;
int rc=0;
HttpConnection http=null;
ConnectionFactory factory = new ConnectionFactory();
try{
String u="my url goes here";deviceside=true";
ConnectionDescriptor descriptor = factory.getConnection(u);
http = (HttpConnection)descriptor.getConnection();
in = http.openDataInputStream();
rc = http.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
Dialog.inform("Please Check The Internet Connection ");
}
int ch;
while ( (ch = in.read())!= -1){
buff3.append( (char) ch);
}
Dialog.inform(" Your Balance Is \n " +buff3.toString() );
buff3.delete(0,buff3.toString().length());
// buff3=new StringBuffer();
//stringItem.setText(" Your Balance Is \n " +buff.toString());
}
catch(Exception o){
Dialog.inform("Please Check The Internet Connection ");
buff3.delete(0,buff3.toString().length());
}
finally
{
try {
if(in != null)
in.close();
if(http != null)
http.close();
buff3.delete(0,buff3.toString().length());
} catch (IOException ex) {
ex.printStackTrace();
}
}

Related

Getting Error code -1 (HTTP_CONNECTION_REFUSED) after first connection

I have a setup with two ESP8266 chips.
One is AP and listening for alarms from other ESP8266 in WiFi mode.
AP is an access point accepting get requests from "alarm" chips.
My problem is that when the first GET request has been handled (succesfully) by the AP, it is no longer possible to make more requests unless the AP chip is reset.
Connection to the AP WiFI goes fine apparently but the actual get request only works on the first attempt after reset, the next ones all return error code -1 to the client.
Code from the AP chip:
void setupAP()
{
WiFi.mode(WIFI_AP);
String AP_NameString = "KEEP SAFE " + deviceID;
char AP_NameChar[AP_NameString.length() + 1];
memset(AP_NameChar, 0, AP_NameString.length() + 1);
for (int i = 0; i < AP_NameString.length(); i++)
AP_NameChar[i] = AP_NameString.charAt(i);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); // subnet FF FF FF 00
WiFi.softAP(AP_NameChar, WiFiAPPSK);
yield();
activeMenu = mainMenu;
server.on("/setup", handleWebRequest_Setup); //Associate the handler function to the path
server.on("/confirm", handleWebRequest_Confirm); //Associate the handler function to the path
server.on("/alarm", HTTP_GET, handleWebRequest_Alarm);
server.begin(); //Start the server
Serial.println("Server listening");
}
void handleWebRequest_Alarm(){
Serial.println("Client connected");
sensorAlarmPostback(server);
String s = "";
s += "<!DOCTYPE HTML>\r\n<html>\r\n";
s += "OK";
s += "</html>\n";
// Send the response to the client
Serial.println("Send OK to client");
server.send(200, "text/html", s);
Serial.println("OK Has been sent to the client");
}
void sensorAlarmPostback(ESP8266WebServer serv) {
Serial.println(String("Alaram recieved from : " + serv.arg("id")));
for (int i = 0; i < maxSensors; i++)
{
if (sensors[i].ID == serv.arg("id"))
sensors[i].alarm = true;
yield();
}
Serial.println("Sensor alarm flag has been set");
}
Code from the "sender" (alarm) chip:
void loop() {
initWifi();
publishAlarm();
WiFi.disconnect();
delay(30 * 1000); // Wait 30 seconds before next alarm
}
void initWifi() {
WiFi.disconnect();
WiFi.mode(WIFI_STA); // added in V 3.1a to disable AP_SSID publication in Client mode - default was WIFI_AP_STA
WiFi.begin(ssid.c_str(), password.c_str());
int retryCount = 0;
while (WiFi.status() != WL_CONNECTED && retryCount < 10) {
delay(2000);
retryCount++;
}
if (WiFi.status() != WL_CONNECTED)
Serial.println("WiFi ERROR");
else
Serial.println("WiFi Connected");
delay(500);
}
void publishAlarm(){
HTTPClient http;
String postStr = "?id=" + AlarmID;
postStr.replace("\r", "");
postStr.replace("\n", "");
Serial.println("String is");
Serial.println(postStr);
Serial.println("Connecting to Controller...");
String PostURL = "http://10.10.10.1/alarm" + postStr;
Serial.println("URL is: " + PostURL);
http.begin(PostURL);
int httpCode = http.GET();
if (httpCode > 0)
{
Serial.println("httpCode > 0");
yield();
delay(100);
http.end();
}
else
{
Serial.println("Error in upload " + String(httpCode));
yield();
delay(100);
http.end();
}
}
I realize that there is a lot of unneeded stuff in the code, but I have been trying almost everything. I just don't get it, and I have the same problem in other projects as well. The chips I use are Wemos D1 Minis and various NodeMCU dev. boards. Does not seem to be related to a specific board.
Update - SOLVED
I decided to wipe my entire development environment and re-install.
It wasn't that big of a deal.
And after a recompile and deployment to the chip (The AP Chip) it works as it alwas should have.
Oh well ....
Hope this helps someone if they end up in the same situation.
Now to cleaning up the code

Codename One - Can't read from socket on real device

I'm developing an iOS app, using Codename One. I extended the SocketConnection class, in order to receive data from a server.
class CustomSocketConnection extends SocketConnection {
private OutputStream os;
private InputStream is;
private InputStreamReader isr;
private String rawMessage;
public CustomSocketConnection(){
os = null;
is = null;
isr = null;
rawMessage = null;
}
public synchronized String getRawMessage(){
return rawMessage;
}
#Override
public void connectionError(int errorCode, String message) {
rawMessage = null;
ToastBar.showErrorMessage("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
System.out.println(">>>CustomSocketConnection, connectionError. Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
System.out.println(">>>CustomSocketConnection, connectionEstablished");
char termination = '\n';
int length = 1024;
char[] buffer = new char[length];
byte[] bufferByte = new byte[length];
StringBuilder stringBuilder = new StringBuilder();
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima del while");
try {
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima della read");
while(true){
System.out.println(">>>CustomSocketConnection, loop di read, inizio");
int read = isr.read();
System.out.println(">>>CustomSocketConnection, loop di read, subito dopo la read");
char c = (char) read;
if (read == -1) rawMessage = null;
System.out.println(">>>CustomSocketConnection, loop di read, letto: " + c);
while(c != termination){
stringBuilder.append(c);
read = isr.read();
c = (char) read;
if (read == -1) rawMessage = null;
}
rawMessage = stringBuilder.toString();
if(rawMessage != null) doActions(rawMessage);
//System.out.println(">>>CustomSocketConnection, connectionEstablished, ho letto: " + rawMessage + "FINE");
}
}
catch (IOException ex) {
System.out.println(">>>CustomSocketConnection, connectionEstablished, errore: " + ex.getMessage());
}
System.out.println(">>>CustomSocketConnection, connectionEstablished, dopo il while");
}
private void doActions(String msg){
//do something
}
}
In the connectionEstablished method, I read data from server, using the read method of the InputStreamReader class.
If I run the app on the simulator, it works properly and it receives data from server. When I launch the app on real devices (iPad mini, 32-bit device, iOS version 8.1.1 12B435, more details here; iPhone 7s, 64-bit device, iOS version 11.2.5 15D60), the read method doesn't receive data from server. In fact, I can see the string printed by the println before the read method, but I can't see the string printed by the println after the read method.
The issue is not server-side, because I developed an Android app and it receive data from the same server. There aren't firewall restrictions or other network limitations: Android app and the Codename One simulator both receive data when connected on the same local network of the server or from another one.
What's wrong?
Solved using InputStream instead of InputStreamReader.
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
System.out.println(">>>CustomSocketConnection, connectionEstablished");
char termination = '\n';
StringBuilder stringBuilder = new StringBuilder();
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima del while");
try {
System.out.println(">>>CustomSocketConnection, connectionEstablished, prima della read");
while(true){
System.out.println(">>>CustomSocketConnection, loop di read, inizio");
int read = is.read();
System.out.println(">>>CustomSocketConnection, loop di read, subito dopo la read");
char c = (char) read;
if (read == -1) rawMessage = null;
System.out.println(">>>CustomSocketConnection, loop di read, letto: " + c);
while(c != termination){
stringBuilder.append(c);
read = is.read();
c = (char) read;
if (read == -1) rawMessage = null;
}
rawMessage = stringBuilder.toString();
if(rawMessage != null) doActions(rawMessage);
//System.out.println(">>>CustomSocketConnection, connectionEstablished, ho letto: " + rawMessage + "FINE");
}
}
catch (IOException ex) {
System.out.println(">>>CustomSocketConnection, connectionEstablished, errore: " + ex.getMessage());
}
System.out.println(">>>CustomSocketConnection, connectionEstablished, dopo il while");
}
Can anyone explain me why it's working with InputStream?

low memory warning when saving files on blackberry

I want to save many files on Sdcard. When I save these files on folder I get a warning that the memory is low
the device memory is too low - please close the following items
and the application crashed.
The problem that I can put the folder manually and I didn't get problem of memory but in the pplication it show it even there is free space on Sdcard.
This the method that I used to save files.
public static void saveWebContentCache(String save_name, String url) {
FileConnection fconn = null;
OutputStream outputStream = null;
try {
fconn = (FileConnection) Connector.open(
NetWorkConfig.webfolder + save_name,
Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
outputStream = fconn.openOutputStream();
outputStream.write(getByte(url));
}
} catch (IOException e) {
Status.show("ko !");
} finally {// Close the connections
try {
if (outputStream != null) {
outputStream.close();
outputStream = null;
}
} catch (Exception e) {
}
try {
if (fconn != null) {
fconn.close();
fconn = null;
}
} catch (Exception e) {
}
}
}
As for me, this line looks suspicious:
outputStream.write(getByte(url));
This is because such implementation implies you have to create/hold in RAM the entire byte array before writing it to file's OutputStream.
Instead, you could combine reading by small chunks from the InputSteam of an http connection and writing the chunks to file's OutputStream. Something like this:
void copyData(InputStream source, OutputStream destination) throws IOException {
byte[] buf = new byte[1024];
int len;
while ((len = source.read(buf)) > 0) {
destination.write(buf, 0, len);
}
destination.flush();
}

Unexpected response code:403 when calling image in Blackberry

Right now i am working on Image download from web.For this i set http connection like below code.
HttpConnection connection = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
connection.setRequestMethod(HttpConnection.POST);
I am calling two images from web.for one picture it display image successfully.But for other picture it show error Unexpected response code:403.I am not understand why this problem is occur.How can i download image from web.Is there any change in HttpConnection need to modify.
Please help me.
Have you tested this on a real phone, or just in the emulator?
If you are using the emulator, make sure you've configured it to connect to the internet, it won't be configured to do that by default.
BlackBerry emulator not connecting to internet
Use this function , as we get bytes from the http connection,you need to convert those bytes into image this function will do that for you , just pass the url of the image in arguments:
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);
int currentWidthFixed32 = Fixed32.toFP(hai.getWidth());
int currentHeightFixed32 = Fixed32.toFP(hai.getHeight());
int reqWidth = 48;
int reqHeight = 35;
int requiredWidthFixed32 = Fixed32.toFP(reqWidth);
int requiredHeightFixed32 = Fixed32.toFP(reqHeight);
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, requiredWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, requiredHeightFixed32);
hai = hai.scaleImage32(scaleXFixed32, scaleYFixed32);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" +url+ 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;
}

Connection Closed When trying to post over 1.5K of url encoded data on 8900, and maybe others

From the simulator, this all works.
I'm using wifi on the device as i'm assuming it's the most stable.
The problem occurs when i try to post more than 1.5K of urlencoded data.
If i send less then it's fine.
It seems to hang the .flush command();
It works on a physical 9700, so i'm presuming that it's possibly device specific
In the example below i'm using form variables, but i've also tried posting the content type json, but still had the same issue
I've written a small testapp, and using the main thread so i know that it's not threads getting confused
If anyone has any ideas that would be great.
private String PostEventsTest()
{
String returnValue = "Error";
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
StringBuffer messagebuffer = new StringBuffer();
URLEncodedPostData postValuePairs;
try
{
postValuePairs = new URLEncodedPostData(null, false);
postValuePairs.append("DATA",postData);// postData);
hc = (HttpConnection) Connector.open(postURL, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("User-Agent", "BlackBerry");
hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
hc.setRequestProperty("Content-Length", Integer.toString(postValuePairs.getBytes().length));
//hc.setRequestProperty("Content-Length", Integer.toString(postData.length()));
dos = hc.openDataOutputStream();
dos.write(postValuePairs.getBytes());
dos.flush();
dos.close();
// Retrieve the response back from the servlet
dis = new DataInputStream(hc.openInputStream());
int ch;
// Check the Content-Length first
long len = hc.getLength();
if (len != -1)
{
for (int i = 0; i < len; i++)
if ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
else
{ // if the content-length is not available
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
dis.close();
returnValue = "Yahoo";
}
catch (Exception ex)
{
returnValue = ex.toString();
ex.printStackTrace();
}
return returnValue;
}
Instead of data streams you should just use the regular input and output streams. So instead of hc.openDataOutputStream() use hc.openOutputStream(). Data streams are for serializing Java objects to a stream, but you just want to write the raw bytes to the stream -- so a regular outputstream is what you want. Same for reading the response - just use the inputstream returned by hc.openInputStream()

Resources