我是FB SDK for android的新手。我按原样跟踪了示例教程。但是我收到了这个错误:
这是MainFragment.class的代码:
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private TextView userInfoTextView;
private Button shareButton;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
authButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "email"));
// This opens a webview to type your email/username and password
//authButton.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
shareButton = (Button) view.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
publishStory();
}
});
return view;
}
private String buildUserInfoDisplay(GraphUser user) {
StringBuilder userInfo = new StringBuilder("");
// Example: typed access (name)
// - no special permissions required
userInfo.append(String.format("Name: %s\n\n",
user.getName()));
// Example: typed access (birthday)
// - requires user_birthday permission
userInfo.append(String.format("Firstname: %s\n\n",
user.getInnerJSONObject() ));
userInfo.append(String.format("Username: %s\n\n",
user.getUsername()));
userInfo.append(String.format("ID: %s\n\n",
user.getId()));
userInfo.append(String.format("Email: %s\n\n",
user.asMap().get("email")));
userInfo.append(String.format("Gender: %s\n\n",
user.asMap().get("gender") ));
return userInfo.toString();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
uiHelper.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
//private boolean isLoggedIn = false; // by default assume not logged in
@SuppressWarnings("deprecation")
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
//isLoggedIn = true;
userInfoTextView.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
// Display the parsed user info
userInfoTextView.setText(buildUserInfoDisplay(user));
}
});
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
//isLoggedIn = false;
userInfoTextView.setVisibility(View.INVISIBLE);
shareButton.setVisibility(View.INVISIBLE);
}
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", "Facebook SDK for Android");
postParams.putString("caption", "Build great social apps and get more installs.");
postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
我刚刚在StackOverflow上检查了所有类似于我的问题,但我没有找到解决我问题的问题。有任何想法吗?我很乐意感谢你的帮助。感谢。
答案 0 :(得分:0)
这是旧版本(已弃用)。你面临的问题是,你已经开始了一个会话而你正在申请一个新的会议。尝试以下示例(不经过弃用),这可能对您有所帮助。
在OnResume()中,我提到Session session = Session.getActiveSession();
获取活动会话而不是请求新会话。这可能会解决您的会话管理问题。
package com.example.integration;
import java.util.Arrays;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class MainActivity extends Activity {
private LoginButton fbLoginBtn;
private SharedPreferences mPrefs;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fbLoginBtn = (LoginButton) findViewById(R.id.fb_login_button);
fbLoginBtn.setReadPermissions(Arrays.asList("email"));
mPrefs = getPreferences(MODE_PRIVATE);
}
@Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Editor edit = mPrefs.edit();
edit.putString("access_token", session.getAccessToken());
edit.putString("expires", session.getExpirationDate() + "");
edit.commit();
Request.executeMeRequestAsync(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 = (String) user.asMap().get("email");
Log.i("facebookid", id);
Log.i("firstName", firstName);
Log.i("lastName", lastName);
Log.i("AccessToken", session.getAccessToken());
Log.i("Email", email);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("name", firstName);
startActivity(intent);
}
}
});
}
else if (state.isClosed()) {
Toast.makeText(this, "Please Login", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(MainActivity.this, requestCode, resultCode, data);
}
}