Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Threads and Services Threads in Android Extending Thread

Cameron Stewart
Cameron Stewart
18,050 Points

Scoping with Threads

I am not sure how to complete this code challange. If we extend a Thread, how do we pass back the result of twitterClient.update() to the Main activity;

public class MainActivity extends Activity {

public class TwitterThread extends Thread{

    final TwitterClient twitterClient = new TwitterClient();
    @Override
    public void run() {
        twitterClient.update();
    }
}
@Override
public void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);

    TwitterThread t = new TwitterThread();
    t.setName("TwitterThread");
    t.start();
}

}

MainActivity.java
public class MainActivity extends Activity {

    public class TwitterThread extends Thread{

        final TwitterClient twitterClient = new TwitterClient();
        @Override
        public void run() {
            twitterClient.update();
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);

        TwitterThread t = new TwitterThread();
        t.setName("TwitterThread");
        t.start();
    }
}

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

The problem is that you've moved the line defining the twitterClient variable inside the inner class. The code should look like this:

public class MainActivity extends Activity {
    final TwitterClient twitterClient = new TwitterClient();

    @Override
    public void onCreate(Bundle savedInstanceState) {
      setContentView(R.layout.activity_main);

      TwitterThread t = new TwitterThread();
      t.setName("TwitterThread");
      t.start();
    }

    public class TwitterThread extends Thread {
      @Override
      public void run() {
        twitterClient.update();
      } 
    }
}
Cameron Stewart
Cameron Stewart
18,050 Points

Thanks Kourosh!

I didnt understand that Inner classes had scope of the external class :S