I am building an app where I am trying to integrate facebook. When I am using device of android 2.3.3 its working fine and i am able to post message. But when I am running that same app in android 4.1 then it showing "failed to post".I am using facebook-sdk version 3.6.0
My code as below
FacebookActivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook);
btnPostStatus = (Button) findViewById(R.id.mBtnPostStatus);
edtPost = (EditText) findViewById(R.id.post_text);
edtPost.setText(messageToPost);
btnPostStatus.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View arg0) {
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
messageToPost = edtPost.getText().toString();
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall(messageToPost);
}
}
});
}
#SuppressWarnings("deprecation")
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY,
Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
#SuppressWarnings("deprecation")
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext()
.getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#SuppressWarnings("deprecation")
public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new LoginDialogListener());
}
#SuppressWarnings("deprecation")
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
}
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null) {
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
}
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
.show();
}
}
It not showing any exception, but not able post
Is there any good fb integration tutorial which using latest facebook sdk version ?
Actually I solved my problem. When I am setting a target-sdk version in my manifest.xml then its working for lower version android device but its not working for my jelly bean android device.
So when I remove target-sdk version then its working properly in jelly bean device also .
Related
I try to write a Facebook Login for my Android App. Strange, it's working fine in the Pixel Emulator. On a real device I am getting a "Login Error, please try again later".
I implemented the following class so far:
'''
public class FacebookLoginManager implements FacebookCallback, GraphRequest.GraphJSONObjectCallback {
private static final String mTAG = FacebookLoginManager.class.getSimpleName();
private final Activity mActivity;
private final CallbackManager mFacebookCallbackManager;
private final IFBSignInListener mIFBSignInListener;
private final LoginManager mLoginManager;
FacebookLoginManager(Activity activity, IFBSignInListener iFBSignInListener) {
mActivity = activity;
mIFBSignInListener = iFBSignInListener;
mFacebookCallbackManager = CallbackManager.Factory.create();
mLoginManager = LoginManager.getInstance();
}
public void logIn() {
mLoginManager.logInWithReadPermissions(mActivity, Arrays.asList("public_profile" /*picture, name, gender, code*/, "email", "user_birthday"));
mLoginManager.registerCallback(mFacebookCallbackManager, this);
}
public void logOut() {
if (null != mLoginManager) {
mLoginManager.logOut();
}
}
public CallbackManager getmFacebookCallbackManager() {
return mFacebookCallbackManager;
}
private void newMeGraphRequest() {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), this);
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,picture,gender,birthday"); // to reduce the response payload for performance reasons
request.setParameters(parameters);
request.setGraphPath("oauth/access_token");
request.executeAsync();
}
private boolean isFacebookSuccessfullyLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return (accessToken != null && !accessToken.isExpired());
}
#Override
public void onSuccess(LoginResult loginResult) {
if (isFacebookSuccessfullyLoggedIn() && null != mIFBSignInListener) {
mIFBSignInListener.showProgressDialog();
newMeGraphRequest();
}
Log.e(mTAG, "Facebook Login Success!");
}
#Override
public void onCancel() {
if (null != mIFBSignInListener) {
mIFBSignInListener.hideProgressDialog();
}
Log.e(mTAG, "Login Cancelled!");
}
#Override
public void onError(FacebookException error) {
Log.i("info", "error has occured " + error.toString());
if (error instanceof FacebookAuthorizationException) {
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
}
Toast.makeText(mActivity, "Internet Connection Error!", Toast.LENGTH_SHORT).show();
if (null != mIFBSignInListener) {
mIFBSignInListener.hideProgressDialog();
}
Log.e(mTAG, "Error : " + error.toString());
}
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (null != mIFBSignInListener) {
mIFBSignInListener.saveSharedPreference(object);
mIFBSignInListener.sendToServer(object);
mIFBSignInListener.hideProgressDialog();
mIFBSignInListener.startActivity();
}
}
}
'''
I use the framework to create a video messenger between Android and IOS.
To do: in iOS session is created and the user is called, which enters with the Android device.
But during the call, before making a call on android - android application crashes.
Maybe someone faced the such? Or what am I doing wrong? I do not understand how to handle the incoming call ... (
My code for Android device
onCreate(...){
QBSettings.getInstance().fastConfigInit(APPLICATION_ID,AUTHORIZATION_KEY,AUTHORIZATION_SECRET);
}
public void createSessionButton(View view){
//Log.d("Tag","onSuccess");
QBAuth.createSession(currentUser,new QBEntityCallbackImpl<QBSession>() {
#Override
public void onSuccess(QBSession session, Bundle params) {
currentUser.setId(session.getUserId());
Log.d("Tag","call set id success");
QBChatService chatService;
if (!QBChatService.isInitialized()) {
Log.d("Tag","QBChatService do not initialize");
QBChatService.init(getApplicationContext());
}
chatService = QBChatService.getInstance();
Log.d("Tag","QBChatService initialize");
// LOG IN CHAT SERVICE
chatService.login(currentUser, new QBEntityCallbackImpl<QBUser>() {
#Override
public void onSuccess() {
runOnUiThread(new Runnable() {
#Override
public void run() {
processTextView.setText("LOG IN CHAT SERVICE onSuccess");
}
});
//processTextView.setText("LOG IN CHAT SERVICE onSuccess");
Log.d("Tag","LOG IN CHAT SERVICE onSuccess");
}
#Override
public void onError(List errors) {
Log.d("Tag","LOG IN CHAT SERVICE onError");
}
});
}
#Override
public void onError(List<String> errors) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Важное сообщение!")
.setMessage("onError")
//.setIcon(R.drawable.ic_android_cat)
.setCancelable(false)
.setNegativeButton("ОК",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public void createSignalingManager(View view) {
QBChatService.getInstance().getVideoChatWebRTCSignalingManager().addSignalingManagerListener(new QBVideoChatSignalingManagerListener() {
#Override
public void signalingCreated(QBSignaling qbSignaling, boolean b) {
if (!b) {
QBRTCClient.getInstance().addSignaling((QBWebRTCSignaling) qbSignaling);
runOnUiThread(new Runnable() {
#Override
public void run() {
processTextView.setText("addSignalingManagerListener");
}
});
}
}
});
// Add activity as callback to RTCClient
QBRTCClient.getInstance().addSessionCallbacksListener(this);
QBRTCClient.getInstance().addConnectionCallbacksListener(this);
QBRTCClient.getInstance().addVideoTrackCallbacksListener(this);
QBRTCClient.getInstance().prepareToProcessCalls(this);
}
My code in iOS
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[QBRTCClient.instance addDelegate:self];
[[QBChat instance] addDelegate:self];
[QBRTCConfig setDisconnectTimeInterval:10];
self.callTestButton.hidden = YES;
}
#pragma mark - Action
- (IBAction)loginAction:(id)sender {
QBUUser* currentUser = [[QBUUser alloc] init];
currentUser.password = pass;
currentUser.login = login;
// connect to Chat
[[QBChat instance] connectWithUser:currentUser completion:^(NSError * error) {
NSLog(#"Error: %#", error);
}];
[QBRequest logInWithUserLogin:login password:pass successBlock:^(QBResponse *response, QBUUser *user) {
NSLog(#"logInWithUserLogin:");
[QBRequest usersWithSuccessBlock:^(QBResponse * response, QBGeneralResponsePage * page, NSArray * users) {
NSLog(#"usersWithSuccessBlock:");
self.callTestButton.hidden = NO;
} errorBlock:^(QBResponse * response) {
}];
} errorBlock:^(QBResponse *response) {
NSLog(#"error: %#", response.error);
}];
}
- (IBAction)callAction:(UIButton *)sender {
NSArray *opponentsIDs = [[NSArray alloc] initWithObjects:[NSNumber numberWithInteger:6919398], nil];
NSLog(#"%ld", (long)[opponentsIDs[0] integerValue]);
QBRTCSession* session = [QBRTCClient.instance createNewSessionWithOpponents:opponentsIDs
withConferenceType:QBRTCConferenceTypeAudio];
session.localMediaStream.videoTrack.enabled = NO;
if (session) {
NSLog(#"new session");
}
NSDictionary *userInfo = #{#"startCall" : #"userInfo"};
[session startCall:userInfo];
}
Please check the documentation that shows how to use Quickblox SDK for videocalls and also check the sample code
I coded an Android Game in Java using Android Studio. Now I want to exchange the players highscore online, via the GoogleApi. So I initialize a GoogleApiClient in my onCreate function:
googleApi = new GoogleApiClient.Builder(FullscreenActivity.this)
.addApi(Games.API)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.build();
Where googleApiis a public GoogleApiClient variable.
Then there are:
#Override
protected void onStart() {
super.onStart();
Log.e("Connected?", String.valueOf(googleApi.isConnected()));
googleApi.connect();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d("ConnectionFailed", String.valueOf(result));
if (result.hasResolution()) {
try {
// !!!
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (IntentSender.SendIntentException e) {
googleApi.connect();
}
}
}
#Override
public void onConnected(Bundle bundle) {
if(!started){
started = true;
setContentView(new Game(this));
}
}
#Override
public void onConnectionSuspended(int i) {
if(!started){
started = true;
this.setContentView(new Game(this));
}
}
The output of onConnectionFailed(...) says: D/ConnectionFailed: ConnectionResult{statusCode=SIGN_IN_REQUIRED, resolution=PendingIntent{2b5bddee: android.os.BinderProxy#7d0328f}, message=null}
On my mobile the Google Play Games Login window showed up, and I logged in. Then a rotating progress circle was showing, and it disappeared. The onConnected(...) function never got called.
What to add/remove/edit?
This is most likely not a duplicate, because I did not find a working solution for several other questions, that equal in content.
During the signin process, there can be multiple calls to onConnectionFailed. Have you looked at the samples in GitHub: https://github.com/playgameservices/android-basic-samples/tree/master/BasicSamples ?
In the samples onConnectionFailed is implemented as:
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "onConnectionFailed");
if (mIsResolving) {
// The application is attempting to resolve this connection failure already.
Log.d(TAG, "onConnectionFailed: already resolving");
return;
}
if (mSignInClicked || mAutoStartSignIn) {
mSignInClicked = false;
mAutoStartSignIn = false;
// Attempt to resolve the connection failure.
Log.d(TAG, "onConnectionFailed: begin resolution.");
mIsResolving = resolveConnectionFailure(this, mGoogleApiClient,
connectionResult, RC_SIGN_IN, getString(R.string.signin_other_error));
}
updateUI();
}
And resolveConnectionFailure is:
public static boolean resolveConnectionFailure(Activity activity,
GoogleApiClient client, ConnectionResult result, int requestCode,
String fallbackErrorMessage) {
if (result.hasResolution()) {
try {
result.startResolutionForResult(activity, requestCode);
return true;
} catch (IntentSender.SendIntentException e) {
// The intent was canceled before it was sent. Return to the default
// state and attempt to connect to get an updated ConnectionResult.
client.connect();
return false;
}
} else {
// not resolvable... so show an error message
int errorCode = result.getErrorCode();
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(errorCode,
activity, requestCode);
if (dialog != null) {
dialog.show();
} else {
// no built-in dialog: show the fallback error message
showAlert(activity, fallbackErrorMessage);
}
return false;
}
}
Please help
I hava code for button post to wall :
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
But I Have New Faceboof android sdk 4.0.0 and this code depreacated
How post to wall whith new library?
I read this, but I don't understand how to use
The official Facebook documentation on how to share from Android SDK 4.0 is located here:
https://developers.facebook.com/docs/sharing/android
That link has examples of how to share by calling the Graph API or sharing by calling the native Facebook app dialog.
Here is how I implemented the share dialog in my own app:
in the xml for the activity/fragment I added the Button
<Button
android:layout_width="144dp"
android:layout_height="144dp"
android:id="#+id/shareFacebookButton"
android:text=""
android:background="#drawable/facebook_button"
android:layout_gravity="center"
android:layout_marginBottom="6dp"
/>
Then inside the Fragment:
Button shareButton = (Button)view.findViewById(R.id.shareFacebookButton);
shareDialog = new ShareDialog(this);
callbackManager = CallbackManager.Factory.create();
shareDialog.registerCallback(callbackManager, new
FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {}
#Override
public void onCancel() {}
#Override
public void onError(FacebookException error) {}
});
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription("The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
}});
Now when someone clicks on the button they will be met with the Facebook dialog like you would expect.
Hope this helps.
Maybe it's not quite the solution you are looking for, but I'm using it.
Facebook Android SDK 4 has class ShareApi for sharing your content. This class has static method share():
public static void share(
final ShareContent shareContent,
final FacebookCallback<Sharer.Result> callback) {
new ShareApi(shareContent)
.share(callback);
}
and non static private String message. So when you're trying to share something (for ex.
ShareApi api = new ShareApi(content);
api.setMessage("My message");
api.share(content, new FacebookCallback<Sharer.Result>() ...)
) will be created new instance of ShareApi with message = null and your message won't be added.
The solution:
Open class ShareApi if you're using Facebook SDK as external library OR copy this class from Github https://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/share/ShareApi.java
if you're using Maven repository.
Change this code:
public static void share(
final ShareContent shareContent,
final FacebookCallback<Sharer.Result> callback) {
new ShareApi(shareContent)
.share(callback);
}
to this one:
public static void share(final String message,
final ShareContent shareContent,
final FacebookCallback<Sharer.Result> callback) {
new ShareApi(message, shareContent)
.share(callback);
}
Change this code:
public ShareApi(final ShareContent shareContent) {
this.shareContent = shareContent;
this.graphNode = DEFAULT_GRAPH_NODE;
}
to this one:
public ShareApi(String message, final ShareContent shareContent) {
this.message = message;
this.shareContent = shareContent;
this.graphNode = DEFAULT_GRAPH_NODE;
}
Use your changed ShareApi class for sharing your content:
ShareApi.share("My message", content, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
if (AppConfig.DEBUG) {
Log.d(TAG, "SUCCESS");
}
}
#Override
public void onCancel() {
if (AppConfig.DEBUG) {
Log.d(TAG, "CANCELLED");
}
}
#Override
public void onError(FacebookException error) {
if (AppConfig.DEBUG) {
Log.d(TAG, error.toString());
}
}
});
If you just want to share text, you can use code below for content object:
ShareLinkContent content = new ShareLinkContent.Builder()
.build();
You've already read this manual https://developers.facebook.com/docs/sharing/android and can add different ShareContent to your post. Use examples from Facebook Github repository for better understanding new SDK.
P.S. Of course, you should have valid access token and publish_actions permission.
This is full working (13.02.2017) example based on Max answer.
Gradle: compile 'com.facebook.android:facebook-android-sdk:[4,5)'
public class ShareOnFacebook extends Activity {
private static final String TAG = "ShareOnFacebook";
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareOnWall();
}
void shareOnWall() {
ShareDialog shareDialog = new ShareDialog(this);
callbackManager = CallbackManager.Factory.create();
shareDialog.registerCallback(callbackManager, new
FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.d(TAG, "onSuccess: ");
Toast.makeText(ShareOnFacebook.this, "onSuccess", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Log.d(TAG, "onCancel: ");
Toast.makeText(ShareOnFacebook.this, "onCancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "onError: ");
Toast.makeText(ShareOnFacebook.this, "onError" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription("The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I have this code.. The only working here is the Login... I want to achieve the Publish to wall or feed dialog.. I have here the code for the wall post but It still not working.. Any help will be appreciated... I followed this link for my Login
[a link] http://www.kpbird.com/2013/03/android-login-using-facebook-sdk-30.html
I am trying to embed the post status in this Login..
public class FacebookActivity extends FragmentActivity {
private Button publishButton;
private String TAG = "FacebookActivity";
private TextView lblEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook_activity);
lblEmail = (TextView) findViewById(R.id.lblEmail);
LoginButton authButton = (LoginButton) findViewById(R.id.authButton);
authButton.setOnErrorListener(new OnErrorListener(){
#Override
public void onError(FacebookException error) {
Log.i(TAG, "Error " + error.getMessage());
}
// TODO Auto-generated method stub
});
// set permission list, Don't forget to add email
authButton.setReadPermissions(Arrays.asList("basic_info","email"));
// session state call back event
authButton.setSessionStatusCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Log.i(TAG,"Access Token"+ session.getAccessToken());
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,Response response) {
if (user != null) {
Log.i(TAG,"User ID "+ user.getId());
Log.i(TAG,"Email "+ user.asMap().get("email"));
lblEmail.setText(user.asMap().get("email").toString());
}
}
});
publishButton.setVisibility(View.VISIBLE);
}
else if (state.isClosed()) {
publishButton.setVisibility(View.INVISIBLE);
}
}
});
publishButton = (Button) findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishFeedDialog();
}
});
}
private void publishFeedDialog() {
Bundle params = new Bundle();
params.putString("name", "Facebook SDK for Android");
params.putString("caption", "Build great social apps and get more installs.");
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
params.putString("link", "https://developers.facebook.com/android");
params.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(getActivity().getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(getActivity().getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
protected ContextWrapper getActivity() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}