0

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?

4
  • Are you sure that the started thread have had time to initialize writer before you read it? Commented Jan 24, 2013 at 11:53
  • how do i make sure? should i wait before starting my thread? Commented Jan 24, 2013 at 11:56
  • Have you tried Class.writer = new CharArrayWriter() ? Commented Jan 24, 2013 at 11:58
  • So you defined writer as a static global and trying to initialize it within the thread? Bad idea. Define in within the thread. Or define it once if you want to share and sure that object is thread safe. Commented Jan 24, 2013 at 12:01

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.