Barcode scanner is reading only QR codes using ML Kit - java

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.

Related

In my app I can't transfer the picture I took from the Camera to the app

I made an automobile management application.
I made a vehicle image adding system in the application.
When the Image is selected I want to upload it to firebase and view it.
When I select a picture from the gallery, I can upload and view it, it works without any problems.
At the same time, when I select Camera, I ask for permission and access the camera, but this is the part that doesn't work. After I take the picture from the camera, I return to the application, but the picture I took is not visible. I don't know how to do this.
And.. I don't know how to code.
I'm trying to watch video lessons and adapt them the way I want to make the applications in my head.
This application is the last point I came to.
As far as I saw the answers to the previous questions and the videos, I could not answer this question.
I know it will be difficult, but can you show this ignorant the correct method?
`
public class UploadActivity extends AppCompatActivity {
Uri imageData;
ActivityResultLauncher<Intent> activityResultLauncher;
ActivityResultLauncher<String> permissionLauncher;
private ActivityUploadBinding binding;
private FirebaseStorage firebaseStorage;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Burada Yazan kod ustteki standart titleyi kaldirmak icin.
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide();
// Burada Bitiyor.
binding = ActivityUploadBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
registerLauncher();
//Firebase fireStorage icin
firebaseStorage = FirebaseStorage.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
storageReference = firebaseStorage.getReference();
`
`
public void selectImage(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Resim Seciniz");
builder.setMessage("Resim Kaynagini Seciniz");
builder.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
/* if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE); */
if (ContextCompat.checkSelfPermission(UploadActivity.this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(UploadActivity.this,Manifest.permission.CAMERA)) {
Snackbar.make(view,"Kameraniza Erismek icin izin gereklidir.",Snackbar.LENGTH_INDEFINITE).setAction("izin Ver", new View.OnClickListener() {
#Override
public void onClick(View view) {
permissionLauncher.launch(Manifest.permission.CAMERA);
}
}).show();
} else {
permissionLauncher.launch(Manifest.permission.CAMERA);
}
} else {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activityResultLauncher.launch(takePicture);
}
dialogInterface.dismiss();
}
});
builder.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(ContextCompat.checkSelfPermission(UploadActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(UploadActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE)) {
Snackbar.make(view,"Galerinize erişmek için izin gereklidir.",Snackbar.LENGTH_INDEFINITE).setAction("İzin Ver", new View.OnClickListener() {
#Override
public void onClick(View v) {
//izin isteyecegiz.
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
}
}).show();
} else {
//Ekstra izin isteyecegiz.
permissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
}
} else {
// Zaten izin verilmis ise.
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(pickPhoto);
}
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void registerLauncher() {
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
Intent intentFromResult = result.getData();
if(intentFromResult != null) {
imageData = intentFromResult.getData();
binding.addCarPicture.setImageURI(imageData);
}
}
}
});
permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), new ActivityResultCallback<Boolean>() {
#Override
public void onActivityResult(Boolean result) {
if(result) {
Intent intentToGallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activityResultLauncher.launch(intentToGallery);
} else {
Toast.makeText(UploadActivity.this,"iznine ihtiyacimiz var",Toast.LENGTH_LONG).show();
}
}
});
}
`
A couple of things.
You should use request codes, so you can check for it in you activity result method and use some logic to distinguish between taking a picture and selecting a photo from the gallery. Because the Gallery and Camera return different different things.
Second, the image taken from the camera isn't saved. It doesn't have a URI location, because it's just in memory.
if(intentFromResult != null) {
imageData = intentFromResult.getData();
Bitmap img = (Bitmap)(data.getExtras().get()'data'));
//Upload img to Database
//Set imageView from Database
}
Here is the documentation on the way you are trying to implement it:
https://developer.android.com/training/camera-deprecated/photobasics
Here is the current documentation on how it should be implemented:
https://developer.android.com/guide/topics/media/camera
And one last bit to think about. It might be better to use a library so you don't have to write a whole new implementation.
I've used https://github.com/Dhaval2404/ImagePicker before, it's ok. There might be a better one out there that suits your needs. Take your time and look around.

Which function returns the recorded audio when I use SpeechRecognizer in android studio?

I am building a custom keyboard app(in android studio) in which I added a microphone key. I wanted to convert the recorded speech to text so I used speechrecognizer. But I also want the recorded audio. I want that my keyboard app when records the audio in chatting applications like whatsapp, it should send that audio as the message. Could somebody help me how to get the recorded audio when i use speechrecognizer. I need to use speechrecognizer only as i need it for other purpose.
(p.s: my app do not have any activity)
This is the code for recording speech and converting to text.
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "com.example.keyboard");
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this.getApplicationContext());
RecognitionListener listener = new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
Toast.makeText(EDMTKeyboard.this, "Recording Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onBeginningOfSpeech() {
Toast.makeText(EDMTKeyboard.this, "Recording Started", Toast.LENGTH_SHORT).show();
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int error) {
System.err.println("Error listening for speech: " + error);
Toast.makeText(EDMTKeyboard.this, "ERROR-"+error, Toast.LENGTH_SHORT).show();
}
#Override
public void onResults(Bundle results) {
Bundle bundle = intent.getExtras();
ArrayList<String> voiceResults = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults == null) {
System.out.println("No voice results");
} else {
System.out.println("Printing matches: ");
for (String match : voiceResults) {
Toast.makeText(EDMTKeyboard.this, match, Toast.LENGTH_SHORT).show();
ic.commitText(match,match.length());
str = str + match;
I=I+match.length()+1;
//System.out.println(match);
}
}
}
#Override
public void onPartialResults(Bundle partialResults) {
}
#Override
public void onEvent(int eventType, Bundle params) {
}
};
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
I checked the questions similar to this in stackoverflow, but the answers given were not working at present(may be the android studio had removed those functions).

Firebase ML kit's QR Code Scanner Scans each QR Code Multiple Times

My scanner scans single QR Code multiple times thats why my createDialog method runs multiple time where i get the info regarding QR code and the user who is using it and the agent who posted it and store data into users node in Db and because it run multiple time my Db cant keep track of the no. of times the qr code scanned for each user..
private void setupCamera() {
startAgain.setEnabled(isDetected);
startAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDetected = !isDetected;
}
});
cameraView.setLifecycleOwner(this);
cameraView.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame) {
processorImage((FirebaseVisionImage) getVisionImageFromFrame(frame));
}
});
options = new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private Object 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();
return FirebaseVisionImage.fromByteArray(data, metadata);
}
private void processorImage(FirebaseVisionImage image) {
if (!isDetected) {
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
}).addOnCompleteListener(new OnCompleteListener<List<FirebaseVisionBarcode>>() {
#Override
public void onComplete(#NonNull Task<List<FirebaseVisionBarcode>> task) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StoreScanQR.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
if (firebaseVisionBarcodes.size() > 0) {
isDetected = true;
startAgain.setEnabled(isDetected);
for (FirebaseVisionBarcode item : firebaseVisionBarcodes) {
try {
createDialog(item.getRawValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Detection is an asynchronous call, so it may be triggered multiple times with different inputs before you can get the first result. If you only care about the first detected result, you can check your isDetected flag at the result processing side (i.e. in #onSuccess callback) rather than detection triggering side.
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
if (!isDetected) {
processResult(firebaseVisionBarcodes);
}
}

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);
}
}

How post to wall facebook android-sdk:4.0.0

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);
}
}

Categories