Android Facebook share dialog custom story with url and image - java

Below you can find my code for sharing custom story using open graph with some custom fields. Image and Url not working - I'm getting error: com.facebook.FacebookException, and nothing more when Url is added, when I set only image I'm getting Toast with "Unidentified error" message:
OpenGraphObject spent = OpenGraphObject.Factory.createForPost("namespace:spent");
spent.setProperty("og:type", "namespace:" + categorySlug.replace("-", "_"));
//Not working -- spent.setProperty("og:url", "http://example.com");
//Not working -- spent.setUrl("http://example.com");
//Not working -- spent.setProperty("og:image", "http://example.com/image.png");
//Not working -- spent.setImageUrls(Arrays.asList("http://example.com/image.png"));
spent.setProperty("og:title", "Title");
spent.setProperty("og:description", "Description");
spent.setProperty("namespace:hours", container.getHours());
spent.setProperty("namespace:minutes", container.getMinutes());
spent.setProperty("namespace:seconds", container.getSeconds());
spent.setType("namespace:mycustomobject");
OpenGraphAction action = GraphObject.Factory.create(OpenGraphAction.class);
action.setProperty("mycostomobject", spent);
action.setType("namespace:spent");
final FacebookDialog shareDialog = new FacebookDialog.OpenGraphActionDialogBuilder(
this,
action,
"mycustomobject"
).build();
if(FacebookDialog.canPresentShareDialog(context,FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
uiLifecycleHelper.trackPendingDialogCall(shareDialog.present());
}
Image is showing in preview. But when I click publish I'm getting error mentioned above.
However my request with JSON code is working and sharing an image:
StringBuilder sb = new StringBuilder();
sb.append("{")
.append("\"").append("og:type").append("\":\"").append("namespace:").append(categorySlug.replace("-", "_")).append("\",")
.append("\"").append("og:url").append("\":\"").append("http://example.com").append("\",")
.append("\"").append("og:title").append("\":\"").append("Title").append("\",")
.append("\"").append("og:image").append("\":\"").append("http://example.com/icon.png").append("\",")
.append("\"").append("og:description").append("\":\"").append("Desc").append("\",")
.append("\"").append("namespace:hours").append("\":\"").append(container.getHours()).append("\",")
.append("\"").append("namespace:minutes").append("\":\"").append(container.getMinutes()).append("\",")
.append("\"").append("namespace:seconds").append("\":\"").append(container.getSeconds()).append("\"")
.append("}");
final Bundle object = new Bundle();
object.putString(categorySlug.replace("-","_"), sb.toString());
object.putBoolean("fb:explicitly_shared", true);
Request request = new Request(
Session.getActiveSession(),
"me/namespace:spent",
object,
HttpMethod.POST,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response != null && response.getError() != null) Log.d("Facebook Share", "Error message:" + response.getError().getErrorCode() + ", " + response.getError().getErrorMessage());
if(response != null && response.getGraphObject() != null){
Toast.makeText(context, "Success!", Toast.LENGTH_SHORT).show();
}
}
}
);
request.executeAsync();
Notes:
Images are present in server.
I've changed namespaces and domains so there could be an errors in names
Exception when I uncomment addProperty("og:image",""): https://gist.github.com/Averus89/55a86b3618f143926eb2

Related

How to send MMS with video/audio attachment programmatically on Android 12 using klinker package

I had this code working on Android 10 but something in Android 12 is breaking the logic. I am trying to send MMS with an attached video using the klinker package on my Android app on Android 12 phones. I can send pictures just fine but attaching audio and video do not work. The code used to be message.setVideo but that got deprecated. Now it is message.addVideo. But it is not working. It sets the bytes to the message but no MMS is sent. Does anyone know a fix for the klinker route or point me to a different direction to send audio and video MMS programmatically on Android 12?
Current code:
public void mmsSend() {
runOnUiThread(new Runnable() {
//#Override
public void run() {
try {
com.klinker.android.send_message.Settings sendSettings = new com.klinker.android.send_message.Settings();
sendSettings.setUseSystemSending(true);
Transaction transaction = new Transaction(mContext, sendSettings);
Message message = new Message(msgBodyMMS, PhoneNumberMMS);
byte[] mediaBytes = null;
//Convert media file to byte array
if (mAttachType != -1)
switch (mAttachType) {
case ProtocolConstants.MSG_NUM_MESSAGE_ATTACH_PICTURE:
File imgFile = new File(mAttachLocation);
if (imgFile.exists()) {
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
message.setImage(myBitmap);
}
break;
case ProtocolConstants.MSG_NUM_MESSAGE_ATTACH_AUDIO:
mediaBytes = convertMediaToBytes(mAttachLocation);
message.addAudio(mediaBytes);
break;
case ProtocolConstants.MSG_NUM_MESSAGE_ATTACH_VIDEO:
mediaBytes = convertMediaToBytes(mAttachLocation);
message.addVideo(mediaBytes);
break;
}
else if (mediaBytes == null) {
message.setImage(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.android));
}
message.setFromAddress(Utils.getMyPhoneNumber(mContext));
message.setSave(false);
message.setSubject(msgBodyMMS);
Uri uri = Uri.parse("content://mms-sms/conversations/");
message.setMessageUri(uri);
transaction.sendNewMessage(message, Transaction.NO_THREAD_ID);
Log.d(TAG, "mmsSend() : MMS Sent Successfully");
lastMMSMessageSent = ClientProtocol.Mms_Send_Ok();
appClass.BluetoothWrite(lastMMSMessageSent);
Toast.makeText(mContext.getApplicationContext(),"MMS Sent Successfully",Toast.LENGTH_LONG ).show();
} catch (Exception e) {
Log.d(TAG, "mmsSend() : MMS send failed " + e.toString());
Toast.makeText(mContext.getApplicationContext(),
"MMS failed, please try again later ! ",
Toast.LENGTH_LONG).show();
}
}
});
}

Keep receiving this error "Failed to initialize detector". Am I not loading the tflite model correctly?

I am trying to setup an ImageAnalyzer with my Android app so I can run object classification using Google's ML Kit API. The issue I am currently facing, as the title suggests, is constantly seeing the error "Failed to initialize detector".
I've reread this tutorial about three times now and followed this post about someone facing the same error (although for a different reason) to no avail. I've also made sure everything with the CameraX API (except the ImageAnalyzer code that I will show in a second) works as expected.
As mentioned in the ML Kit documentation, here is the code I have regarding setting up a LocalModel, a CustomObjectDetectorOptions, and an ObjectDetector:
LocalModel localModel = new LocalModel.Builder()
.setAssetFilePath("mobilenet_v1_1.0_224_quantized_1_metadata_1.tflite")
.build();
CustomObjectDetectorOptions customObjectDetectorOptions =
new CustomObjectDetectorOptions.Builder(localModel)
.setDetectorMode(CustomObjectDetectorOptions.STREAM_MODE)
.enableClassification()
.setClassificationConfidenceThreshold(0.5f)
.setMaxPerObjectLabelCount(3)
.build();
ObjectDetector objectDetector = ObjectDetection.getClient(customObjectDetectorOptions);
Here is the ImageAnalyzer code I have, which basically makes a call to the ML Kit API by way of the processImage helper method:
// Creates an ImageAnalysis for analyzing the camera preview feed
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setTargetResolution(new Size(224, 224))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build();
imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(this),
new ImageAnalysis.Analyzer() {
#Override
public void analyze(#NonNull ImageProxy imageProxy) {
#SuppressLint("UnsafeExperimentalUsageError") Image mediaImage =
imageProxy.getImage();
if (mediaImage != null) {
Log.i(TAG, "Obtained ImageProxy object");
processImage(mediaImage, imageProxy)
.addOnCompleteListener(new OnCompleteListener<List<DetectedObject>>() {
#Override
public void onComplete(#NonNull Task<List<DetectedObject>> task) {
imageProxy.close();
}
});
}
}
});
Here is the processImage helper method, where I actually call objectDetector.process(...), the line of code that actually runs the tflite model.
private Task<List<DetectedObject>> processImage(Image mediaImage, ImageProxy imageProxy) {
InputImage image =
InputImage.fromMediaImage(mediaImage,
imageProxy.getImageInfo().getRotationDegrees());
return objectDetector.process(image)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String error = "Failed to process. Error: " + e.getMessage();
Log.i(TAG, error);
}
})
.addOnSuccessListener(new OnSuccessListener<List<DetectedObject>>() {
#Override
public void onSuccess(List<DetectedObject> results) {
String success = "Object(s) detected successfully!";
Log.i(TAG, success);
for (DetectedObject detectedObject : results) {
Rect boundingBox = detectedObject.getBoundingBox();
Integer trackingId = detectedObject.getTrackingId();
for (DetectedObject.Label label : detectedObject.getLabels()) {
String text = label.getText();
int index = label.getIndex();
float confidence = label.getConfidence();
Log.i(TAG, "Object detected: " + text + "; "
+ "Confidence: " + confidence);
}
}
}
});
}
Essentially, once I run the app, logcat just keeps logging these two lines on repeat. I know it means the ImageAnalyzer is continuously trying to analyze the image input, but for some reason the LocalModel just cannot process the input
2021-01-21 22:02:24.020 9328-9328/com.example.camerax I/MainActivity: Obtained ImageProxy object
2021-01-21 22:02:24.036 9328-9328/com.example.camerax I/MainActivity: Failed to process. Error: Failed to initialize detector.
I have only just started to work with Android, especially ML in Android, so any sort of help would be appreciated!
I managed to fix my issue before anyone answered, but in case anyone who just started to learn Android like me I'll leave my solution here.
Basically, remember to create an asset folder in the /src/main directory rather than the /src/androidTest directory :P
Once I did that, the model loaded correctly and now I just have to figure out how to display the results in my application.
// Do NOT compress tflite model files (need to call out to developers!)
aaptOptions {
noCompress "tflite"
}
add this line in build gradle for app under android tag

Converting Android Volley Request to iOS NSURL asynchronous request

I have the following method in my Android app which I use for user login/registration.
public void registerUser(final String username, final String email, final String password) {
pDialog.setMessage("Signing Up...");
pDialog.show();
request = new StringRequest(Method.POST, SL_URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
pDialog.dismiss();
String[] split = s.split("Config.php");
String after = split[1];
try {
JSONObject jsonObject = new JSONObject(after);
boolean error = jsonObject.getBoolean("error");
if (error) {
String errorMsg = jsonObject.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
} else {
session.setLogin(true, username, email);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("tag", "login");
hashMap.put("username", name);
hashMap.put("password", password);
return hashMap;
}
};
queue.add(request);
}
Now I am writing my app for iOS and trying to replicate this in Swift. So far I have the following code:
let username = usernameTxt.text
let password = passwordTxt.text
let urlPath: String = "***"
let url: NSURL = NSURL(string: urlPath)!
let request1: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request1.HTTPMethod = "POST"
let stringPost="tag=login&username=" + username! + "&password=" + password! // Key and Value
NSLog(stringPost)
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
request1.timeoutInterval = 60
request1.HTTPBody=data
request1.HTTPShouldHandleCookies=false
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request1, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {
var jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
} catch _ {}
})
Now as someone new to iOS development and Swift in general, I have the following questions:
What is the best way to replicate the progressDialog I use in Java in Swift, it must be visible until the request is complete and then it should be dismissed. I'm guessing this should be placed in the completionHandler, however I'm not sure which UI element to use for the progress Dialog.
How do I obtain my response as a String and replicate the behaviour of the split function, and then convert the result of this into a jsonObject like I do in my Java code.
What is the best way to replicate the Toast used to show the error message. I don't think using a dialog which must be closed with a button would be optimal here.
Thank you.
I am also developing Applications for Android and IOS. Here i Answered your three Problems which is faced by me also as a beginner. I hope this would help you.
1) Use MBProgressHUD Link to replicate the progressDialog in Swift .There are two method to show and dismiss the progressDialog:
Use showLoadingHUD() before making HTTP request
private func showLoadingHUD() {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.labelText = "Loading..."
}
And hideLoadingHUD() after receiving the response from server
private func hideLoadingHUD() {
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
}
2) you can use Alamofire Link which can handle Network stuff And you can easily obtain response in String.
Example:
self.showLoadingHUD()
Alamofire.request(.GET, data, parameters: nil)
.response { (request, response, data, error) in
print(data) // if you want to check data in debug window.
let Result = NSString(data: data!, encoding: NSUTF8StringEncoding)
Result!.stringByReplacingOccurrencesOfString("\"", withString: "")
if(newResult == "1"){
self.navigationController!.popViewControllerAnimated(true)
JLToast.makeText("Success").show()
}
else if (newResult == "0"){
JLToast.makeText("Failed").show()
}
self.hideLoadingHUD()
3) mankee Toas are used for a purpose of displaying information for short period of time and disappear themselves. Here we can use Android like Toast which is JLToast. Available on github .
JLToast.makeText("Success").show()

Facebook SDK for Android null pointer exception

I'm following simple tutorial at: https://developers.facebook.com/docs/android/getting-started/ and after I made everything work, I have problems onCompleted callback method.
My code looks like this:
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) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello " + user.getName() + "!");
}
}
}).executeAsync();
since executeMeRequestAsync method from tutorial was deprecated. Everything passes fine, and user != null evaluates as true so I come inside of the block, but on user.getName() I always get NullPointerException and I've checked while debugging GraphUser instance, and it was filled with null values. What I might be doing wrong? Can it be some problems with application configuration? I've generated new KeyHash and it's correct, so I don't know what else would be incorrect.
A NullPointerException can be thrown if findViewById(R.id.welcome) returns null. You can modify your logic to check for welcome as well:
public void onCompleted(GraphUser user, Response response) {
TextView welcome = (TextView) findViewById(R.id.welcome);
if(user != null && welcome != null) {
welcome.setText("Hello " + user.getName() + "!");
}
else {
// Log it in some way
}
}

New Facebook SDK + Android. Add Image on wall facebook

I can not find a working way to send a picture on the wall.
My code is that I do not.
Bundle postParams = new Bundle();
postParams.putByteArray("image", byteArray);
postParams.putString("message", "A wall picture");
Session session = Session.getActiveSession();
if (session != null) {
Log.e("Session", "don t null");
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
I've never sent pictures from the phone, but from a server using an image link. I'll put this code in case it helps you since most of the logic is similar.
final Bundle parameters = new Bundle();
parameters.putString("name", getString(R.string.app_name));
parameters.putString("caption", "haha");
parameters.putString("link", "www.google.com");
parameters.putByteArray("picture", byteArray);//I took this one from your code. My key is "picture" instead of "image"
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
new FeedDialogBuilder(EndGameActivity.this, session, parameters).build().show();
//you can try this one instead of the one above if you want, but both work well
//Request.newMeRequest(session, new Request.GraphUserCallback() {
//
// #Override
// public void onCompleted(GraphUser user, Response response) {
// final Session session = Session.getActiveSession();
// new FeedDialogBuilder(EndGameActivity.this, session, parameters).build().show();
// }
//}).executeAsync();
}
}
});
This code will only work in the last Facebook SDK 3.5 since Request.newMeRequest was recently introduced and should be used instead of Request.executeMeRequestAsync, which has been deprecated.
Also notice that the key I use is "picture" instead of "image". Maybe that's the problem with your code.
But I do it inside a onClick event when the user touch a button. Why do you need it in your onCreate method?

Categories

Resources