Hi I'm using ParseLoginUi for my android app so users can login into my app using facebook, twitter and local signin options.
I want my users to be able to add/upload profile picture.Right now when someone logs in using facebook I get facebook access token for that user and store it into my parse data. However I don't know how to get the facebook profile picture for that user and what is the best way to store it in my parse database (should I save the url as a String in my db? what if the user uploads an image from his/her device)?
Can someone help me with this issue.
To get the Facebook profile picture for the user you will have to use the Facebook Android SDK V4 (the latest version). After getting the image using the Facebook Android SDK, you simply store the url as a string, and associate it with your parseuser! To get an image from the users device, use an intent with startactivityforresult.
Make sure you have the Facebook Android SDK configured, or all the instructions below will be of little use to you!
Step 1. Get the profile Image from Facebook using the Facebook SDK
recommendation. This should be done AFTER logging in a Facebook User through the Parse SDK.
GraphJSONObjectCallback mCallback = new GraphJSONObjectCallback()
{
#Override
public void onCompleted(JSONObject mData, GraphResponse mResponse)
{
if(mResponse.getError() == null)
{
try
{
final JSONObject mPicture = mData.getJSONObject("picture");
final JSONObject mPictureData = mPicture.getJSONObject("data");
final boolean mSilhouette = mPictureData.getBoolean("is_silhouette");
**//this is the URL to the image that you want**
final String mImageUrl = mPictureData.getString("url");
}
catch (JSONException e)
{
//JSON Error, DEBUG
}
}
else
{
//Facebook GraphResponse error, DEBUG
}
}
};
Bundle mBundle = new Bundle();
mBundle.putString("fields", "picture");
GraphRequest mGetUserRequest = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), mCallback);
mGetUserRequest.setParameters(mBundle);
//if running this on the MAIN THREAD then use .executeAsync()
mGetUserRequest.executeAndWait();
Now you should have the String mImageUrl, so you should have the IMAGE. The boolean mSilhuoette lets you know if the default silhuoette is being used. Check out the Facebook Android SDK docs for more info.
Step 2: Associate url with the user
ParseUser mUser = ParseUser.getCurrentUser();
mUser.put("image", mImageUrl);
mUser.saveInBackground();
Note: You could also download the image yourself and store it in a ParseFile. It depends on how you intend to use this image throughout your application.
Step 3: If the user uploads the image from his/her device, you can use an intent with startactivity to allow the user to pick the image. Get the Image in onActivityResult. Load the image into a Bitmap. Once the image is loaded into the bitmap then convert the bitmap into a parsefile and associate that ParseFile with the user and you are done! I recommend using Picasso for this, as well as displaying your image url that you have associated with your ParseUser. You can find more information about Picasso by doing a google search for Android Picasso.
When you get ready to allow the user to select an image from the device use:
Image mImagePickerIntent = new Intent();
mImagePickerIntent.setType("image/*");
mImagePickerIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent mMainIntent = Intent.createChooser(mImagePickerIntent, "Pick Image");
startActivityForResult(mMainIntent, 1);
In onActivityResult use this
#Override
public void onActivityResult(int mRequestCode, int mResultCode, Intent mIntent)
{
super.onActivityResult(mRequestCode, mResultCode, mIntent);
if(mResultCode == Activity.RESULT_OK)
{
final Uri mImageUri = mIntent.getData();
//might be better to load bitmap with a Picasso Target (try/catch)
Bitmap mBitmap = Picasso.with(getActivity()).load(mImageUri).get();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
final byte[] mData = bos.toByteArray();
mBitmap.recycle();
final ParseFile mPhotoFile = new ParseFile("image.png", mData);
mPhotoFile.saveInBackground();
final ParseUser mUser = ParseUser.getCurrentUser();
mUser.put("imageFile", mPhotoFile);
mUser.saveInBackground();
}
}
The code above isn't final! It is suppose to represent a working snapshot of what you have to do to accomplish your goals! Some stuff omitted for brevity like null checks, try/catch blocks, etc.
you can create profile pic uri from facebookId.
public static Uri getFacebookProfilePic(String fbId,int height, int width) {
Uri.Builder builder = new Uri.Builder().encodedPath(String.format("https://graph.facebook.com/%s/picture", fbId));
builder.appendQueryParameter("height", String.valueOf(height));
builder.appendQueryParameter("width", String.valueOf(width));
builder.appendQueryParameter("migration_overrides", "{october_2012:true}");
return Uri.parse(builder.toString());
}
Related
i am having an app using FB android SDK v 4.5 where i want to upload image to facebook custom story directly from device or camera. i have created custom story even enabled user generated photo option in story setting(in object or action) in.
below is code snippet i am try to use for custom story post.
How to attach image to directly to this code from device
String shareTitle = bundle.getString("shareTitle");
String shareUrl = bundle.getString("shareUrl");
Bundle params = new Bundle();
JSONObject myObject = new JSONObject();
try {
myObject.put("og:type", "in_myappnamespace:check_in");
myObject.put("og:title", "Check out what i found on #myapptag "
+ shareTitle);
if (shareUrl != null && !shareUrl.equalsIgnoreCase("")) {
myObject.put("og:url", shareUrl);
}
} catch (JSONException e) {
}
params.putString("check_in", myObject.toString());
params.putString("fb:explicitly_shared", "true");
fbGraphRequest = new GraphRequest(AccessToken.getCurrentAccessToken(),
"me/in_myappnamespace:share", params, HttpMethod.POST);
new Thread() {
public void run() {
final GraphResponse response = fbGraphRequest.executeAndWait();
}}.start();
please help me, how to attach image with this request from android device.
thanks,
Note: This issue only arises when the Facebook app is installed.
I'm trying to open a user's Facebook profile page when an ImageButton is clicked. After looking at this suggested method for more recent Facebook app versions, it's mostly working, with the exception of users that are friends with the logged in user (in the app), or the logged in user themselves.
The process is:
Image button is clicked
Call to Facebook Graph API is made to get the link to the user's profile via their Facebook ID (stored in our database)
A new Intent is created by checking to see if the Facebook app is installed, and generating the correct Uri
A new Activity is started with the generated Intent
Because we're using Facebook Graph API v2.0, the username field is removed from the GraphUser object in the JSON. The problem is that the Facebook link (GraphUser.getLink()) is either:
An app-scoped (protected) link if the user (logged into the app) is not friends with the user whose profile we are trying to view; format is : https://www.facebook.com/app_scoped_user_id/{protected-id}
A 'normal' Facebook link with the user's real id (unprotected); format is: http://www.facebook.com/{real-user-id}
The real problem is that the Facebook Uri when the app is installed expects either:
An app-scoped link
A link with the username attached to it, not {user-id}
However, the web version (opened in a web view) doesn't care. The link can be app-scoped, username-based or id-based. So everything works for WebViews.
Since username is completely inaccessible in Graph API v2.0, I'm just getting null values, which means that for the Facebook app I can't generate the correct Uri that it expects (username-based), only id-based or app-scoped.
Here is the code that I'm using to create the Intent:
public static Intent getFacebookIntent(String facebookProfileUrl) {
PackageManager pm = App.getContext().getPackageManager();
Uri uri;
try {
pm.getPackageInfo("com.facebook.katana", 0);
uri = Uri.parse("fb://facewebmodal/f?href=" + facebookProfileUrl);
} catch (PackageManager.NameNotFoundException e) {
uri = Uri.parse(facebookProfileUrl);
}
return new Intent(Intent.ACTION_VIEW, uri);
}
And here is my onClick() method on the ImageButton:
new Request(
Session.getActiveSession(),
String.valueOf(mate.getFacebookId()),
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
GraphUser g = response.getGraphObjectAs(GraphUser.class);
String fbUrl = g.getLink();
// TODO: If link does not contain 'scoped', need USERNAME, not ID
String otherUrl = "https://www.facebook.com/" + myAppUser.getId();
String finalUrl = (fbUrl.contains("scoped")) ? fbUrl : otherUrl;
Intent intent = getFacebookIntent(finalUrl);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
).executeAsync();
I need the username if the app is installed, otherwise the web view deals with it as it should.
So the question: How can I get a Facebook username by id for the Facebook app? Or, is there a different Uri that the Facebook app expects that I can account for, using ids and not usernames?
You should be able to use the fb://profile/{user-id} URL format to launch native apps. This will let you use the user ID instead of a username. You could rewrite your getFacebookIntent method as:
public Intent getFacebookIntent(GraphUser user) {
PackageManager pm = this.getPackageManager();
Uri uri;
try {
pm.getPackageInfo("com.facebook.katana", 0);
uri = Uri.parse("fb://profile/" + user.getId());
} catch (PackageManager.NameNotFoundException e) {
uri = Uri.parse(user.getLink());
}
return new Intent(Intent.ACTION_VIEW, uri);
}
You could then call this method and pass in the GraphUser object.
I'm trying to share a link(my Google Play app link) using ShareDialog from Facebook SDK but the problem is that when the URL is my app's Google Play link the other information is not displayed correctly... Actually it's displaying only the link from Google Play without name or description!
Here's the code:
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(
this)
.setLink("https://play.google.com/store/apps/details?id=<myapp>")
.setDescription("Test")
.setName("Test for facebook")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
I tried everything and with other URL's actually is working(displaying name, description, caption etc.) but not with the app's URL.
Does anyone know why a Google Play link won't work with text, description or caption?
Actually if you specify the contentUrl (as in 4.0) or link (as in your case), it overrides the name, description, etc. You just don't need to give other things as it then becomes responsibility of url host to supply the details that should be shown when it gets posted on Facebook timeline.
Although, if you want to share something like Message from user followed by your app link. Then I would suggest to go for Graph API (I wasted 2-3 days in posting something like this via ShareApi/ShareDialog but ended up with using Graph API only.)
Code to share using Graph API:
// Constants to be used when sharing message on facebook time line.
private static final int FACEBOOK_ERROR_PERMISSION = 200;
private static final String PARAM_EXPLICIT = "fb:explicitly_shared";
private static final String PARAM_GRAPH_PATH = "/me/feed";
private static final String PARAM_MSG = "message";
private static final String PARAM_LINK = "link";
// Create the parameter for share.
final Bundle params = new Bundle();
params.putBoolean(PARAM_EXPLICIT, true);
params.putString(PARAM_LINK, BirdingUtah.APP_URL);
// If message is empty, only our link gets posted.
String message = "This is the message to share";
if (!TextUtils.isEmpty(message))
params.putString(PARAM_MSG, message);
// Send the request via Graph API of facebook to post message on time line.
new GraphRequest(AccessToken.getCurrentAccessToken(), PARAM_GRAPH_PATH,
params, HttpMethod.POST, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
searchDialog.dismiss();
if (graphResponse.getError() == null) {
// Success in posting on time line.
Logger.toastShort(R.string.msg_share_success);
Logger.debug(TAG, "Success: " + graphResponse);
} else {
FacebookRequestError error = graphResponse.getError();
if (error.getErrorCode() == FACEBOOK_ERROR_PERMISSION)
// Cancelled while asking permission, show msg
Logger.toastLong(R.string.msg_share_permission);
else
// Error occurred while posting message.
Logger.toastShort(R.string.msg_share_error);
Logger.error(TAG, "Error: " + error);
}
// Enable the button back again if profile and access token are non null.
if (Profile.getCurrentProfile() != null || AccessToken.getCurrentAccessToken() != null)
mShareButton.setEnabled(true);
}
}).executeAsync();
My application is very image centric and would like to allow the user to share images generated by the application on facebook posts. I am of the understanding that "User Generated" can only be used with user/camera taken photos so that is not an option. Correct?
Since I can't specify user generated, I'd like to either:
Set the link on the feed image such that the image in the album is opened, not the default og:url.
This link is by default the og:url specified in the open graph object.
I still need all of the other og:url links in the post except the image to point to the website page.
-OR-
Put an href link in the description (or somewhere else in the feed post) that opens the image in the album.
Unless I am mistaken, It doesn't seem that HTML href tags are allowed in posts/stories. Is there a way to do this in the caption of a custom story?
I am able to upload the image to the app's album and obtain the URL to the image in the album (also using "no story" so that it doesn't create a post).
Is what I'm trying to do possible?
How do I garner more control over the links set in a facebook feed post?
EDIT:
Regarding "User Generated" from facebook docs:
"The User Generated Photos action capability can only be used if the photos are original and taken by a user with an actual camera."
I don't want to generate two stories. Ideally I want ONE story that features an image that can be clicked on that links to the original full size image in the app album. The rest of the story shares some details about the image (desc. etc.). So I guess, in a way, I'm looking for a workaround for the camera/photo requirement.
I don't mind the standard story layout (with a smaller image with title, description/captions) but just want to link that image to one in the users application album.
EDIT:
I'm realizing that an Open Graph Story isn't the way to go here. I have instead gone to simply using the Graph API. (https://developers.facebook.com/docs/graph-api/reference/user/photos/) This allows me to post a link in the user comments along with a photo. For anyone interested:
public static void doImagePost(final Bitmap _sideBySide, String _comments) {
Bundle parameters = new Bundle();
parameters.putParcelable("image", _sideBySide);
String message;
if(_comments != null)
{
if(!_comments.isEmpty())
{
message = _comments + '\n' + '\n' + JSBridge.getURL();
} else {
message = JSBridge.getURL();
}
} else {
message = JSBridge.getURL();
}
//Plain Http://blahblahblah.com/foobar/whatever gets turned into a link in the message field
parameters.putString("message", message);
Bitmap redSideBySide = EHelper.reduceImageSize(_sideBySide, (int)4E6);
Session session = Session.getActiveSession();
if(session == null) {
requestPublish(MODE_PHOTO, redSideBySide, _comments);
return;
} else {
if(!session.isOpened())
{
requestPublish(MODE_PHOTO, redSideBySide, _comments);
return;
}
}
//Here is the Graph API request.
Request imagePostRequest = new Request(Session.getActiveSession(), "me/photos" , parameters, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError() == null)
{
Toast.makeText(m_Context, "Post image success", Toast.LENGTH_SHORT).show();
//m_Images = null;
dismissProgressDlg();
} else {
Toast.makeText(m_Context, "Error posting image to facebook: " + response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show();
Log.e(DEBUG_TAG, "Error posting image to facebook: " + response.getError().getErrorMessage());
dismissProgressDlg();
}
}
});
showProgressDialog("Posting to Facebook...");
imagePostRequest.executeAsync();
}
Hi,
I am new to android trying to integrate twitter with my application. I need to do get twitter profile name and profile picture once the user is logged in. I am able to get profile name but not the profile picture. How can I get the profile picture?
You can get some information in this way:
TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
twitterApiClient.getAccountService().verifyCredentials(false, false, new Callback<User>() {
#Override
public void success(Result<User> userResult) {
String name = userResult.data.name;
String email = userResult.data.email;
// ... other infos
// Get the profile pic
// _normal (48x48px) | _bigger (73x73px) | _mini (24x24px)
String photoUrlNormalSize = userResult.data.profileImageUrl;
String photoUrlBiggerSize = userResult.data.profileImageUrl.replace("_normal", "_bigger");
String photoUrlMiniSize = userResult.data.profileImageUrl.replace("_normal", "_mini");
String photoUrlOriginalSize = userResult.data.profileImageUrl.replace("_normal", "");
}
#Override
public void failure(TwitterException exc) {
Log.d("TwitterKit", "Verify Credentials Failure", exc);
}
});
From the official doc:
You can obtain a user’s most recent profile image from GET users/show. Within the user object, you’ll find the profile_image_url
and profile_image_url_https fields. These fields will contain the
resized “normal” variant of the user’s uploaded image. This “normal”
variant is typically 48x48px.
By modifying the URL, you can retrieve other variant sizings such as
“bigger”, “mini”, and “original”.
If you've fetched the user profile, look out for the json entry called 'profile_image_url'. Some documenetation from twitter on this can also be found here. Use this in conjunction with an ImageDownloader to download the image to be used as a bitmap in your project. This is the number one google result of how to download and display an image:
http://getablogger.blogspot.com/2008/01/android-download-image-from-server-and.html
private TwitterApp mTwitter;
mTwitter.getUserProfileImage();
Returns the profile pic of the Logged in user.
Also u can customize the pic according refer : Android Twitter getting profile image size issue