Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
New Developer
corgan1003
Posts: 15
Registered: ‎09-01-2008
My Device: Not Specified

NullPointerException in a strange place

I get a nullpointer exception in when I try to initialize one HttpConnection.  Here is the code:

 

... 

synchronized(this){
                    //open the connection
                    HttpConnection c = null;
                    try{
                        

                         //NULL POINTER EXCEPTION HAPPENS ON LINE BELOW

                        c = (HttpConnection)Connector.open(getUrl());
                       
                        c.setRequestMethod(HttpConnection.GET);
                        c.setRequestProperty("User-Agent", "BlackBerry/3.2.1");
                        c.setRequestProperty("Content-Language", "en-US");
                       
                        System.exit(0);

 

... 

 

This is strange because I had this working before and the only thing I changed was UI stuff.  If I put a System.exit(0) above the line, the program just quits as expected.  If I put it below the line, I get a nullpointer exception.  getUrl() is not an issue because I replaced that with "http://www.google.com" and still get the same results.

 

Any help would be great because I am not sure why this would cause a nullpointer since you cannot instantiate HttpConnection.

 

Thank you,

 

Tony 

Developer
peter_strange
Posts: 19,609
Registered: ‎07-14-2008
My Device: Not Specified

Re: NullPointerException in a strange place

Like you, I can't quite see how you get a null pointer exception on the line you indicated.

 

Can you tell us if you see this on the Sim or on the device,  Also can you confirm the JDE Level you are using and the OS Level of the device.  The OS Level of the device should be >= the JDE Level. 

 

I would recode the lines to try to work it out exactly where the null pointer exception is coming from, say like

String url = getUrl()); System.out.println(url); Connection co = Connector.open(url); System.out.println(co.toString()); c = (HttpConnection) co; System.out.println(c.toString());

 


Sorry can't be of more help. 

 

I'm a little curious as to why you need to d this processing in a synchronized block, especially when you are synchronized on (this).  Can you explain why this is necessary?

 

 

New Developer
corgan1003
Posts: 15
Registered: ‎09-01-2008
My Device: Not Specified

Re: NullPointerException in a strange place

Thank you for the reply.  From the BlackBerry Developer Guide...

Use a synchronized block to wrap the code for opening the connection and retrieving data. This
action is not necessary for this example, but it is good practice in most applications so that
subsequent fetch requests are not missed while received data is processed.

 

So I may not need this code now, but I like to practice good programming techniques...especially when its laid out for me very specifically.

 

I separated the code a bit as you suggested.  And found the NullPointerException is in a stranger place than I expected.  I am posting a bit more of my code now in hopes to get some more vaulable feedback.  I put comments in all caps to show where the exception is thrown.  I do not understand how a pointer could be null in that spot.  Any ideas? (Let me know if you want to see more code.  I try to post the least amount possible while exposing the problem so that people don't have to dig through too much of my code)

 

Here it is:

 

private class ConnectionThread extends Thread{
        private static final int TIMEOUT = 500; //ms
   
        private volatile boolean _start = false;
        private volatile boolean _stop = false;
   
        private String _url;
   
        public void fetch(String url){
            _url = url;
            _start = true;
        }
   
        public void stop(){
            _stop = true;
        }
       
        public synchronized String getUrl(){
            return _url;
        }      
   
        public void run(){
            //infinite loop
            for(;:smileywink:{
                //while no connections are open and thread has not been stopped
                //put thread to sleep to save cpu cycles
                while( !_start && !_stop ){
                    try{
                        sleep(TIMEOUT);
                    }catch (InterruptedException e){
                        System.err.println(e.toString());
                    }
                }
               
                if(_stop) return; //exit thread on stop
               
                //at this point _start has to be true so we process request
                synchronized(this){
                    //open the connection
                    HttpConnection c = null;
                    try{
                        //System.exit(0);
                        //c = (HttpConnection)Connector.open(getUrl());
                       

                        //IF I EXIT THE PROGRAM HERE, NO EXCEPTION IS THROWN

                        String temp_url = getUrl();

                        //BUT IF I EXIT HERE, A NULLPOINTER EXCEPTION IS THROWN

                     
                        System.out.println(temp_url);
   
                        Connection co = Connector.open(temp_url);
                        System.out.println(co.toString());
                       
                        c = (HttpConnection) co;
                        System.out.println(c.toString());
                       
                        c.setRequestMethod(HttpConnection.GET);
                        c.setRequestProperty("User-Agent", "BlackBerry/3.2.1");
                        c.setRequestProperty("Content-Language", "en-US");
                       
                        InputStream istream = c.openInputStream();
                       
                        byte[] data = new byte[256];
                        int len = 0;
                        StringBuffer raw = new StringBuffer();
                       
                        //grab data in 256 byte chunks
                        while( -1 != (len = istream.read(data)) ){
                            //raw.append(new String(data, 0, 256));
                            raw.append(new String(data, 0, len));
                        }
       
                        //convert data to a string
                        String text = raw.toString();
                        //display the string
                        updateContent(text);
                        istream.close();
                        c.close();
                       
                    } catch (IOException e){
                        System.err.println(e.toString());
                        //updateContent(e.toString());
                    } catch (Exception e){
                        System.err.println(e.toString());
                        //updateContent(e.toString());
                    }/*finally{
                        if(istream != null)
                            istream.close();
                        if(c != null)
                            c.close();
                    }*/
                    //indicate the connection is finished
                    _start = false;
                }
            }//end infinite loop 
        }//end run()   
    }//End class ConnectionThread 

 

 Thank you!

Developer
marchywka
Posts: 1,415
Registered: ‎07-30-2008
My Device: Not Specified

Re: NullPointerException in a strange place

I'm not sure what you meant about replacing the geturl() with a hardcoded thing but have you tried

printStackTrace() on the error? I can't see how it would matter but there is an implicit derference

of "this" on your call but it is unlikely to be null...

 

Is there any reason your url member isn't volatile? I have noticed the compiler warnings tend to reflect

a lot of optimization, maybe the RIM people actually respect a volatile declaration :smileyhappy: An NPE

in a non-volatile member would make sense here.

 

Also, I almost never use synchronized methods as explicit synchronization on something is usually

better but you can look here for one example,

 

http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html

 

Nested sync blocks without a purpose are a good way to slow things down and get deadlock.  

 

 

Developer
peter_strange
Posts: 19,609
Registered: ‎07-14-2008
My Device: Not Specified

Re: NullPointerException in a strange place

I've reviewed the Dev Guide and I see you have pretty much got a copy of the code from there.  I don't understand why they have synchronized the block, nor why they have synchronized the getURL.  Neither has any value as far as I can see.  I'm going to raise this as a question later, but for now I'd like to try to replicate your problem.

 

Can you change.

String temp_url = getUrl();

 

to the following:

String temp_url = _url;

temp_url = getUrl();

 

and tell me which line you see the problem on. 

 

If you see the problem on the second line and not the first, I would take out the synchronized on the block and the getURl and try it again (just for testing purposes). 

 

Can you let us know what level of JDE you are using and if you are seeing the problem on the simulator or on the device.  If you are seeing the problem on the Device, I presume the OS Level is >= the JDE level you are using.  Please tell us what device and what OS Level.  I want to use these details to try to replicate what you see,

Developer
marchywka
Posts: 1,415
Registered: ‎07-30-2008
My Device: Not Specified

Re: NullPointerException in a strange place

The fetch method needs to be synchronized or atomic aroudn the two asignments as the compiler is free to first reorder the assignments

and second to keep the url assignment private the the calling thread.

 

 

http://java.sun.com/docs/books/jls/third_edition/html/memory.html

New Developer
corgan1003
Posts: 15
Registered: ‎09-01-2008
My Device: Not Specified

Re: NullPointerException in a strange place

OK, so a lot to respond to here.  I cannot get a normal debugging enviroment working which is why I am using System.exit(0) placements to debug.  Basically, I have waited 5 minutes for the debugger to finish loading and it just does not.  So I do not think I can view System prints and therefor stack traces.  All the work I am doing here is on a simulator with JRE 1.5.0_16-b02. 

 

I am glad you saw what I saw in the dev guide.  Kinda sucks that it is apparently not a great example but it is what many developers reference.  When I change my one getURL() line to the two lines you have requested, I actually end up getting the NPE before either are called.  So now I am pretty sure the problem lies in synchronization.  However, the odd thing is that this was totally working before and I made only UI changes. 

 

With regards to your third response, I do not see how the compiler could reorder the assignments in fetch.  I really do not understand your third response.  I am going to read the two articles you sent, it has been a while since i have done synchronization.  But if you could explain your third response a little better, and maybe give a coding hint, that would be much appreciated....

 

But keep in mind the test I just performed where now the NPE comes before interaction with the _url variable (not before fetch though).

 

Thank you so much again!

Developer
marchywka
Posts: 1,415
Registered: ‎07-30-2008
My Device: Not Specified

Re: NullPointerException in a strange place

Eh, I hate to ask but are you sure this thread is the one throwing? I did notice your catches aren't annotated in anyway.

 

Generally you use sync blocks to get something to behave atomiclly. In the absence of syn and volatile,

the compiler can do anything that you can't see and timing is nothing ( to negate the old phrase). Normally you

can get away with it as reordering wouldn't be very common and writes to main storage pretty much occur

all the time but it is something to consider.

 

Developer
peter_strange
Posts: 19,609
Registered: ‎07-14-2008
My Device: Not Specified

Re: NullPointerException in a strange place

[ Edited ]

Can you confirm the level of JDE you are using and where you see the problem (Simulator or device). 

 

I am very concerned that you are not able to debug, that indicates a serious compatibility problem.  I suspect your NPE may just be a symptom of that.

 

Also marchywka has a very good point.  Because you issue a System.exit(0), you are closing this and all the associated Threads/User Interface actions etc. etc.  I think we need to get you debugging properly rather than using System.exit(0) as a debugging tool.

Message Edited by peter_strange on 09-11-2008 08:07 PM
New Developer
corgan1003
Posts: 15
Registered: ‎09-01-2008
My Device: Not Specified

Re: NullPointerException in a strange place

OK, my JDE is 4.5.0.7

I thought you meant JRE...sorry.

 And this is on the simulator so no worries about the BB OS...yet

 

Also, I found the NPE, and I feel REALLY stupid.  The code was in my main screen constructor.  I had this:

 

Object[] playlistChoices;

playlistChoices = new Object[3];

ObjectChoiceField PlaylistSelector =  new ObjectChoiceField("", playlistChoices, 0);

add(PlaylistSelector);

 

The problem is that it wanted something like this:

 

Object[] playlistChoices;

playlistChoices = new Object[3];

playlistChoices[0] = "0";

playlistChoices[0] = "1"; 

playlistChoices[0] = "2"; 

ObjectChoiceField PlaylistSelector =  new ObjectChoiceField("", playlistChoices, 0);

add(PlaylistSelector);

 

So my guess is that I needed to allocate space for each string in the array?  I thought "new Object[3]" did this.  This is very strange to me.

 

I am not realy sure what to do about the debugging environment...but I am also super worried about that as this application develops.

 

Thanks for all your help and any suggestions regarding the debugging environment would be greatly appreciated.