i am trying to get profile pic,email from twitter integration - android

public class AndroidTwitterExample extends Activity {
private TwitterLoginButton twitterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
setUpViews();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
twitterButton.onActivityResult(requestCode, resultCode, data);
}
private void setUpViews() {
setUpTwitterButton();
}
private void setUpTwitterButton() {
twitterButton = (TwitterLoginButton) findViewById(R.id.twitter_button);
twitterButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
String username =result.data.getUserName();
Toast.makeText(getApplicationContext(),
username,
Toast.LENGTH_SHORT).show();
Log.d("response",result.response.getBody().toString());
setUpViewsForTweetComposer();
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.app_name),
Toast.LENGTH_SHORT).show();
}
});
}
private void setUpViewsForTweetComposer() {
TweetComposer.Builder builder = new TweetComposer.Builder(this)
.text("Just setting up my Fabric!");
builder.show();
}
}
i tried the above code but result object i only get the username and userId how can i get profile pic and email.

For getting profile pic use this one in success of callback :
Twitter.getApiClient(result.data).getAccountService()
.verifyCredentials(true, false, new Callback<User>() {
#Override
public void failure(TwitterException e) {
//If any error occurs handle it here
}
#Override
public void success(Result<User> userResult) {
//If it succeeds creating a User object from userResult.data
User user = userResult.data;
//Getting the profile image url
String profileImage = user.profileImageUrl.replace("_normal", "");
Log.i("profile Image",""+profileImage);
}
});
and for email Id fetching here is reference url :
https://docs.fabric.io/android/twitter/log-in-with-twitter.html#request-user-email-address

Related

Unable to create share dialog using facebook SDK

I have a simple app, in which I am using facebook sdk to get user info. I am trying to share content by using ShareLinkContent.Builder but I am receving error:
onError:
{FacebookServiceException: httpResponseCode: -1, facebookErrorCode: 100, facebookErrorType: null, message: The parameter 'href' or 'media' is required}
Here is my MainActivity:
CallbackManager callbackManager;
ShareDialog shareDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.d(LOG_TAG, "success");
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "onError: ", error);
}
#Override
public void onCancel() {
Log.d(LOG_TAG, "cancel");
}
});
createPost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent.Builder post = new ShareLinkContent.Builder();
post = post.setContentUrl(Uri.parse(""));
post.setContentTitle("");
shareDialog.show(MainActivity.this, post.build());
}
}
});
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
What happens is that, dialog does not appear and I get the above error in logcat.
UPDATE:
What I want:
Is it possible to use ShareLinkContent.Builder with a null setContentUrl, I just want my user to share his text not a link or something else. Is it possible?

Facebook login in fragment

I would like to use Facebook login in my App. I have just registred app and added SDK to project. However, I tried to follow the tutorial from documentation but nothing worked (I need to get ID and email from profile and send to to my server).
Fragment
public class LoginFragment extends Fragment {
#BindView(R.id.ivLogo) ImageView ivLogo;
#BindView(R.id.email) EditText edEmail;
#BindView(R.id.password) EditText edPassword;
#BindView(R.id.btnFbLogin) LoginButton btnFbLogin;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
String email, password, ID;
User user;
public LoginFragment() {
// Required empty public constructor
}
public static LoginFragment newInstance() {
LoginFragment fragment = new LoginFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.i("success", "success");
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_login_screen, container, false);
ButterKnife.bind(this, view);
btnFbLogin.setReadPermissions("email");
btnFbLogin.setFragment(this);
// Callback registration
btnFbLogin.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
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
((MainActivity) getActivity()).getSupportActionBar().hide();
}
private void FBcallback() {
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
try {
String email = object.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onCancel() { }
#Override
public void onError(FacebookException e) { }
};
btnFbLogin.setReadPermissions("email");
btnFbLogin.registerCallback(callbackManager, callback);
}
private void loginEmail() {
FactoryAPI.getInstanceLogin().login("hardcoded mail", "hardcoded password").enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), R.string.email_password_is_not_right, Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
}
});
}
private void loginFB() {
FactoryAPI.getServieFBlogin().loginFB(email, ID).enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
user = response.body().getUser();
startActivity();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
Log.e("error", "error");
}
});
}
public void getEmailPassword() {
email = edEmail.getText().toString();
password = edPassword.getText().toString();
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(getContext(), R.string.empty_properties, Toast.LENGTH_SHORT).show();
}
}
public static boolean emailValidation(CharSequence target) {
return !TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
public void startActivity() {
Intent intent = new Intent(getContext(), AccountActivity.class);
intent.putExtra("account", user);
startActivity(intent);
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
#OnClick({R.id.sign_up_email, R.id.btnFbLogin})
public void onClick(View view) {
switch (view.getId()) {
case R.id.sign_up_email:
loginEmail();
case R.id.btnFbLogin:
break;
}
}
private void getProfile(Profile profile){
if(profile != null){
ID = profile.getId();
}
}
}
As your facebook login is in Fragment not in activity, so the
callback comes in onActivityResult() of Activity in which this fragment attached.
You can check this after override the onActivityResult() of your activity, and put a debug point there.
After you getting result in your activity onActivityResult() method, you can send it to your fragment's onActivityResult().
Hope this will help.
First of all if you are using LoginButton then you don't need to register with LoginManager. Here is the sample
//Using Facebook's LoginButton
//Register Callback
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("email")); //set permissions as public_profile, email, etc
loginButton.setFragment(this); //If you are using in a fragment
// Callback registration
loginButton.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
}
});
Now with LoginManager when using Custom Button to login instead of FB's LoginButton
//To check if you are already logged In
boolean loggedIn = AccessToken.getCurrentAccessToken() == null;
// To Manually login. This will launch facebook's login screen.
LoginManager.getInstance().logInWithReadPermissions(this,
Arrays.asList("public_profile","email"));
In both the cases, for Fragment or Activity you need to handle onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}

Set Facebook Name in a dialog

When I'm connected by the facebook login button, I launch a custom dialog (in the onSuccess) and I want to write in this dialog the name of the person connected. It works when I do it in the layout called in onCreate(I make appear the name after connexion). But it doesn't work when I want to write this in the layout called by the dialog after the connexion (but it's the same activity).
Here is my code :
private CallbackManager mCallbackManager2;
private ProfileTracker mProfileTracker2;
private LoginButton loginbutton2;
final Context context = this;
private ProfilePictureView fAvatar2;
private TextView fName2;
private FacebookCallback<LoginResult> mCallback2 = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
/*
LAUNCH DIALOG ABOUT FACEBOOK CONNEXION
*/
// custom dialog
final Dialog dialogFacebookConnexion = new Dialog(context);
dialogFacebookConnexion.setContentView(R.layout.dialog_facebook_connect);
Button dialogButton = (Button) dialogFacebookConnexion.findViewById(R.id.dialogOk);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogFacebookConnexion.dismiss();
Intent intentmainpage = new Intent(InfoAccountActivity.this, MainPageActivity.class);
startActivity(intentmainpage);
}
});
dialogFacebookConnexion.setCanceledOnTouchOutside(false);
int dialogHeight = (int) getResources().getDimension(R.dimen.dialog_height);
int dialogWidth = (int) getResources().getDimension(R.dimen.dialog_width);
dialogFacebookConnexion.getWindow().setLayout(dialogWidth, dialogHeight);
dialogFacebookConnexion.show();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_info_account);
mCallbackManager2 = CallbackManager.Factory.create();
loginbutton2 = (LoginButton) findViewById(R.id.login_button2);
loginbutton2.setBackgroundResource(R.drawable.facebookconnexion);
loginbutton2.setReadPermissions("user_friends");
loginbutton2.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
loginbutton2.registerCallback(mCallbackManager2, mCallback2);
fName2 = (TextView) findViewById(R.id.facebookName2);
fAvatar2 = (ProfilePictureView) findViewById(R.id.facebook_avatar2);
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
OnProfileChanged(newProfile);
}
};
}
private void OnProfileChanged (Profile profile) {
if (profile != null) {
try {
fName2.setText(profile.getName());
fAvatar2.setProfileId(profile.getId());
} catch (Exception ex) {
}
} else {
}
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
OnProfileChanged(profile);
}
#Override
public void onStop() {
super.onStop();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager2.onActivityResult(requestCode, resultCode, data);
}
Is it a problem with private or protected ? An information can't be access by the dialog?
In any activity, you can use the following facebook code from their SDK once you have signed into Facebook:
Profile.getCurrentProfile().getName()
Did you try using the Request.newMeRequest using your active open session? It is easy to capture the logged user's profile afterwards.
GraphRequest rq = GraphRequest.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(final GraphUser user, Response response) { ...
...
rq.executeAndWait();
You can retrieve the user's name by user.getName() in the onCompleted method and use it anywhere.

Facebook share dialog PostId is null

I am sharing a video on FB via share dialog in Android. The sharing works perfectly fine. However, FB post id returns null. The callback returns even before the video is uploaded. Please let me know, if I missing something. Below is my code.
public class TestFragment extends Fragment {
private CallbackManager callbackManager;
private ShareDialog shareDialog;
public TestFragment() {
// Required empty public constructor
}
public static TestFragment newInstance(String path, String json) {
TestFragment fragment = new TestFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity());
callbackManager = CallbackManager.Factory.create();
shareDialog = new ShareDialog(this);
// this part is optional
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Timber.d("result.getPostId() :: " + result.getPostId());
}
#Override
public void onCancel() {
Timber.d("Facebook : Cancelled");
}
#Override
public void onError(FacebookException e) {
Timber.d(e.getMessage());
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
ButterKnife.inject(this, view);
return view;
}
#OnClick(R.id.facebookShare)
public void share() {
Timber.d("share button pressed");
if (ShareDialog.canShow(ShareVideoContent.class)) {
Timber.d("showing share dialog");
shareDialog.show(getVideoContent());
} else {
Timber.d("unable to show the share dialog");
}
}
private ShareVideoContent getVideoContent() {
Timber.d(mVideoMetadata.getVideoId());
ShareVideo shareVideo = new ShareVideo.Builder()
.setLocalUrl(Uri.parse("... file ..."))
.build();
ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(shareVideo)
.build();
return content;
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
shareDialog.show(shareContent, ShareDialog.Mode.FEED);
Set mode to ShareDialog.Mode.FEED.
It's working for me .
Here's example
When Login Success With Facebook Then Call This Method
shareOnFacebook()
private void shareOnFacebook(){
ShareLinkContent shareContent = new ShareLinkContent.Builder()
.setContentTitle("The Simpson!")
.setContentUrl(Uri.parse("http://www.codecube.in/airbucks-project"))
.build();
mFacebookShareDialog.show(shareContent, ShareDialog.Mode.FEED);
mFacebookShareDialog.registerCallback( this.callbackManager, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.v("MyApp", "Share success!"); //Showed if I press the share or the cancel button
String postID = result.getPostId();
Log.v("MyApp", "Share success!" +result.getPostId());
}
#Override
public void onCancel() {
Log.v("MyApp", "Share canceled"); //Only showed when I press the close button
}
#Override
public void onError(FacebookException e) {
Log.v("MyApp","Share error: " + e.toString());
}
});
mFacebookShareDialog.show(shareContent, ShareDialog.Mode.FEED);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}

Android: Simple facebook onLoginListener cannot be resolved

Im using the simple facebook library, i have this code:
import com.sromku.simple.fb.listeners.OnLoginListener;
import com.sromku.simple.fb.Permission;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebookConfiguration;
public class MainActivity extends Activity {
private SimpleFacebook mSimpleFacebook;
private Button mButtonLogin;
#Override
public void onResume()
{
super.onResume();
mSimpleFacebook = SimpleFacebook.getInstance(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
mSimpleFacebook.onActivityResult(this, requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
// login listener
OnLoginListener onLoginListener = new SimpleFacebook.OnLoginListener()
{
#Override
public void onFail(String reason)
{
Log.w(TAG, reason);
}
#Override
public void onException(Throwable throwable)
{
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
Log.i(TAG, "In progress");
}
#Override
public void onLogin()
{
// change the state of the button or do whatever you want
Log.i(TAG, "Logged in");
}
#Override
public void onNotAcceptingPermissions()
{
Log.w(TAG, "User didn't accept read permissions");
}
};
I get one error in the OnLoginListener, it says the "SimpleFacebook.OnLoginListener cannot be resolved", i have imported the OnLoginListener so i dont understand why it is not working?
Why do you write new SimpleFacebook.OnLoginListener()? The class SimpleFacebook doesn't contain OnLoginListener.
You already imported com.sromku.simple.fb.listeners.OnLoginListener and that's why creating the listener should be following:
OnLoginListener onLoginListener = new OnLoginListener()
{
...
}
you need implement this...
OnLoginListener onLoginListener = new OnLoginListener() {
#Override
public void onLogin() {
// change the state of the button or do whatever you want
Log.i("", "Logged in");
}
#Override
public void onNotAcceptingPermissions(Permission.Type type) {
// user didn't accept READ or WRITE permission
Log.w("", String.format("You didn't accept %s permissions", type.name()));
}
#Override
public void onException(Throwable throwable) {
}
#Override
public void onFail(String reason) {
}
#Override
public void onThinking() {
}

Categories

Resources