您好。我想将facebook sdk添加到我的应用程序以进行授权/登录。我注册我的应用程序,测试 - 所有工作,直到我添加权限(用于电子邮件),现在我导致NullPointerException - 代码:
private void startFacebookLogin() {
Session.StatusCallback mCallback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
Log.d("FACEBOOK", "onCompleted()");
final GraphUser graphUser = user;
if (user != null) {
final Intent intent = new Intent(RegisterActivity.this, AboutYourselfActivity.class);
intent.putExtra(NAME, graphUser.getName());
intent.putExtra(EMAIL, (String) graphUser.asMap().get(EMAIL));
intent.putExtra(USER_SOCIAL_ID, graphUser.getId());
intent.putExtra(PROVIDER, FACEBOOK);
intent.putExtra(PASSWORD, "");
intent.putExtra(PHONE, "");
Log.d("FACEBOOK USER ", graphUser.getName());
Log.d("FACEBOOK USER ", graphUser.getId());
Log.d("FACEBOOK USER ",(String) graphUser.asMap().get(EMAIL));
RegisterActivity.this.startActivity(intent);
//RegisterActivity.this.finish();
URL img_value = null;
try {
img_value = new URL("http://graph.facebook.com/" + user.getId() + "/picture?type=small");
BitmapLoaderTask task = new BitmapLoaderTask(new DownloadComplete() {
@Override
public void complete() {
}
});
task.execute(img_value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
} else {
Log.d("FACEBOOK", "hmm " + session.getState().toString());
}
}
};
Session.OpenRequest request = new Session.OpenRequest(RegisterActivity.this);
request.setPermissions(Arrays.asList("email", "user_birthday"));
request.setCallback(mCallback );
// get active session
Session mFacebookSession = Session.getActiveSession();
if (mFacebookSession == null || mFacebookSession.isClosed())
{
mFacebookSession = new Session(RegisterActivity.this);
}
mFacebookSession.openForRead(request);
}
我崩溃了
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); // here I cath crash
}
}
日志:
FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {com.DriverNotes.AndroidMobileClientTest/com.DriverNotes.AndroidMobileClientTest.RegisterActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3406)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3449)
at android.app.ActivityThread.access$1200(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1328)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.DriverNotes.AndroidMobileClientTest.RegisterActivity.onActivityResult(RegisterActivity.java:300)
at android.app.Activity.dispatchActivityResult(Activity.java:5456)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3402)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3449)
at android.app.ActivityThread.access$1200(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1328)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
try this
private void performFacebookLogin()
{
Log.d("FACEBOOK", "performFacebookLogin");
final Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, Arrays.asList("email"));
Session openActiveSession = Session.openActiveSession(this, true, new Session.StatusCallback()
{
@Override
public void call(Session session, SessionState state, Exception exception)
{
Log.d("FACEBOOK", "call");
if (session.isOpened() && !isFetching)
{
Log.d("FACEBOOK", "if (session.isOpened() && !isFetching)");
isFetching = true;
session.requestNewReadPermissions(newPermissionsRequest);
Request getMe = Request.newMeRequest(session, new GraphUserCallback()
{
@Override
public void onCompleted(GraphUser user, Response response)
{
Log.d("FACEBOOK", "onCompleted");
if (user != null)
{
Log.d("FACEBOOK", "user != null");
org.json.JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String email = graphResponse.optString("email");
String id = graphResponse.optString("id");
//String facebookName = user.getUsername();
System.out.println("Birthday--------------"+user.getBirthday());
System.out.println("User ID----------------"+user.getId());
System.out.println("LINK---------------------"+user.getLink());
System.out.println("username---------------"+user.getUsername());
System.out.println("Hashcode----------------"+user.hashCode());
System.out.println("Inner JSON--------------"+user.getInnerJSONObject());
System.out.println("Location-------------------"+user.getLocation());
System.out.println("class------------------------"+user.getClass());
System.out.println(user.getProperty("email"));
if (email == null || email.length() < 0)
{
System.out.println(
"Facebook Login"+
"An email address is required for your account, we could" +
" not find an email associated with this Facebook account. Please associate a email with this account or login the oldskool way.");
return;
}
}
}
});
getMe.executeAsync();
}
else
{
if (!session.isOpened())
Log.d("FACEBOOK", "!session.isOpened()");
else
Log.d("FACEBOOK", "isFetching");
}
}
});
}
答案 1 :(得分:2)
试试这个:
List<String> permissions = Arrays.asList("public_profile", "user_birthday", "email");
Session session = Session.openActiveSession(this, false, permissions, statusCallback);
if(session == null) {
session = Session.openActiveSession(this, true, permissions, statusCallback);
Session.setActiveSession(session);
//Log.e("session2 ", "session " + session.getAccessToken());
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest((Activity) v.getContext()).setCallback(statusCallback));
}
}
else
{
//DO WHATEVER YOU HAVE TO DO Session.getActiveSession().getAccessToken() should exist
}
private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state, Exception exception) {
// Respond to session state changes, ex: updating the view
Log.e("session", "session " + session.getAccessToken() + " state: " + state.isOpened());
}
}
抱歉,创建一个公共实例变量:
private Session.StatusCallback statusCallback = new SessionStatusCallback();
答案 2 :(得分:1)
我使用了此代码,现在已授权
List<String> permissions = new ArrayList<String>();
permissions.add("email");
permissions.add("user_photos");
//start Facebook session
openActiveSession(this, true, new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
//make request to the /me API
Log.e("sessionOpened", "true");
Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Work with user (get name, email and other)
}
}
}).executeAsync();
}
}
}, permissions);
答案 3 :(得分:-1)
谢谢你的帮助。现在一切正常,代码:
private static Session openActiveSession(Activity activity, boolean allowLoginUI, Session.StatusCallback callback, List<String> permissions) {
Session.OpenRequest openRequest = new Session.OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = new Session.Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
private void startFacebookLogin() {
List<String> permissions = new ArrayList<String>();
permissions.add("email");
//start Facebook session
openActiveSession(this, true, new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
//make request to the /me API
Log.e("sessionOpened", "true");
Request.newMeRequest(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String firstName = user.getFirstName();
String lastName = user.getLastName();
String id = user.getId();
String email = user.getProperty("email").toString();
final Intent intent = new Intent(RegisterActivity.this, AboutYourselfActivity.class);
intent.putExtra(NAME, user.getName());
intent.putExtra(EMAIL, user.getProperty("email").toString());
intent.putExtra(USER_SOCIAL_ID,user.getId());
intent.putExtra(PROVIDER, FACEBOOK);
intent.putExtra(PASSWORD, "");
intent.putExtra(PHONE, "");
DatabaseManager.getInstance(RegisterActivity.this).
setProperty(FACEBOOK_USER_NAME, user.getName());
DatabaseManager.getInstance(RegisterActivity.this).
setProperty(FACEBOOK_USER_EMAIL, user.getProperty("email").toString());
DatabaseManager.getInstance(RegisterActivity.this).
setProperty(FACEBOOK_USER_ID, user.getId());
Log.e("facebookId", id);
Log.e("firstName", firstName);
Log.e("lastName", lastName);
Log.e("email", email);
}
}
}).executeAsync();
}
}
}, permissions);