How post to wall facebook android-sdk:4.0.0 - java

Please help
I hava code for button post to wall :
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
But I Have New Faceboof android sdk 4.0.0 and this code depreacated
How post to wall whith new library?
I read this, but I don't understand how to use

The official Facebook documentation on how to share from Android SDK 4.0 is located here:
https://developers.facebook.com/docs/sharing/android
That link has examples of how to share by calling the Graph API or sharing by calling the native Facebook app dialog.
Here is how I implemented the share dialog in my own app:
in the xml for the activity/fragment I added the Button
<Button
android:layout_width="144dp"
android:layout_height="144dp"
android:id="#+id/shareFacebookButton"
android:text=""
android:background="#drawable/facebook_button"
android:layout_gravity="center"
android:layout_marginBottom="6dp"
/>
Then inside the Fragment:
Button shareButton = (Button)view.findViewById(R.id.shareFacebookButton);
shareDialog = new ShareDialog(this);
callbackManager = CallbackManager.Factory.create();
shareDialog.registerCallback(callbackManager, new
FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {}
#Override
public void onCancel() {}
#Override
public void onError(FacebookException error) {}
});
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription("The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
}});
Now when someone clicks on the button they will be met with the Facebook dialog like you would expect.
Hope this helps.

Maybe it's not quite the solution you are looking for, but I'm using it.
Facebook Android SDK 4 has class ShareApi for sharing your content. This class has static method share():
public static void share(
final ShareContent shareContent,
final FacebookCallback<Sharer.Result> callback) {
new ShareApi(shareContent)
.share(callback);
}
and non static private String message. So when you're trying to share something (for ex.
ShareApi api = new ShareApi(content);
api.setMessage("My message");
api.share(content, new FacebookCallback<Sharer.Result>() ...)
) will be created new instance of ShareApi with message = null and your message won't be added.
The solution:
Open class ShareApi if you're using Facebook SDK as external library OR copy this class from Github https://github.com/facebook/facebook-android-sdk/blob/master/facebook/src/com/facebook/share/ShareApi.java
if you're using Maven repository.
Change this code:
public static void share(
final ShareContent shareContent,
final FacebookCallback<Sharer.Result> callback) {
new ShareApi(shareContent)
.share(callback);
}
to this one:
public static void share(final String message,
final ShareContent shareContent,
final FacebookCallback<Sharer.Result> callback) {
new ShareApi(message, shareContent)
.share(callback);
}
Change this code:
public ShareApi(final ShareContent shareContent) {
this.shareContent = shareContent;
this.graphNode = DEFAULT_GRAPH_NODE;
}
to this one:
public ShareApi(String message, final ShareContent shareContent) {
this.message = message;
this.shareContent = shareContent;
this.graphNode = DEFAULT_GRAPH_NODE;
}
Use your changed ShareApi class for sharing your content:
ShareApi.share("My message", content, new FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
if (AppConfig.DEBUG) {
Log.d(TAG, "SUCCESS");
}
}
#Override
public void onCancel() {
if (AppConfig.DEBUG) {
Log.d(TAG, "CANCELLED");
}
}
#Override
public void onError(FacebookException error) {
if (AppConfig.DEBUG) {
Log.d(TAG, error.toString());
}
}
});
If you just want to share text, you can use code below for content object:
ShareLinkContent content = new ShareLinkContent.Builder()
.build();
You've already read this manual https://developers.facebook.com/docs/sharing/android and can add different ShareContent to your post. Use examples from Facebook Github repository for better understanding new SDK.
P.S. Of course, you should have valid access token and publish_actions permission.

This is full working (13.02.2017) example based on Max answer.
Gradle: compile 'com.facebook.android:facebook-android-sdk:[4,5)'
public class ShareOnFacebook extends Activity {
private static final String TAG = "ShareOnFacebook";
CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
shareOnWall();
}
void shareOnWall() {
ShareDialog shareDialog = new ShareDialog(this);
callbackManager = CallbackManager.Factory.create();
shareDialog.registerCallback(callbackManager, new
FacebookCallback<Sharer.Result>() {
#Override
public void onSuccess(Sharer.Result result) {
Log.d(TAG, "onSuccess: ");
Toast.makeText(ShareOnFacebook.this, "onSuccess", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Log.d(TAG, "onCancel: ");
Toast.makeText(ShareOnFacebook.this, "onCancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "onError: ");
Toast.makeText(ShareOnFacebook.this, "onError" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Hello Facebook")
.setContentDescription("The 'Hello Facebook' sample showcases simple Facebook integration")
.setContentUrl(Uri.parse("http://developers.facebook.com/android"))
.build();
shareDialog.show(linkContent);
}
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}

Related

Barcode scanner is reading only QR codes using ML Kit

I'm trying to build a barcode scanner in android studio, using ML Kit. I have a code that works fine, it is only detecting QR codes. I wanted to make the barcode scanner to read all types of barcodes, mainly those for food products. I'm trying to get the raw values of the barcode for searching purposes in the database and displaying the concerned information to the screen.
Below are the codes that I've used to detect the QR code.
public class MainActivity extends AppCompatActivity {
CameraView camera_view;
boolean isDetected = false;
private Button btn_start_again;
FirebaseVisionBarcodeDetectorOptions options;
FirebaseVisionBarcodeDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Dexter.withActivity(this)
.withPermissions(new String [] {Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO})
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
setUpCamera();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
Toast.makeText(getApplicationContext(),"You must accept the permissions",Toast.LENGTH_LONG).show();
}
}).check();
}
private void setUpCamera() {
btn_start_again =(Button)findViewById(R.id.btn_again);
btn_start_again.setEnabled(false);
btn_start_again.setOnClickListener((View v) -> isDetected = !isDetected);
camera_view = (CameraView) findViewById(R.id.cameraview);
camera_view.setLifecycleOwner(this);
camera_view.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame) {
processImage(getVisionImageFromFrame(frame));
}
});
FirebaseVisionBarcodeDetectorOptions options =
new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(
FirebaseVisionBarcode.FORMAT_QR_CODE,
FirebaseVisionBarcode.FORMAT_AZTEC)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private void processImage(FirebaseVisionImage image) {
if(!isDetected){
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"e.getMessage()",Toast.LENGTH_LONG).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
if(firebaseVisionBarcodes.size() > 0 ){
isDetected = true;
btn_start_again.setEnabled(isDetected);
for (FirebaseVisionBarcode item:firebaseVisionBarcodes){
Rect bounds = item.getBoundingBox();
Point[] corners = item.getCornerPoints();
String rawValue = item.getRawValue();
int value_type = item.getValueType();
switch (value_type){
case FirebaseVisionBarcode.TYPE_TEXT:
{
createDialog(item.getRawValue());
}
break;
case FirebaseVisionBarcode.TYPE_URL:
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getRawValue()));
startActivity(intent);
}
case FirebaseVisionBarcode.TYPE_CONTACT_INFO:
{
String info = new StringBuilder("Name:")
/*.append(item.getContactInfo().getName().getFormattedName())
.append("\n")*/
.append("Address")
.append(item.getContactInfo().getAddresses().get(0).getAddressLines())
.append("\n")
.append("Email:")
.append(item.getContactInfo().getEmails().get(0).getAddress())
.toString();
createDialog(info);
}
break;
default:
{
createDialog(rawValue);
}
break;
}
}
}
}
private void createDialog(String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(text);
builder.setPositiveButton("OK", ((DialogInterface dialog, int i) -> dialog.dismiss()));
AlertDialog dialog = builder.create();
dialog.show();
}
private FirebaseVisionImage getVisionImageFromFrame(Frame frame) {
byte[] data = frame.getData();
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setHeight(frame.getSize().getHeight())
.setWidth(frame.getSize().getWidth())
.build();
//.setRotation(frame.getRotation())
return FirebaseVisionImage.fromByteArray(data,metadata);
}
}
You have also a hardware problem.
The cameras of an android device usually only read the barcodes if they are focused correctly and that only happens with the rear camera since the front camera does not usually have autofocus.
Instead, QR codes are read even if they are not focused well.
In addition a normal camera is slow reading barcodes, if you want a device that reads all the codes quickly look for one with a built-in barcode reader, they are known as PDA, although they are much more expensive than a smartphone.

How to insert Scanned data in FireBase Realtime DataBase from QR/Barcode?

This is my code it is working fine it scans Qr/Barcode, but I want scanned data to insert in fire-base database. This app is connected with fire-base and using ML kit for barcode scanning. This app also has login signup connected with fire-base auth and scanner app. but I don't know how to push scanned data in fire-base realtime database in android studio.
public class MainActivity extends AppCompatActivity {
View view;
CameraView camera_view;
boolean isDetected= false;
Button btn_start_again;
private static final String TAG = "MainActivity";
FirebaseVisionBarcodeDetectorOptions options;
FirebaseVisionBarcodeDetector detector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
.getVisionBarcodeDetector();
Dexter.withActivity(this)
.withPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO})
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
setupCamera();
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
}
}).check();
}
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
private void setupCamera()
{
btn_start_again= (Button)findViewById(R.id.btn_again);
btn_start_again.setEnabled(isDetected);
btn_start_again.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDetected = !isDetected;
}
});
camera_view = (CameraView)findViewById(R.id.cameraView);
camera_view.setLifecycleOwner(this);
camera_view.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame)
{
processImage(getVisionImageFromFrame(frame));
}
});
options = new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private void processImage(FirebaseVisionImage image){
if(!isDetected)
{
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, ""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes){
if (firebaseVisionBarcodes.size()>0)
{
isDetected = true;
btn_start_again.setEnabled(isDetected);
for(FirebaseVisionBarcode item: firebaseVisionBarcodes)
{
int value_type = item.getValueType();
switch (value_type)
{
case FirebaseVisionBarcode.TYPE_TEXT:
{
createDialog(item.getRawValue());
}
break;
case FirebaseVisionBarcode.TYPE_URL:
{
//start browser intent
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(item.getRawValue()));
startActivity(intent);
}
break;
case FirebaseVisionBarcode.TYPE_CONTACT_INFO:
{
String info = new StringBuilder("Name: ")
.append(item.getContactInfo().getName().getFormattedName())
.append("\n")
.append("Address: ")
.append(item.getContactInfo().getAddresses().get(0).getAddressLines())
.append("\n")
.append("Email: ")
.append(item.getContactInfo().getEmails().get(0).getAddress())
.toString();
createDialog(info);
}
break;
default:
break;
}
}
}
}
private void createDialog(String text)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(text)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private FirebaseVisionImage getVisionImageFromFrame(Frame frame){
byte[] data= frame.getData();
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setHeight(frame.getSize() .getHeight())
.setWidth(frame.getSize() .getWidth())
//.setRotation(frame.getRotation())
.build();
return FirebaseVisionImage.fromByteArray(data,metadata);
}
}

(Android, Firebase) databasereference.push().setValue() not working even though log says otherwise

I'm testing Firebase by building an app that simply puts a message in the Database (authorisations are set to true for the test), it worked only once, and now nothing is pushed to the database. But as you can see I put logs everywhere to see where the problem is and surprisingly the onChildEventListener() seems to notice a change.
Here is the code for my main activity :
public class MainActivity extends AppCompatActivity {
public final static String TAG = "Main Activity";
public final int[] id = {0};
Button sendButton;
EditText messageEditText;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id[0] = 0;
sendButton = findViewById(R.id.send_message);
messageEditText = findViewById(R.id.message_text);
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("test/geomessage/");
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message = messageEditText.getText().toString();
Log.e(TAG, "Test 1");
GeoMessage currentGeomessage = new GeoMessage(id[0], message);
Log.e(TAG, "Test 2");
databaseReference.child("children").push().setValue(currentGeomessage).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.e(TAG, "Success !");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "FAIL");
}
}).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.e(TAG, "Complete");
}
});
Log.e(TAG, "Test 3");
}
});
databaseReference.child("children").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.e("101", "Child Added !");
id[0] = (int) dataSnapshot.getChildrenCount();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.e("101", "Child CHanged !");
id[0] = (int) dataSnapshot.getChildrenCount();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private static class GeoMessage {
int id;
String content;
public GeoMessage() {};
public GeoMessage(int id, String content) {
this.id = id;
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
}
Here are the logs when I click on the "Send" Button :
11-03 19:02:13.338 7440-7440/com.example.brumor.geofiretest E/Main Activity: Test 1
11-03 19:02:13.338 7440-7440/com.example.brumor.geofiretest E/Main Activity: Test 2
11-03 19:02:13.340 7440-7440/com.example.brumor.geofiretest E/Main Activity: Test 3
11-03 19:02:13.420 7440-7440/com.example.brumor.geofiretest E/101: Child Added !
The observed behavior occurs when the device does not have a connection to the Firebase servers. Calls to setValue() change the DB cache held locally in the client. This causes listeners for the changed location to fire. But the completion listeners for setValue() do not fire until the update to the Firebase server completes successfully or fails.
Check that your device has a network connection. You can detect the Firebase connection status using the example here.
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message = messageEditText.getText().toString();
GeoMessage currentGeomessage = new GeoMessage(id[0], message);
databaseReference.child("children").push().setValue(currentGeomessage);
}
});
No need to use addonSuccessListener to store data. Also it is not even entering the method addonSuccessListener , so its skipping the whole method and then it prints the Log for you, but nothing is entering the database. Usually onSuccessListener is used for firebase storage, to see if the task is successful or not.
Also according to this page: https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/tasks/Task
public abstract Task<T> addOnSuccessListener (OnSuccessListener<? super T> listener)
The above method is deprecated.
You have to use this now:
public abstract Task<T> addOnSuccessListener (Executor executor, OnSuccessListener<? super T> listener)

How to get emailid from Facebook Login in using facebook sdk version 3.22.0

I am using only one button when i click on the button then i want to get the email id.
Here is my code and get the ID and name, but emailid cannot get.I am using facebook sdk version 3.22.0 Please help me.
enter code here
package com.example.testintegration;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.testfbintegration.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.model.GraphUser;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static String APP_ID = "862722850469774"; // Replace with your App ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
// Buttons
Button btnFbLogin;
/*Button btnFbGetProfile;
Button btnPostToWall;
Button btnShowAccessTokens;*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
/*btnFbGetProfile = (Button) findViewById(R.id.btn_get_profile);
btnPostToWall = (Button) findViewById(R.id.btn_fb_post_to_wall);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);*/
mAsyncRunner = new AsyncFacebookRunner(facebook);
/**
* Login button Click event
* */
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
//loginToFacebook();
logfacebook();
}
});
/**
* Getting facebook Profile info
* *//*
btnFbGetProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
*//**
* Posting to Facebook Wall
* *//*
btnPostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postToWall();
}
});
*//**
* Showing Access Tokens
* *//*
btnShowAccessTokens.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAccessTokens();
}
});*/
}
public void logfacebook()
{
Session.openActiveSession(MainActivity.this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
System.out.println(user.getName());
System.out.println(user.getBirthday());
System.out.println(user.getFirstName());
System.out.println(user.getLastName());
System.out.println(user.getLink());
System.out.println(user.getUsername());
System.out.println(user.getLocation());
System.out.println("facebook user id" + user.getId());
System.out.println(user.asMap().get("email").toString());
// Session.OpenRequest open = new Session.OpenRequest(Login)
}
}
});
}
}
});
}
/**
* Function to login into facebook
* */
public void loginToFacebook() {
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);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
// btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
//btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
//btnShowAccessTokens.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
// btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
//btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
//btnShowAccessTokens.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Get Profile information by making request to Facebook Graph API
* */
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to show Access Tokens
* */
public void showAccessTokens() {
String access_token = facebook.getAccessToken();
Toast.makeText(getApplicationContext(),
"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
/*btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);*/
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}
use this code.
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback() {
#Override
public void onSuccess(LoginResult result) {
new GraphRequest();
// SocialSdkPrefrences.getInstance().setAccessToken(result.getAccessToken().getToken());
GraphRequest request = GraphRequest.newMeRequest(result.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Profile profile = Profile.getCurrentProfile();
FacebookGraphUser fbGraphUser = (FacebookGraphUser) JsonUtil.toModel(response.getRawResponse(), FacebookGraphUser.class);
if (fbGraphUser != null) {
String image_url = "http://graph.facebook.com/" + fbGraphUser.getId() + "/picture?type=large";
// UniversalImageLoaderUtil.loadImageWithDefaultImage(image_url, (ImageView) findViewById(R.id.user_image), null, R.drawable.place_holder_album);
User user=new User(fbGraphUser.getEmail(),image_url,profile.getName(),Long.parseLong(fbGraphUser.getId()));
Gson gson = new Gson();
Log.d("social", gson.toJson(user));
if (fbGraphUser.getEmail() != null) {
if (Util.isValidEmail(fbGraphUser.getEmail())) {
new SocialLogInAsyncTask(LoginActivity.this, user).execute();
} else {
Toast.showShortToast(LoginActivity.this, "You have not valid email,cant login");
}
} else {
Toast.showShortToast(LoginActivity.this, "You have not email,cant login");
}
} else {
Toast.showErrorToast(LoginActivity.this, R.string.error_signup);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.width(300)");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.d("tag", "cancel facebook login");
}
#Override
public void onError(FacebookException error) {
Log.d("tag", "error in login" + error.getMessage());
}
});
Please check this link of your answer & let me know if you find any problem in fb integration.
Unable to get emailId after login through fb in android
call this in your main Activity or the activity that is using FaceBookSignIn method
FacebookSdk.sdkInitialize(MainActivity.this);
add this method in your activity
public void FaceBookSignIn() {
callbackManager = CallbackManager.Factory.create();
loginType = Constants.loginTypeFaceBook;
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
DisplaySnackBar.display(getWindow().getDecorView().findViewById(android.R.id.content), "Success", true);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
try {
String email = jsonObject.getString(Constants.FacebookEmail),
String name = jsonObject.getString(Constants.FacebookName),
String firstName = jsonObject.getString(Constants.FacebookFirstName),
String lastName = jsonObject.getString(Constants.FacebookLastName),
String id = jsonObject.getString(Constants.FacebookID);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,birthday,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
DisplaySnackBar.display(getWindow().getDecorView().findViewById(android.R.id.content), "Sign In Cancel", true);
}
#Override
public void onError(FacebookException e) {
DisplaySnackBar.display(getWindow().getDecorView().findViewById(android.R.id.content), "Error", true);
}
});
}
Don't forget to add this dependency in your gradle build file
compile 'com.facebook.android:facebook-android-sdk:4.5.0'

Can't relogin with Facebook credentials after logout

I have an Android application that allow users to login with their Facebook credentials. Once they logout for the first time, they can't login again. After clearing the application's permission from the Applications page in user settings on Facebook's website, logging in works correctly.
I use a LoginButton to login.
Activities that need to be able to access the login information, extend this AuthActivity Activity.
public class AuthActivity extends Activity {
private AuthUtils authUtils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
authUtils = new AuthUtils(this);
authUtils.onCreate(savedInstanceState);
}
public AuthUtils getAuthUtils() {
return authUtils;
}
#Override
public void onStart() {
super.onStart();
authUtils.onStart();
}
#Override
public void onStop() {
super.onStop();
authUtils.onStop();
}
#Override
public void onResume() {
super.onResume();
authUtils.onResume();
}
#Override
public void onPause() {
super.onPause();
authUtils.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
authUtils.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
authUtils.onSaveInstanceState(outState);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
authUtils.onActivityResult(requestCode, resultCode, data);
}
}
AuthUtils look like this. I stripped of all Google+ login related stuff and everything that doesn't have anything to do with the login process, like saving the user information with my application preferences.
public class AuthUtils implements ConnectionCallbacks, OnConnectionFailedListener {
private final Activity activityContext;
private UiLifecycleHelper facebookUiHelper;
public AuthUtils(Activity context) {
this.activityContext = context;
facebookUiHelper = new UiLifecycleHelper(context, facebookStatusCallback);
}
public void signInFacebook() {
LoginButton facebookLoginButton = new LoginButton(activityContext);
facebookLoginButton.setReadPermissions(Arrays.asList("email"));
facebookLoginButton.performClick();
}
public void signOutFacebook() {
Session facebookSession = Session.getActiveSession();
if(facebookSession != null) {
facebookSession.closeAndClearTokenInformation();
}
}
private StatusCallback facebookStatusCallback = new StatusCallback() {
#Override
public void call(final Session session, SessionState state, Exception exception) {
if(state.isOpened()) {
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
String email = "";
if(user.asMap().containsKey("email")) {
email = user.getProperty("email").toString();
} else {
// ... not related to login
}
// Some actions here, not related to login.
}
});
} else if(state.isClosed()) {
// ... not related to login
}
}
};
public void onCreate(Bundle savedInstanceState) {
facebookUiHelper.onCreate(savedInstanceState);
}
public void onResume() {
facebookUiHelper.onResume();
}
public void onPause() {
facebookUiHelper.onPause();
}
public void onDestroy() {
facebookUiHelper.onDestroy();
}
public void onSaveInstanceState(Bundle outState) {
facebookUiHelper.onSaveInstanceState(outState);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
facebookUiHelper.onActivityResult(requestCode, resultCode, data);
}
}
I had the same problem, even when running Facebook's sample apps. I solved this by providing my default signing key to Facebook: both in my Developer Settings for the Sample Apps at https://developers.facebook.com/settings/developer/sample-app/ and then in your Apps settings in the Android platform.
Facebook suggests an easy way to get at your default key which can be found under Troubleshooting at https://developers.facebook.com/docs/android/getting-started. The code for doing so when running the Hello Facebook example app is provided below.
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.facebook.samples.hellofacebook",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
Note: When you're publishing apps, you shouldn't be using the default key and be generating and signing apps with your own.

Categories