I’m very new to Java and I’m attempting to write an android app and going through the facebook api. I’m looking at this page, specifically, this
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
This work just fine, I’m just trying to understand how. I’m not understanding the method in a method and more specifically, how would I extract this if I wanted to write it differently?
I tried creating another class
public class FaceBookCallbackLogin implements FacebookCallback<LoginResult> {
@Override
public void onSuccess(LoginResult loginResult) {
....
}
@Override
public void onCancel() {
}
and tried to initiate the login from my MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
info = (TextView)findViewById(R.id.info);
loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FaceBookCallbackLogin());
}
but, this never calls the onSuccess method in FaceBookCallbackLogin, and I can’t call it explicitly because I don’t have the param LoginResult.
So, how would i write this so I can have the login in a different class? In the original code, where is the param for onSuccess – LoginResult – coming from?
2
Answers
Okay, So the Javadocs say
A benefit of the above is it allows you to be precise about your definition for a particular interface implementation without having to go through the hassle of creating new classes for each implementation. Look at the example below.
Notice how I am implementing the same
saySomething
method differently without having to create two separate classes (class files) for each implementation. I am almost inlining the implementation of the class.From an Android perspective this is very useful, imagine having to create a separate class for your click listeners. It is still possible, however it is much more simple and readable to create a simple anonymous inner-class for your implementation of your click-listener
Is much simpler to read and understand than creating a new class that implements View.OnClickListener like below
The way you have changed from anonymous inner class to separate class looks just fine.
However, in first example you have done this:
In second example you have done this:
Maybe that is the problem..