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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With