简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM