Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Activity (this) inside setOnClickListener

Tags:

java

android

I'm new in java and android development and I have one issue, let me explain. I have custom interface and custom class which use this as a listener.

In my HomeActivity I call method on my custom class and the class respond via listeners (interface), this is short version:

public class HomeActivity extends Activity implements WebClientResponseListener {
    private User user;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //....
        // I call my class and add this as a listener:
        MyWebServiceClient mws = new MyWebServiceClient(getApplicationContext());
        mws.getProducts(this.user.getToken(), this)
    }
    //....
    @Override
    public void onDataDownloadSuccess(JSONObject jsonObject) {
        Log.d("DATA", "SUCCESS");
    }
}

When I run it like that everything works fine. The onDataDownloadSuccess method is called and I can see log output.

The issue appears when I try to run it from OnClickListener:

private void sendRequest() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(getString(R.string.request_info_title));
    builder.setItems(items, this);
    //.....
    builder.create().show();
}

Later in the same activity I have:

public void onClick(DialogInterface dialogInterface, int which) {
    MyWebServiceClient mws = new MyWebServiceClient(getApplicationContext());
     mws.getProducts(user.getToken(), this)
}

In this situation my listener onDataDownloadSuccess method is not called. I can see in in the console:

unregisterIRListener() is called

and

GC_FOR_ALLOC freed 1613K, 35% free 13400K/20408K, paused 18ms, total 18ms

I was looking for the solution on line and I've already tried some stuff for example:

//in OnClick
mws.getProducts(user.getToken(), HomeActivity.this);

I created private variable HomeActivity and in onCreate I call

homeActivity = this;

and later in onClick I was trying to pass homeActivity instead of this but with no luck. Thanks in advance.

like image 470
Greg Avatar asked Mar 05 '14 11:03

Greg


2 Answers

always try to use YOUR_ACTIVITY_NAME.this because when you use only "this", it point to the current context . let say you are in OnClickListener , it is an anonymous class so, when you use this inside this. it will point to the button not to the activity. Therefore, you need to point towards activity by using activityname.this.

like image 110
Waqar Ahmed Avatar answered Oct 01 '22 16:10

Waqar Ahmed


As you need context and not activity, variable needs to be:

Context homeActivity;

or

Context context;  

Then in onCreate()

context=this; 

use that context or homeActivity in your activity or HomeActivity.this

Inside the click listener, "this" is a reference for the click listener.

like image 39
Pararth Avatar answered Oct 01 '22 16:10

Pararth