I'm trying to upload photo to Facebook from my Android App and it works fine, photo is uploaded, problem is, Facebook app doesn't open, my App simply uploads photo directly to News Feed, but without option to maybe discard it, or change text or antything, so what i would like is to open facebook post with my image attached but not posted until i click the "post"
here is my code :
Bitmap img = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Request uploadRequest = Request.newUploadPhotoRequest(
Session.getActiveSession(), img, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Toast.makeText(MyActivity.this,
"Photo uploaded successfully",
Toast.LENGTH_LONG).show();
}
});
uploadRequest.executeAsync();
I googled around for hours, and this facebook sdk is messed up, i can't seem to find any proper answer, if i use shareDialog facebook provides, i can't share local images, if i dont use share dialog i can't open facebook app, and i don't want to use OpenGraph stories .. Any help would be gravely appreciated.
You can post imade or text into facebook by using facebook SDK wich is explaned here
and to post an image
private void postImageToWall(String accessToken,byte[] image, String text){
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
//text with the image
params.putString("message",text);
// The byte array is the data of a picture.
params.putByteArray("picture", image);
try {
facebook.request("me/photos", params, "POST");
uploadSucceed = true;
} catch (FileNotFoundException fileNotFoundException) {
showToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
showToast(malformedURLException.getMessage());
} catch (IOException ioException) {
showToast(ioException.getMessage());
}
}
Related
i have webview where if you create a url ending in m3u8 it will open an external player,
#Override
// Force links to be opened inside WebView and not in Default Browser
// Thanks http://stackoverflow.com/a/33681975/1815624
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".m3u8") || url.endsWith(".ts") || url.endsWith(".mpd") || url.endsWith(".mp4"))
{
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
intent.setPackage("com.genuine.leone");
view.getContext().startActivity(intent);
return true; // to tell the WebView that it should not load the URL because you handled it by yourself
}
catch (ActivityNotFoundException e) {
// Player is not installed, you may want to open the play store link
}
}
the problem now, m3u8 requires a widevine license to play, how to send a widevine license url to the external player
i have to research but not find anything, any idea?
I have the below list of test video links which i am am trying to set it on my VideoView. The first two works fine but the third one shows java.net.ProtocalException and I have the same problem when i user the link from my local Spring Web Application Server. How to play such link in videoView?
The list of links
1. VIDEO_SOURCE = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/SubaruOutbackOnStreetAndDirt.mp4";
2. VIDEO_SOURCE = "https://media.geeksforgeeks.org/wp-content/uploads/20201217192146/Screenrecorder-2020-12-17-19-17-36-828.mp4?_=1";
3. VIDEO_SOURCE = "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4";
VideoView Code
if( URLUtil.isValidUrl(VIDEO_SOURCE)){
try{
videoUri = getMedia(VIDEO_SOURCE);
// Set up the media controller widget and attach it to the video view.
MediaController controller = new MediaController(_CourseContents.this);
// anchor view for the videoView
controller.setAnchorView(mVideoView);
// sets the media player to the videoView
controller.setMediaPlayer(mVideoView);
// sets the media controller to the videoView
mVideoView.setMediaController(controller);
mVideoView.setVideoURI(videoUri);
try {
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
} catch (Exception e) {
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "Cannot parse video source:" + e.getMessage(), Toast.LENGTH_LONG).show();
finish();
}}else {
Toast.makeText(getApplicationContext(), "Invalid video source.", Toast.LENGTH_LONG).show();
finish();
}
The Error
I have an app that allow user to upload a photo on wall.
The code works well for the majority of users, but I have reported that the application crashes sometimes when uploading photo.
The problem is not in taking the pictures from the camera, but it is when you have to take the path of the picture.
The version of Android that is causing this problem is 4.4.2, but I do not understand how to fix it.
post some code:
activityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
try {
//picUri is a global variable Uri
picUri = data.getData();
cropImage();
} catch (Exception e) {
e.printStackTrace();
}
}
else if(requestCode == PIC_CROP) {
try{
//thumbnail is a global variable Bitmap
thumbnail = MediaStore.Images.Media.getBitmap(context.getContentResolver(), cropImageUri);
setImage();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
hot to crop image:
public void cropImage() {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("scale", true);
//indicate output X and Y
cropIntent.putExtra("outputX", 700);
cropIntent.putExtra("outputY", 700);
//retrieve data on return
cropIntent.putExtra("return-data", false);
File f = createNewFile("CROP_");
try{
f.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
//cropImageUri is a global variable Uri
cropImageUri = Uri.fromFile(f);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}
catch(ActivityNotFoundException anfe){
anfe.printStackTrace();
}
}
create new File:
private File createNewFile(String prefix) {
if (prefix== null) {
prefix="IMG_";
}
else if("".equalsIgnoreCase(prefix)) {
prefix="IMG_";
}
File newDirectory = new File(Environment.getExternalStorageDirectory()+"/mypics/");
if (!newDirectory.exists()) {
if (newDirectory.mkdir()) {
}
}
File file = new File(newDirectory,(prefix+System.currentTimeMillis()+".jpg"));
if (file.exists()) {
file.delete();
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
then when a user click on "send" method preUploadImage is called:
public void preUploadImage() {
UploadImage uploadImage = new UploadImage();
Uri newUri = getImageUri(thumbnail);
try{
// System.out.println("uri = "+picUri);
uploadImage.upload(getRealPathFromURI(newUri));
}
catch (IOException e) {
e.printStackTrace();
}
}
public Uri getImageUri(Bitmap inImage) {
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
and in the last row the error appears.
return Uri.parse(path);
this row cause a NullPointerException
java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:468)
at android.net.Uri$StringUri.<init>(Uri.java:458)
at android.net.Uri.parse(Uri.java:430)
at com.delsorboilario.verdebio.ScriviDomanda.getImageUri(ScriviDomanda.java:584)
at com.delsorboilario.verdebio.ScriviDomanda.preUploadImage(ScriviDomanda.java:608)
at com.delsorboilario.verdebio.ScriviDomanda$6$4$2.run(ScriviDomanda.java:292)
I have not attempted to use insertImage(), and in this case, it is not quite clear why you would need it.
Primarily, it seems like you are looking to upload the photo. For that, all you need is the File that you created in createNewFile(). If you are uploading it yourself (e.g., HttpUrlConnection, some third-party library), you should be able to just use the File or an InputStream on it. Even if the upload code really needs a Uri, you can try Uri.fromFile() to get a Uri from your File and see if that works.
Where MediaStore does come into play is making your file be indexed and therefore accessible to apps (ones that query the MediaStore for images) and to users (via their MTP connection through their USB cable). MediaScannerConnection and its static scanFile() method are a fairly straightforward way to get the file indexed. Just make sure your file is fully written to disk first (e.g., if you are writing the file yourself, call getFD().sync() on your FileOutputStream after flush() and before close()).
Looks like MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Title", null); return null.
Form the documentation of MediaStore.Images.Media
Insert an image and create a thumbnail for it.
Parameters
cr The content resolver to use
source The stream to use for the image
title The name of the image
description The description of the image
Returns The URL to the newly created image, or null if the image
failed to be stored for any reason
Can we have any optimise way to run video.Below mention is my code.This code help in run the youtube video.
if (YouTubeIntents.canResolvePlayVideoIntent(activity)){
//Getting ID of YouTube video out of URL
List<NameValuePair> params = null;
try {
params = URLEncodedUtils.parse(new URI(sourceUrl), "UTF-8");
} catch (URISyntaxException e) {
e.printStackTrace();
}
String videoID = params.get(0).getValue();
Log.v(TAG, "YouTube Video ID:" + videoID);
// createPlayVideoIntentWithOptions only works for first
// video playback. Update to use stand-alone player api instead.
Intent intent = YouTubeStandalonePlayer.createVideoIntent(
activity, g.kGoogleAPIKey,
videoID, 0, true, false);
activity.startActivity(intent);
Log.i(TAG, "Video Playing in YouTube App....");
} else {
Log.v(TAG, "YouTube generic intent");
activity.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(sourceUrl)));
Log.i(TAG, "Video Playing in whatever user selected....");
}
your question is a bit vague.. if all you want to do is play a youTube video from your app you can easily just call the yourtube intent.. and pass the url of the video as an extra. this would open youTube..
alternatively you can get access to the youTube Player api: https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/package-summary
which you will have to get an api key and do something like this:
This example looks to see if the standalone player is available to your user and if it isn't calls youtube directly as stated in the first part of my answer
if (YouTubeIntents.canResolvePlayVideoIntent(activity)){
//Getting ID of YouTube video out of URL
List<NameValuePair> params = null;
try {
params = URLEncodedUtils.parse(new URI(sourceUrl), "UTF-8");
} catch (URISyntaxException e) {
e.printStackTrace();
}
String videoID = params.get(0).getValue();
Log.v(TAG, "YouTube Video ID:" + videoID);
// createPlayVideoIntentWithOptions only works for first
// video playback. Update to use stand-alone player api instead.
Intent intent = YouTubeStandalonePlayer.createVideoIntent(
activity, g.kGoogleAPIKey,
videoID, 0, true, false);
activity.startActivity(intent);
Log.i(TAG, "Video Playing in YouTube App....");
} else {
Log.v(TAG, "YouTube generic intent");
activity.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(sourceUrl)));
Log.i(TAG, "Video Playing in whatever user selected....");
}
trying to get my first android widget and let me tell you moving from Visual Studio Pro to eclipse is not a smooth thing!
Anyway i run into the above error which gives me some trouble to solve. Ive searched for all possible duplicates and it seems that this error occurs when the app hits IPC size (ie. big images)
My small widget launches an intentservice to download some info from the web and one image. the original image size of the png is around 100k. However before i update widget I downscale to around 17k. (checked with memory tracker size was 16400bytes[]).
and yet the update fails. if i remove the image the update is successful.
this is the listener in widgetprovider which get executed:
public void onHttpLoaded(Bitmap image, String titlestring, String subtitlestring)
{
Context context = getApplicationContext();
if (image == null) //no data?
{
Toast.makeText(context, context.getResources().getString(R.string.null_data_toast), Toast.LENGTH_LONG);
return;// exit!
}
try
{
RemoteViews widgetView = new RemoteViews(this.getPackageName(), R.layout.main);
widgetView.setTextViewText(R.id.title, titlestring);
//all other comment out
//The problem!
widgetView.setImageViewBitmap(R.id.main_icon, image);
//Get global appwidgetmanager
AppWidgetManager manager = AppWidgetManager.getInstance(this);
//update widget
manager.updateAppWidget(Constants.THIS_APPWIDGET, widgetView);
}
catch (Exception e)
{
Log.d("onHttpLoaded", e.toString());
}
}
and the onHandleIntent from my service that the above code gets called:
protected void onHandleIntent(Intent intent)
{
resources = getApplicationContext().getResources();
int iAppWidgetId;
try
{
iAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
catch (Exception e)
{
Log.d("Service", "WidgetID not found");
}
//comment out stuff...
//launch new httpTask
httpTask myhttpTask = new httpTask(tittlestring, subtitlestring, (myHttpListener) MyUpdateService.this, MyUpdateService.this);
//limit size of bitmap
myhttpTask.setSampleSize(Constants.BITMAP_SAMPLE_SIZE); //size = 4
myhttpTask.execute();
}
all tests are done in emulator.
one detail that may be important is that in logcat i get 20-30 fail messages "!!! failed binder transaction !!!"
any ideas on how i messed this up?
thnks!
solved. it was a memory problem of the emulator.