Sagar Duhan
Sagar Duhan

Reputation: 257

How can I automatically use the name of the class?

In the code below what can I write instead of Play.this so that it could automatically use the name of the class in which it is used without the need to write the name (in this case "Play") AlertDialog.Builder builder = new AlertDialog.Builder(Play.this);

Upvotes: 0

Views: 109

Answers (3)

Lucas Ferraz
Lucas Ferraz

Reputation: 4152

There are other things to think before set the context (this).

First case - If you are in a class that extends a context in its base like Activity/Services, and you are NOT in a inner class, you can use just "this"

Second - If you are in a class that extends a context in its base like Activity/Services, and you are in a inner class, you can use (Play.this), because the "this" in this case, is about the inner class.

Third - If you are in another class that does not have a context, you can pass it in constructor or method like:

class Test {
   public void createBuilder(Context context) {
      AlertDialog.Builder builder = new AlertDialog.Builder(context);
   }
}

Upvotes: 1

Martin Häusler
Martin Häusler

Reputation: 7244

I think what you are looking for is this.getClass().getName(). If you want just the unqualified name, use this.getClass().getSimpleName() instead. I know very little about Android specifically, but that's how you would do it in Java in general.

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

There's no reason to use Play.this in code being part of Play class. Just use this:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

However if you want to do that from your inner class, then you need this will not point to Context subclass, so you can i.e. create member in your parent class, i.e.:

Context mContext;

initialize it in i.e. onCreate():

mContext= this;

and use mContext from your listener's code

AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

Upvotes: 1

Related Questions