Passing "This", but not really So i am developing an Android application as a side project/hobby and I have come across the situation that I have to pass an Activity into a method for use a context (Don't question it)

The problem here is that I have to pass it into a PreferenceOnClickListener and so I am unable to use this. I have come up with the following code snippet, that you all might just wanna stab me for writing... Sorry, I feel bad for creating this as well:

Preference rebuildDB = pf.findPreference(getString(R.string.preference_rebuildDatabase));
    Activity thisContext = this;
    rebuildDB.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            SongLoader.generateXml(thisContext);
            return true;
        }
    });


The thing I don't like is setting thisContext to the value of this, so my question is the following:

Is this really as bad as I think it is, and is there any better way to achive it?
You can do it in 2 way.

The first is by implementing the interface on your main class, so you don't have to create an anonymous class on the fly but just pass your this.

UPDATE

Here is an example on how to do it:

public class MyActivity extends AppCompatActivity
                        implements Preference.OnPreferenceClickListener {


        // You implement the listener method in your main 
        // class, so you just pass the current this object
        @Override
        public boolean onPreferenceClick(Preference preference) {
           SongLoader.generateXml(this);
           return true;
        }

        // ... other code

       // when you record the listener your main class is the
       // listener now.
       rebuildDB.setOnPreferenceClickListener(this);

}


The second is by creating a specific class that implement the interface.

This class is going to take in the constructor a parameter that is an instance of your main class.

So you will pass a new instance of this class instead of an instance of an anonymous class.

Here is an example of what I mean.

private static class MyOnPreferenceClickListener implements Preference.OnPreferenceClickListener {

    MyActivity myActivity;

    public MyOnPreferenceClickListener(MyActivity myActivity) {
        this.myActivity = myActivity;
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        SongLoader.generateXml(myActivity);
        return true;
    }
}


I defined private and static considering to declare this class inside your main class.

UPDATE

The fist method is the quick and fast way, not considering the anonymous listener class, but could drive on very fat classes implementing many different listeners, depends on the Activity you're writing.

The second method, helps to decouple the listeners from your business code, and organize it in a better way.