RuntimeException:无法强制转换为android.app.Activity

时间:2016-03-18 04:44:38

标签: java android facebook

我试图开发登录facebook sdk,但我有错误:

java.lang.ClassCastException: com.app.loginsample.MainActivity cannot be cast to android.app.Activity

在MainActivity类中,我写了这个:

public class MainActivity extends Fragment {

private TextView textDetails;

private CallbackManager callbackManager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;

private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {

        AccessToken accessToken = loginResult.getAccessToken();
        Profile profile = Profile.getCurrentProfile();

        displayWelcomeMessage(profile);


    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onError(FacebookException error) {

    }
};


public MainActivity(){


}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    mTokenTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {

        }
    };

    mProfileTracker = new ProfileTracker() {
        @Override
        protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {

        }
    };

    mTokenTracker.startTracking();
    mProfileTracker.startTracking();
}


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.activity_main, container, false);
}

private void displayWelcomeMessage(Profile profile){
    if(profile!=null){
        textDetails.setText("Welcome " + profile.getName());

    }
}


@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);

    loginButton.setReadPermissions("user_friends");
    // If using in a fragment
    loginButton.setFragment(this);
    // Other app specific specialization
    loginButton.registerCallback(callbackManager, callback);

    textDetails = (TextView)view.findViewById(R.id.textView);
}


@Override
public void onResume() {
    super.onResume();

    Profile profile = Profile.getCurrentProfile();
    displayWelcomeMessage(profile);
}

@Override
public void onStop() {
    super.onStop();

    mTokenTracker.stopTracking();
    mProfileTracker.stopTracking();

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackManager.onActivityResult(requestCode, resultCode, data);
    }

}
你能帮帮我吗?谢谢......

0 个答案:

没有答案