Android Facebook Dialog - java

I have integrated Facebook into my app. However, instead of bringing it up in a dialog, it opens full screen. I was wondering if anyone would know of a way to change this to dialog.
FaceBook Handler Class:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* Get existing access_token if any
*/
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null)
facebook.setAccessToken(access_token);
if(expires != 0)
facebook.setAccessExpires(expires);
if (facebook.isSessionValid())
postFacebookMessage();
else {
facebook.authorize(this, new String[] {"publish_stream"}, new Facebook.DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
Toast.makeText(FacebookConnector.this, "Facebook error: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e) {
Toast.makeText(FacebookConnector.this, "Facebook dialog error: " + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onComplete(Bundle values) {
postFacebookMessage();
Toast.makeText(FacebookConnector.this, "Thank You For Sharing!", Toast.LENGTH_SHORT).show(); }
#Override
public void onCancel() {Toast.makeText(FacebookConnector.this, "Facebook authorization cancelled.", Toast.LENGTH_LONG).show();
}
});
}
}
private void postFacebookMessage() {
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
Bundle params = new Bundle();
params.putString("message", MSG);
params.putString("picture", "http://meanwhileinwv.com/meanwhile.png");
mAsyncRunner.request("me/feed", params, "POST", new FacebookPostListener(), null); }
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
The code above produces the following result:
I would like it to be a dialog that the facebook window opens into. I have achieved this with my Twitter code:

Call authorization with additional parameter Facebook.FORCE_DIALOG_AUTH, like this:
facebook.authorize(this, new String[] {"publish_stream"}, Facebook.FORCE_DIALOG_AUTH, new Facebook.DialogListener() { ... });

Related

While Run Facebook Login App it Shows Error

Here in my Main activity and I follow all the facebook Concole Methood.
When I tried to run the app.it shows an error that
Login error: There was an error while login your app, try again later
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton = findViewById(R.id.login_button);
textView1 = findViewById(R.id.tv1);
textView2 = findViewById(R.id.tv2);
textView3 = findViewById(R.id.tv3);
circleImageView = findViewById(R.id.profile_pic);
callbackManager = CallbackManager.Factory.create();
loginButton.setPermissions(Arrays.asList("first_name","last_name","email","id","image_url"));
checkLoginStatus();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
}
#Override
public void onCancel()
{
}
#Override
public void onError(FacebookException error)
{
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
AccessTokenTracker accessTokenTracker=new AccessTokenTracker()
{
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken)
{
if(currentAccessToken==null)
{
textView1.setText("");
textView2.setText("");
textView3.setText("");
circleImageView.setImageResource(0);
Toast.makeText(MainActivity.this,"User Logged out",Toast.LENGTH_LONG).show();
}
else
{
loadUserProfile(currentAccessToken);
}
}
};
private void loadUserProfile(AccessToken newacesstoken)
{
GraphRequest request=GraphRequest.newMeRequest(newacesstoken,new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted(JSONObject object, GraphResponse response)
{
try
{
String first_name=object.getString("first_name");
String last_name=object.getString("last_name");
String email=object.getString("email");
String id=object.getString("id");
String image_url = "https://graph.facebook.com/" + id + "/picture?type=normal";
textView1.setText(first_name +" "+last_name);
textView2.setText(email);
textView3.setText(id);
//RequestOptions requestOptions = new RequestOptions();
//requestOptions.dontAnimate();
Picasso.get().load(image_url).into(circleImageView);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "first_name,last_name,email,id,image_url");
request.setParameters(parameters);
request.executeAsync();
}
private void checkLoginStatus()
{
if(AccessToken.getCurrentAccessToken()!=null)
{
loadUserProfile(AccessToken.getCurrentAccessToken());
}
}
}

Retrofit MaltformedJsonException expected at line - android

I used Facebook Login in my app as registering. Facebook API part worked well and after I got parameters I saved them to session, too.
For second part, I create a user data in MySQL via PHP Slim Framework.
I posted body with Retrofit. After user authentication I got Facebook data perfectly.
Everything is good but somehow Retrofit works onFailure method instead of onResponse method. (I got a little "user added" message in response) And gives this error(below)
Debug Mode Screenshot: Click to See
MainActivity
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
TextView text;
Button button;
ImageView image;
ProgressDialog mDialog;
String accessToken;
//SESSION
String user_email;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPreferences.edit();
goIfTokenExist();
//
text = findViewById(R.id.text);
image = findViewById(R.id.image);
//
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
mDialog = new ProgressDialog(MainActivity.this);
mDialog.setMessage("Retrieving data...");
mDialog.show();
accessToken = loginResult.getAccessToken().getToken();
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
mDialog.dismiss();
getData(object);
goIfTokenExist();
}
});
//Graph API
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
if (AccessToken.getCurrentAccessToken() != null) {
text.setText(AccessToken.getCurrentAccessToken().getUserId());
}
}
public void getData(JSONObject obj) {
try {
URL profile_picture = new URL("https://graph.facebook.com/" + obj.getString("id") + "/picture?width=250&height=250");
Glide.with(this).load(profile_picture.toString()).into(image);
text.setText(
"ID: " + obj.getString("id") + "\n" +
"NAME: " + obj.getString("name") +
"EMAIL: " + obj.getString("email") +
"BIRTHDAY: " + obj.getString("birthday")
);
//SAVE SESSIONS
editor.putString("facebook_id", obj.getString("id"));
editor.putString("facebook_email",obj.getString("email"));
editor.putString("facebook_name",obj.getString("name"));
editor.putString("facebook_birthday",obj.getString("birthday"));
editor.putString("facebook_username",""+obj.getString("name").replaceAll("\\s+","").toLowerCase());
editor.commit();
UserFacebook userNew = new UserFacebook(
obj.getString("id"),
obj.getString("email"),
obj.getString("name"),
obj.getString("birthday"),
obj.getString("name").replaceAll("\\s+","").toLowerCase());
API_Service service = Client.getRetrofitInstance().create(API_Service.class);
Call<UserFacebook> userFacebookCall = service.addFacebookUser(userNew);
userFacebookCall.enqueue(new Callback<UserFacebook>() {
#Override
public void onResponse(Call<UserFacebook> call, Response<UserFacebook> response) {
Toast.makeText(MainActivity.this, "done", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<UserFacebook> call, Throwable t) {
Toast.makeText(MainActivity.this, "was wrong", Toast.LENGTH_SHORT).show();
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null;
}
public void goIfTokenExist() {
//FORWARD TO HOME IF TOKEN IS VALID
if (isLoggedIn() == true) {
startActivity(new Intent(MainActivity.this, ForwardDeneme.class));
} else {
Toast.makeText(MainActivity.this, "no token!", Toast.LENGTH_SHORT).show();
}
}}
API_Service (interface)
public interface API_Service {
#Headers("Content-Type: application/json")
#POST("api/user/add")
Call<UserFacebook> addFacebookUser(#Body UserFacebook userFacebook);}
Client
public class Client {
private static Retrofit retrofit = null;
private static String BASE_URL = "http://192.168.1.102/myWebsite/public/index.php/";
private Client() {}
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}}
Thanks in advance.
Change the Response from call, from UserFacebook to String or UserFacebook need a String parameter called user_added (depending on the json you are receiving)

Facebook login not working Parse

I'm trying to integrate Facebook login function to my app.
When I click on "continue with Facebook button" everything works but the user info is not added to the parse database also the "logs" when login success or failure also not appearing in the logcat.
Any help would be appreciated.
public class FacebookLoginActivity extends Activity {
LoginButton loginButtonFB;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
}};
loginButtonFB = findViewById(R.id.fb_login_button);
loginButtonFB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseFacebookUtils.logInWithReadPermissionsInBackground(FacebookLoginActivity.this, mPermissions, new LogInCallback() {
#Override
public void done(final ParseUser parseUser, ParseException e) {
if (parseUser == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (parseUser.isNew()) {
if (!ParseFacebookUtils.isLinked(parseUser)) {
ParseFacebookUtils.linkWithReadPermissionsInBackground(parseUser, FacebookLoginActivity.this, mPermissions, new SaveCallback() {
#Override
public void done(ParseException ex) {
if (ParseFacebookUtils.isLinked(parseUser)) {
Log.d("MyApp", "Woohoo, user logged in with Facebook!");
Toast.makeText(FacebookLoginActivity.this, "Logged in",Toast.LENGTH_LONG).show();
}
}
});
}
} else {
if (!ParseFacebookUtils.isLinked(parseUser)) {
ParseFacebookUtils.linkWithReadPermissionsInBackground(parseUser, FacebookLoginActivity.this, mPermissions, new SaveCallback() {
#Override
public void done(ParseException ex) {
if (ParseFacebookUtils.isLinked(parseUser)) {
Log.d("MyApp", "Woohoo, user logged in with Facebook!");
Toast.makeText(FacebookLoginActivity.this, "Logged in",Toast.LENGTH_LONG).show();
}
}
});
}
}
}
});
}
});
}
}
FacebookSdk.sdkInitialize(getApplicationContext());
initialiseControls();
private void initialiseControls(){
txtStatus=(TextView)findViewById(R.id.txtStatus);
callbackManager = CallbackManager.Factory.create();
login_button=(LoginButton)findViewById(R.id.login_button);
}
private void loginWithFb(){
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast.makeText(getApplicationContext(), "LOGGED IN USING FACEBOOK !", Toast.LENGTH_LONG).show();
//txtStatus.setText("LOGIN SUCCESSFUL!!!\n" + loginResult.getAccessToken().getToken());
Intent testactivty = new Intent(MainActivity.this, VenuesActivity.class);
startActivity(testactivty);
updateUI(true);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "FAILED !", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "ERROR !", Toast.LENGTH_LONG).show();
}
});
}
It works for me...Hope it helps you

Android app hangs after subsequent call to startActivityForResult

Not sure if this is know behavior or what, but here's the logical flow:
User opens app
Pulls nav drawer out, clicks profile pic to change it
Gallery intent pops up, user picks image, everything works fine
Subsequent attempt to open gallery works fine, upon choosing picture, application hangs
onResume() is not called, neither is onActivityResult(). I even commented out all the code in onActivityResult and it still happens. Any ideas what would cause this?
Here is code from onCreate() in the main activity
ImageButton profilePictureButton = (ImageButton) findViewById(R.id.change_profile_picture);
profilePictureButton.requestFocus();
profilePictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
And here's the handler:
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == 1) {
ImageView view = ((ImageView) findViewById(R.id.nav_profile_picture));
if(data != null) {
/*Picasso.with(this).load(data.getData()).into(view);
UsersCache.getInstance().GetUser("", new Response.Listener<UserItem>() {
#Override
public void onResponse(UserItem response) {
String pictureName = response.username + UUID.randomUUID().toString();
String url = "<redacted>";
JSONObject requestBody = new JSONObject();
try {
requestBody.put("profilePicture", "<redacted>/media/profile_pictures/" + pictureName);
} catch(JSONException e) {
e.printStackTrace();
return;
}
FlareJsonObjectRequest request = new FlareJsonObjectRequest(Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String tet = null;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String tet = null;
}
});
new AmazonS3Uploader(data.getData(), "profile_pictures/" + pictureName);
VolleyQueue.getInstance().getQueue().add(request);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String tet = null;
}
});*/
}
}
I think you are missing the read access permission in Manifest -
android:name="android.permission.READ_EXTERNAL_STORAGE" />

Facebook login button in Android returns user to the same page after logging in

I currently have a Facebook login button in my main activity and want the user to view a new fragment after logging in. However, as it stands, the user gets taken back to the main activity after logging in and I'm not sure why. I defined the button in XML:
<com.facebook.login.widget.LoginButton
xmlns:facebook="http://schemas.android.com/apk/res-auto"
facebook:com_facebook_login_text="FACEBOOK"
android:id="#+id/login_button"
android:layout_width="230dp"
android:layout_height="30dp"/>
and in my MainActivity in onCreate() I initialised the button:
fbLogIn = (LoginButton) findViewById(R.id.login_button);
fbLogIn.setReadPermissions("user_friends");
fbLogIn.registerCallback(FbFragment.mCallBackManager, FbFragment.mCallBack);
FbFragment is the Fragment I want the user to be taken to after logging in via the button - and it contains stuff like the CallbackManager:
public class FbFragment extends Fragment {
private static TextView mTextDetails;
public static CallbackManager mCallBackManager = CallbackManager.Factory.create();;
public static FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login_fragment, container, true);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode, resultCode, data);
}
}
I can't figure out why this Fragment never gets displayed. Out of desperation I even tried setting up an onClickListener() in MainActivity where FbFragment gets initialised every time the button gets clicked but that didn't work either (unsurprisingly).
Any ideas? Highly grateful for any help, thanks
I dont think you are getting callback in onActivityResult() in your FbFragment Please check it and tell if any exception thrown..
This is an activity for facebook login :- HOPE THIS HELPS !!!
public class FacebookActivity extends BaseActivity {
private String TAG = this.getClass().getSimpleName();
private ImageView cancelBtn, iv_googlePlus, loginBtn;
private String accessToken;
private String android_id = "";
private TextView tv_letsFrndOnFb,tv_knowYouBetter,tv_and,tv_serveYouBetter,tv_willNotPost;
private Context FbContext = FacebookActivity.this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
iv_googlePlus = (ImageView) findViewById(R.id.iv_googlePlus);
tv_letsFrndOnFb = (TextView) findViewById(R.id.tv_letsFrndOnFb);
tv_knowYouBetter = (TextView) findViewById(R.id.tv_knowYouBetter);
tv_and = (TextView) findViewById(R.id.tv_and);
tv_serveYouBetter = (TextView) findViewById(R.id.tv_serveYouBetter);
tv_willNotPost = (TextView) findViewById(R.id.tv_willNotPost);
tv_letsFrndOnFb.setTypeface(PACIFICO);
tv_knowYouBetter.setTypeface(PROXIMA_NOVA_BOLD);
tv_and.setTypeface(PROXIMA_NOVA_LIGHT_ITALIK);
tv_serveYouBetter.setTypeface(PROXIMA_NOVA_BOLD);
tv_willNotPost.setTypeface(PROXIMA_NOVA_LIGHT);
cancelBtn = (ImageView) findViewById(R.id.iv_cancelBtn);
loginBtn = (ImageView) findViewById(R.id.iv_checkBtn);
android_id = Settings.Secure.getString(FacebookActivity.this.getContentResolver(),
Secure.ANDROID_ID);
Log.d(TAG,"DEVICE_ID : "+android_id);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(FacebookActivity.this, NumberVerifyActivity.class);
startActivity(intent);
FacebookActivity.this.finish();
}
});
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isNetworkAvailable()) {
fbLogin();
} else
displayToast(R.string.need_network);
}
});
}
public void fbLogin() {
Session.openActiveSession(FacebookActivity.this, true,
new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#Override
public void call(Session session, SessionState state,
Exception exception) {
Log.v(TAG, "APP ID : " + session.getApplicationId());
accessToken = session.getAccessToken();
Log.v(TAG, "ACCESS TOKEN : " + accessToken);
if (session.isOpened()) {
Log.v(TAG, "SESSION STATE : " + "Active");
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
System.out.println(TAG
+ "FACEBOOK RESPONSE : "
+ response.toString());
GraphObject go = response
.getGraphObject();
go.getProperty("gender");
System.out.println(TAG
+ "USER GENDER : "
+ go.getProperty("gender"));
if (user != null) {
System.out.println(TAG
+ "USER NAME : "
+ user.getName());
System.out.println(TAG
+ "USER FACEBOOK ID : "
+ user.getId());
System.out.println(TAG
+ "USER FIRST NAME : "
+ user.getFirstName());
System.out.println(TAG
+ "USER LAST NAME : "
+ user.getLastName());
System.out.println(TAG
+ "USER DOB : "
+ user.getBirthday());
if(user.getName()!=null && go.getProperty("gender")!=null && user.getId()!=null){
if(user.getName()!=null && go.getProperty("gender")!=null && user.getId()!=null){
Bundle b = new Bundle();
b.putString("Gender", go.getProperty("gender").toString());
Intent i = new Intent(FacebookActivity.this,NumberVerifyActivity.class);
i.putExtras(b);
startActivity(i);
}
}
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
}

Categories

Resources