bardao
bardao

Reputation: 954

Java, getting a null value after starting a thread

I am trying to run this code in my android application in a non GUI related class.

Thread connection = new Thread(new Runnable() {
                public void run() {
                    try {
                        streamSource = new StreamSource(conn.getInputStream());
                        writer = new CharArrayWriter();
                        StreamResult streamResult = new StreamResult(writer);
                        TransformerFactory factory = TransformerFactory.newInstance();
                        Transformer transformer = factory.newTransformer();
                        transformer.transform(streamSource, streamResult);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
              });
        connection.start();

The issue is that when I call writer, I am getting a null value. Writer is defined as a static global variable as well as streamSource. I'm not good with threads and this seems like my main thread is not seeing that my writer is created.

Any help?

Upvotes: 0

Views: 625

Answers (2)

Davor Pecet
Davor Pecet

Reputation: 171

Start your thread after you have initilized the writer object. If you need both threads runing at the same time, then the easy way is to run a while loop checking if writer != null with Thread.sleep on every iteration

Upvotes: 0

THarms
THarms

Reputation: 311

Your variable Writer is in another class (thread) therefor you do not have access to it. It is static, that's the cause of being able to access it theoretically, But it is not initialized to the other thread.

Please create the variable where you need it - or "outsource" the complete action taking place there.

EDIT : http://developer.android.com/guide/components/processes-and-threads.html Here is some information about Threads and processes in Android.

Upvotes: 1

Related Questions