Cant import facebook Session class in android in android studio - android

I am newbie to android and working on a demo for getting facebook profilel info after login,I have successfully implemented login and want to fetch profile info,i got the code,But while adding profile info it's fail to import necessary classes(Session),can anybudy help me for this.
java
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.Session;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
.
.
.
.
.
private Session openActiveSession(Activity activity, boolean allowLoginUI,
StatusCallback callback, List<String> permissions, Bundle savedInstanceState) {
OpenRequest openRequest = new OpenRequest(activity).
setPermissions(permissions).setLoginBehavior(SessionLoginBehavior.
SSO_WITH_FALLBACK).setCallback(callback).
setDefaultAudience(SessionDefaultAudience.FRIENDS);
Session session = Session.getActiveSession();
Log.d(LOG_TAG, "" + session);
if (session == null) {
Log.d(LOG_TAG, "" + savedInstanceState);
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, fbStatusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED) || allowLoginUI) {
session.openForRead(openRequest);
return session;
}
}
return null;
}

This is the working code for FACEBOOK INTEGRATION:
1) Create one xml: fragment_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivityFragment">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/textView"
android:layout_centerHorizontal="true"/>
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
2) Java Class i.e. MainFragment.java
package example.com.facebook_integration;
/**
* Created by dinesh sharma on 2/22/2016.
*/
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import net.simplifiedcoding.androidlogin.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
/**
* A placeholder fragment containing a simple view.
*/
public class MainFragment extends Fragment {
private CallbackManager callbackManager;
private TextView textView;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
displayMessage(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
final ImageView imageView=(ImageView)view.findViewById(R.id.myImage);
textView = (TextView) view.findViewById(R.id.textView);
//loginButton.setReadPermissions("user_likes");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
loginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday","user_likes","user_friends"));
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(final JSONObject object, GraphResponse response)
{
Log.v("LoginActivity", response.toString());
try
{
// Application code
System.out.println("JSONRESPOMSEEE "+response.toString());
String email = object.getString("email");
String birthday = object.getString("birthday"); // 01/31/1980 format
String name = object.getString("name");
Profile profile = Profile.getCurrentProfile();
Uri uri=(Uri)profile.getProfilePictureUri(200,200);
System.out.println("Email "+email+" Birthday "+birthday+name);
System.out.println("Email " + uri);
final ArrayList arrayList=new ArrayList();
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/likes",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try {
JSONObject json = new JSONObject(response.getRawResponse());
JSONArray jarray = json.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject likes = jarray.getJSONObject(i);
String likeId = likes.getString("id");
String likeName = likes.getString("name");
String likeCreatedTime = likes.getString("created_time");
arrayList.add("Page Name "+likeName+" Time= "+likeCreatedTime+" ID= "+likeId);
System.out.println("My Name " + likeName + " " + likeCreatedTime);
}
System.out.println("ArrayList mine "+arrayList);
System.out.println("ArrayList mine size "+arrayList.size());
}
catch(Exception e)
{
System.out.println("My Exception "+e);
}
}
}
).executeAsync();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void displayMessage(Profile profile) {
if(profile != null){
textView.setText(profile.getName());
}
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume()
{
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
}
3) Create one more xml: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:id="#+id/fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="example.com.facebook_integration.MainFragment"
></fragment>
</RelativeLayout>
4) Create your MainActivity.java
package example.com.facebook_integration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import net.simplifiedcoding.androidlogin.R;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
See this link https://www.simplifiedcoding.net/login-with-facebook-android-studio-using-facebook-sdk-4/
But i have done all the important changes in my code you can use this code after following all the steps from above link.

Related

How to get facebook profile pic android studio

im unable to retrieve the facebook profile pic:
package com.androidtutorialpoint.flogin.Adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.androidtutorialpoint.flogin.ImageHelper;
import com.androidtutorialpoint.flogin.Model.Post_Song;
import com.androidtutorialpoint.flogin.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by sravya on 19-02-2017.
*/
public class SongPostListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Post_Song> songlist;
public SongPostListAdapter(ArrayList<Post_Song> songlist, int layout, Context context) {
this.songlist = songlist;
this.layout = layout;
this.context = context;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
TextView name,time,title,artist;
LinearLayout song_pic;
}
ImageView profilePicImageView;
#Override
public View getView(int position, View view, ViewGroup parent) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row ==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout,null);
holder.artist = (TextView)row.findViewById(R.id.artist);
holder.name = (TextView)row.findViewById(R.id.user_name);
holder.time = (TextView)row.findViewById(R.id.time);
holder.title = (TextView)row.findViewById(R.id.song_title);
holder.song_pic = (LinearLayout)row.findViewById(R.id.track_pic);
//holder.userImage =(ImageView) row.findViewById(R.id.user_pic);
profilePicImageView = (ImageView) row.findViewById(R.id.profilePicture);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
Post_Song posts = songlist.get(position);
holder.artist.setText(posts.getArtist());
holder.name.setText(posts.getUname());
holder.time.setText(posts.getTime());
holder.title.setText(posts.getTitle());
new LoadProfileImage(profilePicImageView).execute(posts.getUser_pic());
final ViewHolder finalHolder = holder;
Picasso.with(context).load(posts.getArtwork()).placeholder(R.drawable.music_placeholder).into(new Target(){
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
finalHolder.song_pic.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
Log.d("TAG", "FAILED");
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
Log.d("TAG", "Prepare Load");
}
});
return row;
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,90,90, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(context,resized,100,90,90, false, false, false, false));
}
}
}
}
This is my adaptor. Iam not able to get the profile pic here.
This is my Facebook fragment, here there is no problem with getting the profile pic
package com.androidtutorialpoint.flogin;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.content.SharedPreferences;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;
import com.facebook.share.widget.ShareDialog;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class FacebookFragment extends Fragment{
DatabaseHelper myDb;
private LoginButton loginButton;
private Button getLibrary;
private Button getShared;
private boolean postingEnabled = false;
private static final String PERMISSION = "publish_actions";
private final String PENDING_ACTION_BUNDLE_KEY =
"com.example.hellofacebook:PendingAction";
//private Button postStatusUpdateButton;
// private Button postPhotoButton;
private ImageView profilePicImageView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private boolean canPresentShareDialog;
private boolean canPresentShareDialogWithPhotos;
private CallbackManager callbackManager;
private ProfileTracker profileTracker;
private ShareDialog shareDialog;
private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
#Override
public void onCancel() {
Log.d("FacebookFragment", "Canceled");
}
#Override
public void onError(FacebookException error) {
Log.d("FacebookFragment", String.format("Error: %s", error.toString()));
String title = getString(R.string.error);
String alertMessage = error.getMessage();
showResult(title, alertMessage);
}
#Override
public void onSuccess(Sharer.Result result) {
Log.d("FacebookFragment", "Success!");
if (result.getPostId() != null) {
String title = getString(R.string.success);
String id = result.getPostId();
String alertMessage = getString(R.string.successfully_posted_post, id);
showResult(title, alertMessage);
}
}
private void showResult(String title, String alertMessage) {
new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
};
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(getActivity());
FacebookSdk.sdkInitialize(getActivity());
// Other app specific specialization
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_facebook, parent, false);
loginButton = (LoginButton) v.findViewById(R.id.loginButton);
// If using in a fragment
loginButton.setFragment(this);
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast toast = Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_SHORT);
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
toast.show();
handlePendingAction();
updateUI();
}
#Override
public void onCancel() {
// App code
if (pendingAction != PendingAction.NONE) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
#Override
public void onError(FacebookException exception) {
if (pendingAction != PendingAction.NONE
&& exception instanceof FacebookAuthorizationException) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
private void showAlert() {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
}
});
shareDialog = new ShareDialog(this);
shareDialog.registerCallback(
callbackManager,
shareCallback);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
updateUI();
handlePendingAction();
}
};
profilePicImageView = (ImageView) v.findViewById(R.id.profilePicture);
greeting = (TextView) v.findViewById(R.id.greeting);
//postStatusUpdateButton = (Button) v.findViewById(R.id.postStatusUpdateButton);
/*postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});*/
/*postPhotoButton = (Button) v.findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});*/
getLibrary = (Button) v.findViewById(R.id.getLibraryButton);
getShared = (Button)v.findViewById(R.id.getSharedButton);
getShared.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), SongPostList.class));
}
});
getLibrary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
// Can we present the share dialog for regular links?
canPresentShareDialog = ShareDialog.canShow(
ShareLinkContent.class);
// Can we present the share dialog for photos?
canPresentShareDialogWithPhotos = ShareDialog.canShow(
SharePhotoContent.class);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
if(!postingEnabled) {
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
}else{
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
// GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
// new GraphRequest.GraphJSONObjectCallback() {
// #Override
// public void onCompleted(
// JSONObject object,
// GraphResponse response) {
// if (object != null) {
// Log.d("Me Request",object.toString());
// Toast t = Toast.makeText(getActivity(), object.toString(), Toast.LENGTH_SHORT);
// t.show();
// }
//
// }
// });
// Bundle parameters = new Bundle();
// parameters.putString("fields", "id,name,link,email");
// request.setParameters(parameters);
// request.executeAsync();
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "user_friends"));
//
//
//
// }
// });
return v;
}
#Override
public void onResume() {
super.onResume();
// Call the 'activateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onResume methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.activateApp(getActivity());
updateUI();
}
#Override
public void onPause() {
super.onPause();
// Call the 'deactivateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onPause methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.deactivateApp(getActivity());
}
#Override
public void onDestroy() {
super.onDestroy();
profileTracker.stopTracking();
}
private void updateUI() {
boolean enableButtons = AccessToken.getCurrentAccessToken() != null;
//postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
//postPhotoButton.setEnabled(enableButtons || canPresentShareDialogWithPhotos);
Profile profile = Profile.getCurrentProfile();
if (enableButtons && profile != null) {
new LoadProfileImage(profilePicImageView).execute(profile.getProfilePictureUri(200, 200).toString());
greeting.setText(getString(R.string.hello_user, profile.getName()));
boolean isInserted =myDb.insertData(profile.getId(),profile.getName(),profile.getProfilePictureUri(200,200).toString());
if(isInserted == true){
Toast.makeText(getActivity(),"Data Inserted",Toast.LENGTH_LONG).show();
SharedPreferences settings = getActivity().getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("uid", profile.getId());
editor.putString("name",profile.getName());
editor.putString("pic",profile.getProfilePictureUri(200,200).toString());
editor.commit();
}else{
Toast.makeText(getActivity(),"Not Inserted",Toast.LENGTH_LONG).show();
}
postingEnabled = true;
//postPhotoButton.setVisibility(View.VISIBLE);
//postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
} else {
Bitmap icon = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.user_default);
profilePicImageView.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(), icon, 200, 200, 200, false, false, false, false));
greeting.setText(null);
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case NONE:
break;
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}
private void postStatusUpdate() {
Profile profile = Profile.getCurrentProfile();
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Integrate Facebook Login to your Android App")
.setContentDescription(
"This app shows how to integrate Facebook Login to your Android App")
.setContentUrl(Uri.parse("http://www.androidtutorialpoint.com/material-design/adding-facebook-login-to-android-app/"))
.build();
if (canPresentShareDialog) {
shareDialog.show(linkContent);
} else if (profile != null && hasPublishPermission()) {
ShareApi.share(linkContent, shareCallback);
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
}
private void postPhoto() {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.androidlogo);
SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(image).build();
ArrayList<SharePhoto> photos = new ArrayList<>();
photos.add(sharePhoto);
SharePhotoContent sharePhotoContent =
new SharePhotoContent.Builder().setPhotos(photos).build();
if (canPresentShareDialogWithPhotos) {
shareDialog.show(sharePhotoContent);
} else if (hasPublishPermission()) {
ShareApi.share(sharePhotoContent, shareCallback);
} else {
pendingAction = PendingAction.POST_PHOTO;
// We need to get new permissions, then complete the action when we get called back.
LoginManager.getInstance().logInWithPublishPermissions(
this,
Arrays.asList(PERMISSION));
}
}
private boolean hasPublishPermission() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null && accessToken.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action, boolean allowNoToken) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null || allowNoToken) {
pendingAction = action;
handlePendingAction();
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,200,200, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),resized,250,200,200, false, false, false, false));
}
}
}
}
Please help, iam unable to figure out whats wrong
Instead of downloading the image using a custom class extended from AsyncTask you can load it with Picasso.
Uri image = Profile.getCurrentProfile().getProfilePictureUri(200, 200);
Picasso.with(context).load(image).placeholder(R.drawable.placeholder).into(imageView);

Basic Facebook API Login not working

I am new to Android Development and Facebook SDK. I am just trying to link Facebook loginButton with my application. When I click on button it ask me for login details and permissions and then it comes back successfully to app. But again at the same moment when I click on that button it ask me to login again.
package com.example.pranavjain.pranavapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
// If using in a fragment
// Other app specific specialization
// Callback registration
CallbackManager callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object1,
GraphResponse response) {
// Application code
Log.d("tagpranav", object1.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
// App code
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
// App code
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have already checked that Hash key is right. Nothing gets logged under "tagpranav" or "LoginActivity".
Make sure to add following in your onCreate() method as first line:
FacebookSdk.sdkInitialize(getApplicationContext());
Consider moving your code in onCreate() method of your MainActivity. Below I'd mentioned working sample.
public class MainActivity extends ActionBarActivity {
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(PERMISSIONS_ARRAY);
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i(TAG, "Logged in...");
GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject user, GraphResponse response) {
try {
if (user != null) {
Log.e(TAG, "UserID : " + user.getString("id"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).executeAsync();
}
#Override
public void onCancel() {
// Login canceled
}
#Override
public void onError(FacebookException exception) {
// Login error
}
});
}
}
In above code PERMISSIONS_ARRAY is array having all your permissions.
One thing you are missing is, make callbackManager class variable and add following method in your MainActivity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "OnActivityResult...:" + resultCode);
}
EDIT-1:
A class variable is something defined in a class and out side of method, so that all methods of class can access it.
In your code you have defined callbackManager inside a method, so you can't access it in onActivityResult. I have made relevant changes in my answer.
You have to pass the results to the callbackManager in onActivityResult like here: https://github.com/facebook/facebook-android-sdk/blob/master/samples/HelloFacebookSample/src/com/facebook/samples/hellofacebook/HelloFacebookSampleActivity.java#L231

my fragment showing blank screen after i am having this code

package com.example.mindwareuae;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputFilter.LengthFilter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;
public class FacebokkFragment extends Fragment{
private LoginButton loginBtn;
private Button postImageBtn;
private Button updateStatusBtn;
private TextView userName;
private UiLifecycleHelper uiHelper;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
try
{
View rootView = inflater.inflate(R.layout.fragment_facebook,container,false);
userName = (TextView)rootView.findViewById(R.id.user_name);
loginBtn = (LoginButton) rootView.findViewById(R.id.fb_login_button);
loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
#Override
public void onUserInfoFetched(GraphUser user) {
if (user != null) {
userName.setText("Hello, " + user.getName());
} else {
userName.setText("You are not logged");
}
}
});
postImageBtn = (Button)rootView.findViewById(R.id.fbpost_image);
postImageBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
postImage();
}
});
updateStatusBtn = (Button)rootView.findViewById(R.id.fbupdate_status);
updateStatusBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttonsEnabled(false);
}catch(Exception e)
{
e.printStackTrace();
}
return rootView;
}
public void buttonsEnabled(boolean isEnabled) {
postImageBtn.setEnabled(isEnabled);
updateStatusBtn.setEnabled(isEnabled);
}
public void postImage() {
if (checkPermissions()) {
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(getActivity(),
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
} else {
requestPermissions();
}
}
// public void postStatusMessage() {
// if (checkPermissions()) {
// Request request = Request.newStatusUpdateRequest(
// Session.getActiveSession(), message,
// new Request.Callback() {
// #Override
// public void onCompleted(Response response) {
// if (response.getError() == null)
// Toast.makeText(getActivity(),
// "Status updated successfully",
// Toast.LENGTH_LONG).show();
// }
// });
// request.executeAsync();
// } else {
// requestPermissions();
// }
// }
public boolean checkPermissions() {
Session s = Session.getActiveSession();
if (s != null) {
return s.getPermissions().contains("publish_actions");
} else
return false;
}
public void requestPermissions() {
Session s = Session.getActiveSession();
if (s != null)
s.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS));
}
// #Override
// public void onResume() {
// super.onResume();
// uiHelper.onResume();
// buttonsEnabled(Session.getActiveSession().isOpened());
// }
//
// #Override
// public void onPause() {
// super.onPause();
// uiHelper.onPause();
// }
//
// #Override
// public void onDestroy() {
// super.onDestroy();
// if (rootView != null) {
// ViewGroup parentViewGroup = (ViewGroup) rootView.getParent();
// if (parentViewGroup != null) {
// parentViewGroup.removeAllViews();
// }
// }
// uiHelper.onDestroy();
// }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
}
i want login the facbook from this fragment..but i am not getiing any thing my xml file is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:facebook="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="20dp"
android:background="#EEEEEE">
<com.facebook.widget.LoginButton
android:id="#+id/fb_login_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
facebook:confirm_logout="false"
facebook:fetch_user_info="true" />
<TextView
android:id="#+id/fb_user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:textSize="18sp" />
<Button
android:id="#+id/fbupdate_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="update_status" />
<Button
android:id="#+id/fbpost_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="post_image" />
</LinearLayout>
it is my xml file why i am not able to get the fragment with my facebook login button.
please any one can explain me.
Create a FragmentActivity and add your fragment to that FragmentActivity
public class MainActivity extends FragmentActivity{
FacebokkFragment fbFragment;
ArrayList<Fragment> fragemetnList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fbFragment = new FacebokkFragment();
fragemetnList = getFragmnetsList();
setContentView(R.layout.activity_main);
}
ArrayList<Fragment> getFragmnetsList() {
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
fragments.add(fbFragment);
// you can also add more fragments here
return fragments;
}
}
Now create an activity_main.xml file into your res/layout directory
Don't forget to make the entry of your MainActivity into AndroidManifest.xml file
May this code will solve your problem
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
}
Is this part of code really required? Try removing this.
Try this
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container, false);
...
return rootView;

Issue in Fetching user's facebook data after user login through my android app

Screenshot of the problem in debug:
Follwoing is my complete code of facebook login file
import java.util.ArrayList;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
Context context;
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Display the parsed user info
// userInfoTextView.setText(buildUserInfoDisplay(user));
// Log.d(TAG,"Failed to login");
}
}
}).executeAsync();
}
else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
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("Birthday: %s\n\n", user.getBirthday()));
// Example: partially typed access, to location field,
// name key (location)
// - requires user_location permission
userInfo.append(String.format("Location: %s\n\n", user.getLocation()
.getProperty("name")));
// Example: access via property name (locale)
// - no special permissions required
userInfo.append(String.format("Locale: %s\n\n",
user.getProperty("locale")));
// Example: access via key for array (languages)
// - requires user_likes permission
JSONArray languages = (JSONArray) user.getProperty("languages");
if (languages.length() > 0) {
ArrayList<String> languageNames = new ArrayList<String>();
for (int i = 0; i < languages.length(); i++) {
JSONObject language = languages.optJSONObject(i);
// Add the language name to a list. Use JSON
// methods to get access to the name field.
languageNames.add(language.optString("name"));
}
userInfo.append(String.format("Languages: %s\n\n",
languageNames.toString()));
}
return userInfo.toString();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_layout, container, false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_about_me",
"user_likes", "user_status", "user_groups"));
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
public void onResume() {
super.onResume();
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);
uiHelper.onSaveInstanceState(outState);
}
}
Any help regarding this issue will be a great favour thanks...
Try using the following code , it might help , working fine in my case.
import java.util.Arrays;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class MainFragment extends Fragment {
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private TextView userInfoTextView;
private String fbAccessToken;
private ImageView userProfileImg;
#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);
authButton.setReadPermissions(Arrays.asList("user_location", "user_birthday", "user_likes"));
userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
userProfileImg = (ImageView)view.findViewById(R.id.user_profile_img);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
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);
uiHelper.onSaveInstanceState(outState);
}
#SuppressWarnings("deprecation")
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
userInfoTextView.setVisibility(View.VISIBLE);
// Request user data and show the results
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
userInfoTextView.setText(buildUserInfoDisplay(user,fbAccessToken));
}
}
});
}
else if (state.isClosed()) {
Toast.makeText(getActivity(), "Please Login", Toast.LENGTH_SHORT).show();
userInfoTextView.setVisibility(View.GONE);
}
}
private String buildUserInfoDisplay(GraphUser user,String token) {
StringBuilder userInfo = new StringBuilder("");
userInfo.append(String.format("Name: %s\n\n",
user.getName()));
userInfo.append(String.format("Birthday: %s\n\n",
user.getBirthday()));
userInfo.append(String.format("Id: %s\n\n",
user.getId()));
userInfo.append(String.format("Locale: %s\n\n",
user.getProperty("locale")));
userInfo.append(String.format("Link: %s\n\n",
user.getLink()));
userInfo.append(String.format("Gender:%s\n\n",user.asMap().get("gender").toString()));
userInfo.append(String.format("Token:%s\n\n",token));
return userInfo.toString();
}
}

on publish feed, facebook 3.0 examples

so i followed the tutorial pages in the facebook dev site and i have this code:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and this is the fragment class
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.LoginButton;
public class MainFragment extends Fragment {
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private UiLifecycleHelper uiHelper;
private Button shareButton;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
protected String TAG;
#Override
public void onResume() {
super.onResume();
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);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#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);
shareButton = (Button) view.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
authButton.setFragment(this);
return view;
}
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
if (state.isOpened()) {
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
shareButton.setVisibility(View.INVISIBLE);
}
}
private void publishStory() {
Session session = Session.getActiveSession();
Log.i(TAG,session.toString());
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;
}
}
so i have all the code its mean to work in this two pages
https://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/
and
https://developers.facebook.com/docs/howtos/androidsdk/3.0/publish-to-feed/
for some reason i can log in, that is done, but now when i click share it just stays loading forever untill my android device ask me to shut down the application because is frozen, the log cat says facebook.katana is not respoding, so how can i work around this. is something related to permisions in the app dashboard? or what is wrong. i need to know if i did something wrong. before i start again and do it all over again.
Update : after almost 24 hours finally i got the posted message in my wall, so it seems this work after all, but facebook seems unresponsive sometimes.

Categories

Resources