0

I am new to java and android and want to understand how this works?

public class MainActivity extends AppCompatActivity {   
    private class  MyThread implements Runnable
    {    
        @Override
        public void run()
        {
            MainActivity.this.runOnUiThread(new Runnable()) {
                @Override
                public void run()
                {
                    loadingSection.setVisibility(View.VISIBLE);
                }
            });
            downloadImageUsingThreads(url);
        }
    }
}

What is MainActivity.this?

MainActivity is a class, so how does MainActivity.this works?

Matthew
  • 7,440
  • 1
  • 24
  • 49
q126y
  • 1,589
  • 4
  • 18
  • 50
  • 3
    http://stackoverflow.com/questions/2411270/when-should-i-use-this-in-a-class – Madhur Feb 20 '16 at 06:54
  • refer http://stackoverflow.com/questions/9656097/this-keyword-in-android – sasikumar Feb 20 '16 at 06:54
  • 1
    Because you're code is running inside the context of `MyThread`, `this` points to the instance of `MyThread`, to allow you to reference the outer class, you need to use `MainActivity.this`, which returns the instance of the outer class – MadProgrammer Feb 20 '16 at 06:55
  • http://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object – Doug Stevenson Feb 20 '16 at 06:56

3 Answers3

2

Java doesn't have pointers. However, Object(s) are implemented with references.

In your example, you have an inner class (MyThread). MyThread is accessing the instance of the outer class (MainActivity) within which it was instantiated.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

MyThread is an inner class of MainActivity, so an instance of MyThread is associated with an instance of MainActivity.

With MyThread code, this refers to the instance of MyThread. To access the instance of MainActivity, you have to qualify it by writing MainActivity.this.

class A {
    int fieldA;

    class B {
        int fieldB;

        void methodB() {
            // This method can be executed for an instance of B,
            // so it can access the fields of B.
            this.fieldB = 13;

            // Since B is a non-static nested class of A,
            // it can also access the fields is A
            A.this.fieldA = 66;
        }
    }

    void methodA() {
        // This method can be executed for an instance of A,
        // so it can access the fields of A.
        this.fieldA = 42;

        // In order to create an instance of class B, you need
        // and instance of class A. This is implicitly done here.
        new B(); // The new B object is associated with the A
                 // object defined by 'this'.
    }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

What is MainActivity.this?

the keyword this is indicating that you are passing as argument the actual instance of a class,

which class?: the MainActivity class

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97