How to reuse j2me kxml parser? - parsing

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

Related

BlackBerry java.io.IOException: null

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

Writing a list of strings to a file

From the API page, I gather there's no function for what I'm trying to do. I want to read text from a file storing it as a list of strings, manipulate the text, and save the file. The first part is easy using the function:
abstract List<String> readAsLinesSync([Encoding encoding = Encoding.UTF_8])
However, there is no function that let's me write the contents of the list directly to the file e.g.
abstract void writeAsLinesSync(List<String> contents, [Encoding encoding = Encoding.UTF_8, FileMode mode = FileMode.WRITE])
Instead, I've been using:
abstract void writeAsStringSync(String contents, [Encoding encoding = Encoding.UTF_8, FileMode mode = FileMode.WRITE])
by reducing the list to a single string. I'm sure I could also use a for loop and feed to a stream line by line. I was wondering two things:
Is there a way to just hand the file a list of strings for writing?
Why is there a readAsLinesSync but no writeAsLinesSync? Is this an oversight or a design decision?
Thanks
I just made my own export class that handles writes to a file or for sending the data to a websocket.
Usage:
exportToWeb(mapOrList, 'local', 8080);
exportToFile(mapOrList, 'local/data/data.txt');
Class:
//Save data to a file.
void exportToFile(var data, String filename) =>
new _Export(data).toFile(filename);
//Send data to a websocket.
void exportToWeb(var data, String host, int port) =>
new _Export(data).toWeb(host, port);
class _Export {
HashMap mapData;
List listData;
bool isMap = false;
bool isComplex = false;
_Export(var data) {
// Check is input is List of Map data structure.
if (data.runtimeType == HashMap) {
isMap = true;
mapData = data;
} else if (data.runtimeType == List) {
listData = data;
if (data.every((element) => element is Complex)) {
isComplex = true;
}
} else {
throw new ArgumentError("input data is not valid.");
}
}
// Save to a file using an IOSink. Handles Map, List and List<Complex>.
void toFile(String filename) {
List<String> tokens = filename.split(new RegExp(r'\.(?=[^.]+$)'));
if (tokens.length == 1) tokens.add('txt');
if (isMap) {
mapData.forEach((k, v) {
File fileHandle = new File('${tokens[0]}_k$k.${tokens[1]}');
IOSink dataFile = fileHandle.openWrite();
for (var i = 0; i < mapData[k].length; i++) {
dataFile.write('${mapData[k][i].real}\t'
'${mapData[k][i].imag}\n');
}
dataFile.close();
});
} else {
File fileHandle = new File('${tokens[0]}_data.${tokens[1]}');
IOSink dataFile = fileHandle.openWrite();
if (isComplex) {
for (var i = 0; i < listData.length; i++) {
listData[i] = listData[i].cround2;
dataFile.write("${listData[i].real}\t${listData[i].imag}\n");
}
} else {
for (var i = 0; i < listData.length; i++) {
dataFile.write('${listData[i]}\n');
}
}
dataFile.close();
}
}
// Set up a websocket to send data to a client.
void toWeb(String host, int port) {
//connect with ws://localhost:8080/ws
//for echo - http://www.websocket.org/echo.html
if (host == 'local') host = '127.0.0.1';
HttpServer.bind(host, port).then((server) {
server.transform(new WebSocketTransformer()).listen((WebSocket webSocket) {
webSocket.listen((message) {
var msg = json.parse(message);
print("Received the following message: \n"
"${msg["request"]}\n${msg["date"]}");
if (isMap) {
webSocket.send(json.stringify(mapData));
} else {
if (isComplex) {
List real = new List(listData.length);
List imag = new List(listData.length);
for (var i = 0; i < listData.length; i++) {
listData[i] = listData[i].cround2;
real[i] = listData[i].real;
imag[i] = listData[i].imag;
}
webSocket.send(json.stringify({"real": real, "imag": imag}));
} else {
webSocket.send(json.stringify({"real": listData, "imag": null}));
}
}
},
onDone: () {
print('Connection closed by client: Status - ${webSocket.closeCode}'
' : Reason - ${webSocket.closeReason}');
server.close();
});
});
});
}
}
I asked Mads Agers about this. He works on the io module. He said that he decided not to add writeAsLines because he didn't find it useful. For one it is trivial to write the for loop and the other thing is that you have to parameterize it which the kind of line separator that you want to use. He said he can add it if there is a strong feeling that it would be valuable. He didn't immediately see a lot of value in it.

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

Issue in Invoking camera and saving images in SD card

In my task I have to invoke camera in a button click and take picture and have to save it and display the image in the same screen. I have tried it and succeed in emulator. but its not working in real device. getting some errors. tried a lot. but cant able to find out the issue. more over, Its working perfectly in 9700 emulator and showing some error in 9500.
public class CameraScreen extends MainScreen implements FieldChangeListener
{
/** The camera's video controller */
private VideoControl _videoControl;
private Field _videoField;
private EncodingProperties[] _encodings;
private int _indexOfEncoding = 0;
private static String FILE_NAME = System.getProperty("fileconn.dir.photos")+"IMAGE"; //"file:///SDCard/" + "myphotos/" + "IMAGE";//
private static String EXTENSION = ".bmp";
private static int _counter;
int flag = 0;
BitmapField imageField = new BitmapField();
HorizontalFieldManager menuBar = new HorizontalFieldManager(Field.USE_ALL_WIDTH);
VerticalFieldManager main_vfm = new VerticalFieldManager();
VerticalFieldManager camera_vfm = new VerticalFieldManager();
VerticalFieldManager image_vfm = new VerticalFieldManager();
ButtonField bt = new ButtonField("Click",ButtonField.CONSUME_CLICK);
ButtonField front_bt = new ButtonField("Front",ButtonField.CONSUME_CLICK);
ButtonField back_bt = new ButtonField("Back",ButtonField.CONSUME_CLICK);
ButtonField side1_bt = new ButtonField("Side 1",ButtonField.CONSUME_CLICK);
ButtonField side2_bt = new ButtonField("Side 2",ButtonField.CONSUME_CLICK);
public CameraScreen()
{
setTitle("First Screen");
bt.setChangeListener(this);
front_bt.setChangeListener(this);
back_bt.setChangeListener(this);
side1_bt.setChangeListener(this);
side2_bt.setChangeListener(this);
image_vfm.add(menuBar);
menuBar.add(front_bt);
menuBar.add(back_bt);
menuBar.add(side1_bt);
menuBar.add(side2_bt);
image_vfm.add(bt);
try {
Bitmap image = Bitmap.createBitmapFromBytes( readFile(),0, -1, 5 );
imageField.setBitmap(image);
image_vfm.add(imageField);
} catch(Exception e) {
System.out.println(e.toString());
}
main_vfm.add(image_vfm);
add(main_vfm);
front_bt.setFocus();
// Initialize the camera object and video field
initializeCamera();
// Initialize the list of possible encodings
initializeEncodingList();
// If the field was constructed successfully, create the UI
if(_videoField != null)
{
createUI();
}
// If not, display an error message to the user
else
{
camera_vfm.add( new RichTextField( "Error connecting to camera." ) );
}
}
/**
* Takes a picture with the selected encoding settings
*/
public void takePicture()
{
try
{
// A null encoding indicates that the camera should
// use the default snapshot encoding.
String encoding = null;
if( _encodings != null )
{
// Use the user-selected encoding
encoding = _encodings[_indexOfEncoding].getFullEncoding();
}
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
createImageScreen( _videoControl.getSnapshot( encoding ) );
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
}
}
/**
* Prevent the save dialog from being displayed
* #see net.rim.device.api.ui.container.MainScreen#onSavePrompt()
*/
protected boolean onSavePrompt()
{
return true;
}
/**
* Initializes the Player, VideoControl and VideoField
*/
private void initializeCamera()
{
try
{
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer( "capture://video" );
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
// Grab the video control and set it to the current display
_videoControl = (VideoControl)player.getControl( "VideoControl" );
if (_videoControl != null)
{
// Create the video field as a GUI primitive (as opposed to a
// direct video, which can only be used on platforms with
// LCDUI support.)
_videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
//_videoControl.setDisplaySize(50, 50);
_videoControl.setVisible(true);
}
// Set the player to the STARTED state (see Player javadoc)
player.start();
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
}
}
/**
* Initialize the list of encodings
*/
private void initializeEncodingList()
{
try
{
// Retrieve the list of valid encodings
String encodingString = System.getProperty("video.snapshot.encodings");
// Extract the properties as an array of word
String[] properties = StringUtilities.stringToKeywords(encodingString);
// The list of encodings
Vector encodingList = new Vector();
//Strings representing the four properties of an encoding as
//returned by System.getProperty().
String encoding = "encoding";
String width = "width";
String height = "height";
String quality = "quality";
EncodingProperties temp = null;
for(int i = 0; i < properties.length ; ++i)
{
if( properties[i].equals(encoding))
{
if(temp != null && temp.isComplete())
{
// Add a new encoding to the list if it has been
// properly set.
encodingList.addElement( temp );
}
temp = new EncodingProperties();
// Set the new encoding's format
++i;
temp.setFormat(properties[i]);
}
else if( properties[i].equals(width))
{
// Set the new encoding's width
++i;
temp.setWidth(properties[i]);
}
else if( properties[i].equals(height))
{
// Set the new encoding's height
++i;
temp.setHeight(properties[i]);
}
else if( properties[i].equals(quality))
{
// Set the new encoding's quality
++i;
temp.setQuality(properties[i]);
}
}
// If there is a leftover complete encoding, add it.
if(temp != null && temp.isComplete())
{
encodingList.addElement( temp );
}
// Convert the Vector to an array for later use
_encodings = new EncodingProperties[ encodingList.size() ];
encodingList.copyInto((Object[])_encodings);
}
catch (Exception e)
{
// Something is wrong, indicate that there are no encoding options
_encodings = null;
home.errorDialog(e.toString());
}
}
/**
* Adds the VideoField to the screen
*/
private void createUI()
{
// Add the video field to the screen
camera_vfm.add(_videoField);
}
/**
* Create a screen used to display a snapshot
* #param raw A byte array representing an image
*/
private void createImageScreen( byte[] raw )
{
main_vfm.replace(camera_vfm, image_vfm);
fieldChanged(raw);
Bitmap image1 = Bitmap.createBitmapFromBytes( readFile(),0, -1, 5 );
try{
if(flag == 1){
}
else{
image_vfm.delete(imageField);
}
imageField.setBitmap(image1);
image_vfm.add(imageField);
}
catch(Exception e){System.out.println(e.toString());}
}
private byte[] readFile() {
byte[] result = null;
FileConnection fconn = null;
try {
fconn = (FileConnection)Connector.open(FILE_NAME + "_front" + EXTENSION);
} catch (IOException e) {
System.out.print("Error opening file");
}
if (!fconn.exists()) {
//Dialog.inform("file not exist");
} else {
InputStream in = null;
ByteVector bytes = new ByteVector();
try {
in = fconn.openInputStream();
} catch (IOException e) {
System.out.print("Error opening input stream");
}
try {
int c = in.read();
while (-1 != c) {
bytes.addElement((byte) c);
c = in.read();
}
result = bytes.getArray();
} catch (IOException e) {
System.out.print("Error reading input stream");
}
try {
fconn.close();
} catch (IOException e) {
System.out.print("Error closing file");
}
}
return result;
}
public void fieldChanged( final byte[] _raw )
{
try
{
flag ++;
// Create the connection to a file that may or
// may not exist.
FileConnection file = (FileConnection)Connector.open(FILE_NAME + "_front" + EXTENSION);
// If the file exists, increment the counter until we find
// one that hasn't been created yet.
if (file.exists()) {
file.delete();
file.close();
file = (FileConnection) Connector.open(FILE_NAME + "_front" + EXTENSION);
}
//FileConnection file_temp = (FileConnection)Connector.open(FILE_NAME + "tempimg" + EXTENSION);
//file_temp.delete();
// We know the file doesn't exist yet, so create it
file.create();
// Write the image to the file
OutputStream out = file.openOutputStream();
out.write(_raw);
// Close the connections
//out.close();
file.close();
//Dialog.inform( "Saved to " + FILE_NAME + "_front" + EXTENSION );
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
Dialog.inform( "File not saved this time");
}
}
/**
* Sets the index of the encoding in the 'encodingList' Vector
* #param index The index of the encoding in the 'encodingList' Vector
*/
public void setIndexOfEncoding(int index)
{
_indexOfEncoding = index;
}
/**
* #see net.rim.device.api.ui.Screen#invokeAction(int)
*/
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if(!handled)
{
switch(action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
srn2 screen2 = new srn2();
srn3 screen3 = new srn3();
srn4 screen4 = new srn4();
if(field==bt)
{
main_vfm.replace(image_vfm, camera_vfm);
}
if(field==back_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen2);
}
if(field==side1_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen3);
}
if(field==side2_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen4);
}
}
}
Note: This Error displaying first "javax.microedition.media.MediaException: There is already another active Player. Call Player.close() on the existing Player to free up the resources." and camera gets open and when i try to take picture this error displays "Error Class Java.lang.ArrayIndexOutOfBoundsException: Index 0>=0"
After _videoControl.getSnapshot( encoding ) has been called you need to close player (i.e. to call player.close(). And that's exactly what the exception tells about.
However this method of taking images is highly unreliable - you'll not be able to use it for every BB device model. I don't know why RIM put it in SDK samples. By doing that RIM pushes developers to a wrong way. As alishaik786 mentiones a proper method of taking images on BB is using Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, new CameraArguments()) with a FileSystemJournalListener implementation. Just search on StackOverflow on these for the implementation details. I vaguely recall the implementation is painful (like many other parts on BB), but once done it will work on any device.
you got two error
1."javax.microedition.media.MediaException: There is already another active Player. Call Player.close()
this exception thrown if you try to open camera (player) while another instance of camera is already opened. In your code, you need to define the player object as a class level and must close the player after taking the snapshot (also need to close the player if you push from one screen to another).
2."Error Class Java.lang.ArrayIndexOutOfBoundsException: Index 0>=0"
This error may occur when you access encoding array while encoding array size is zero.
You can ensure this issue by using _videoControl.getSnapshot( null), which take the snapshot in default encoding.
So first insure these issue and reply me.

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.

Resources