简体   繁体   中英

Get Activity (this) inside setOnClickListener

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.

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.

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.

您可以创建一个Context实例并将其在侦听器外部初始化为this ,然后只需在需要的地方调用它

The above solution should work perfectly fine but still adding some flavors in it. Thought it will be helpful for someone to understand better.

public class SampleActivity extends AppCompatActivity {

private Context sampleActivityContext; 
private Button continueButton;
// All your class level variables/fields declared in this section

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sampleActivityContext = this; // Assigning the current activity(i.e.,) SampleActivity context
    .......
    continueButton = findViewById(R.id.continueButton); // Map the UI element from the XML to the corresponding java element
    .......  
   // Setting the onclick listener for the button 
    continueButton.setOnClickListener(new View.onClickListener() {
 @Override
  public void onClick(View view) {
 // When you need the context of the activity use sampleActivityContext 
 // instead of this keyword as this will refer the current view/button within the section 
// or you can prefer SampleActivity.this as well 

} 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM