upload / post video by facebook sdk 3.0.1 [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
all the code i saw until now not working with sdk 3.0.1
like this code :
Is uploading videos from an SD Card to Facebook possible with the Facebook SDK?
i think this because facebook change util file, but i not sure.
i will glud if someone will share with us (many developer that search for this code) working code (on sdk 3.0.1) that upload successfully mp4 file video to facebook wall from sd cards.
thanks ahead

Try this code, it is working:
File file=new File(Environment.getExternalStorageDirectory()+"/testvideo.mp4");
try {
Request audioRequest = Request.newUploadVideoRequest(session, file, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
if(response.getError()==null)
{
Toast.makeText(MainActivity.this, "Video Shared Successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
});
audioRequest.executeAsync();
} catch (Exception e) {
e.printStackTrace();
}

This is a working to upload video on facebook with sdk 3.0.1
Enjoy...:)
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
this.requestPublishPermissions(session);
this.is_return = true;
return;
}
Session session = Session.getActiveSession();
if (session != null){
Request.Callback requestCallback= new Request.Callback() {
public void onCompleted(Response response) {
final FacebookRequestError error = response.getError();
if(SubmitPost.this.pDialog.isShowing()) {
SubmitPost.this.pDialog.dismiss();
}
if (error != null) {
new AlertDialog.Builder(SubmitPost.this)
.setTitle("Error")
.setMessage(error.getErrorMessage())
.setPositiveButton("OK", null)
.show();
} else {
try {
GraphObject graphObject = response.getGraphObject();
if(graphObject != null) {
JSONObject graphResponse = graphObject.getInnerJSONObject();
postId = graphResponse.getString("id");
SubmitPost.this.write_status.setText("");
if(SubmitPost.this.showDialog) {
SubmitPost.this.showDialog = false;
SubmitPost.this.groups_list.setAdapter(SubmitPost.this.adapter);
new AlertDialog.Builder(SubmitPost.this)
.setTitle("Result")
.setMessage("Your status is posted successfully")
.setPositiveButton("OK", null)
.show();
}
}
} catch (JSONException e) {
Log.i("TAG","JSON error "+ e.getMessage());
Bundle postParams = new Bundle();
final RequestBatch requestBatch = new RequestBatch();
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
postParams.putParcelable(file.getName(), descriptor);
// byte[] data = Utility.videoEncode(this.file);
// postParams.putByteArray("video", data);
for (final String requestId : requestIds) {
requestBatch.add(new Request(SubmitPost.this.session, requestId+"/videos", postParams, HttpMethod.POST, requestCallback));
}
}
if (!postParams.containsKey(MIGRATION_BUNDLE_PARAM)) {
postParams.putString(MIGRATION_BUNDLE_PARAM, FbSdkVersion.MIGRATION_BUNDLE);
}
}
requestBatch.executeAsync();

Related

Stuck on choose account for application in android

I am using google drive authorization in my application. While I was running the application using android studio debug/run option, it was working fine. But, today I published the application and after installing it, I am stuck at choose account for appname. I don't know what wrong happened?
I tried a few options:
Since the app package name should not contain .example while uploading apk to google play store, I did the same in my https://console.developers.google.com/ credentials. This didn't work.
Tried to re-install the application, but it didn't work either.
the google drive code is:
private void saveFileToDrive() {
// Start by creating a new contents, and setting a callback.
//Log.i(TAG, "Creating new contents.");
Drive.DriveApi.newDriveContents(mGoogleApiClient)
.setResultCallback(new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
// If the operation was not successful, we cannot do anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
//Log.i(TAG, "Failed to create new contents.");
return;
}
// Otherwise, we can write our data to the new contents.
//Log.i(TAG, "New contents created.");
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents().getOutputStream();
// Write the bitmap data from it.
FileInputStream fis;
try {
fis = new FileInputStream(outputFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
byte[] photoBytes = baos.toByteArray();
outputStream.write(photoBytes);
outputStream.close();
fis.close();
//Log.w(TAG, "Successfully written: ");
// let us delete the file here
File file = new File(outputFile);
if (file.delete())
{
//Log.d(TAG, "Successfully deleted.");
}
} catch (FileNotFoundException e) {
//Log.w(TAG, "FileNotFoundException: " + e.getMessage());
} catch (IOException e1) {
//Log.w(TAG, "Unable to write file contents." + e1.getMessage());
}
// Create the initial metadata - MIME type and title.
// Note that the user will be able to change the title later.
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("audio/mpeg").setTitle(file_name_with_extension).build();
// Create an intent for the file chooser, and start it.
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, metadataChangeSet, result.getDriveContents())
;
}
});
}
/**
* Called before the activity is destroyed
*/
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
#Override
protected void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
if (mGoogleApiClient == null) {
// Create the API client and bind it to an instance variable.
// We use this instance as the callback for connection and connection
// failures.
// Since no account name is passed, the user is prompted to choose.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
// Connect the client. Once connected, the camera is launched.
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
if (mAdView != null) {
mAdView.pause();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_OK) {
// Store the image data as a bitmap for writing later.
//Log.d(TAG, "Data is saved successfully.");
Toast.makeText(getApplicationContext(), "The file " + file_name + " has been saved successfully to your drive.", Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Called whenever the API client fails to connect.
//Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization
// dialog is displayed to the user.
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
//Log.e(TAG, "Exception while starting resolution activity", e);
}
}
#Override
public void onConnected(Bundle connectionHint) {
//Log.i(TAG, "API client connected.");
}
#Override
public void onConnectionSuspended(int cause) {
//Log.i(TAG, "GoogleApiClient connection suspended");
}
My app is live here:
https://play.google.com/store/apps/details?id=com.khan.spyrecorder
Please help me to solve the issue.

How to upload (post) a video to Facebook using an Android app?

Trying to have a simple video upload app, found this answer which eclipse says many of the functions there are deprecated.
https://stackoverflow.com/a/6924732/1525654
I'm using the latest Facebook SDK (version 3.16).
Is there a simple example for taking a video from the SD card and post it onto a Facebook's wall ?
Here's what I did.
First your callback,
private Request.Callback requestCallback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError() == null) {
Toast.makeText(YourActivity.this, "Posted to Facebook.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(YourActivity.this, "Post to Facebook failed.", Toast.LENGTH_SHORT).show();
}
}
};
Then, see if you have the publish_actions permission already,
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for(String string : subset) {
if(!superset.contains(string)) {
return false;
}
}
return true;
}
Then put this method inside your onClick() method
public void uploadVideoToFb(String caption) {
// Get Facebook's active session.
Session session = Session.getActiveSession();
/*
* Check published permissions first.
*/
List<String> permissionList = session.getPermissions();
if(!isSubsetOf(FacebookFragment.PERMISSIONS, permissionList)) {
/*pendingPublishReauthorization = true;*/
/*
* Set additional permission requests to be able
* to publish on the Facebook feed.
* Inside PERMISSIONS is just "publish_actions".
*/
Session.NewPermissionsRequest newPermissionRequest = new Session.NewPermissionsRequest(this, FacebookFragment.PERMISSIONS);
session.requestNewPublishPermissions(newPermissionRequest);
return;
}
new TaskDownloadAndPostToFb(this, caption).execute();
}
Our publish_action permission,
public static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
Then here's my AsyncTask,
#Override
public void onPostExecute(Integer result) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath() + filename;
File videoFile = new File(baseDir);
if(videoFile.exists()) {
Session session = Session.getActiveSession();
if(session != null) {
try {
Request request = Request.newUploadVideoRequest(session, videoFileLocal, requestCallback);
/*
* Take note of where to get the reference
of your bundle, it should always be
request.getParameters()
*/
Bundle params = request.getParameters();
params.putString("description", this.caption);
request.setParameters(params);
request.executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
Log.i(TAG, "Video not found.");
}
}
Also, I have edited a lot of my code, of course, for security reasons. Let me know if something is lacking and broken.
I'm using Facebook's latest SDK 3.17 as of August 7, 2014

how to catch Failed to find provider info for com.facebook.katana.provider.PlatformProvider error

Can someone tell me where should i set a try/catch to catch this?
02-10 22:54:35.701: E/ActivityThread(787): Failed to find provider info for com.facebook.katana.provider.PlatformProvider
I already know that it is caused because I have not installed the facebook application in the cellphone.
I want to make a Toast when the exception is throwed
this do not work.
shareButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
try{
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(Archivo.this)
.setLink(pagina)
.setName(nombre)
.setPicture(photo)
.setDescription(brief)
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
}
catch(FacebookDialogException ex){
int duration = Toast.LENGTH_SHORT;
CharSequence FacebookDialogError="Instale y actualize su version de Facebook";
Toast toast = Toast.makeText(activity,FacebookDialogError , duration);
toast.show();
}
}
});
I set te same toast in where the facebookdialog receive a exception and it still not working.
public FacebookDialog build() {
validate();
Bundle extras = new Bundle();
putExtra(extras, NativeProtocol.EXTRA_APPLICATION_ID, applicationId);
putExtra(extras, NativeProtocol.EXTRA_APPLICATION_NAME, applicationName);
Intent intent = handleBuild(extras);
if (intent == null) {
int duration = Toast.LENGTH_SHORT;
CharSequence FacebookDialogError="Instale y aCtualize su version de Facebook";
Toast toast = Toast.makeText(activity,FacebookDialogError , duration);
toast.show();
throw new FacebookException("Unable to create Intent; this likely means the Facebook app is not installed.");
}
appCall.setRequestIntent(intent);
return new FacebookDialog(activity, fragment, appCall, getOnPresentCallback());
}
What should I do to make a Toast of that exception?
Sorry if it is too late to answer my own question, but I am about to update the app in where this question came out.
Since the question is still watched I will post the a troubleshooting
This is a fallback in case of the Facebook app is not found.
private void publishFeedDialog(String Link,String Name,String Photo,String Descripcion) {
Bundle params = new Bundle();
params.putString("name", Name);
params.putString("caption",Caption);
params.putString("description",Descripcion);
params.putString("link", Link);
params.putString("picture",Photo);
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(sEstablecimiento.this,
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(sEstablecimiento.this,
"Posted story, id: "+postId,
Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(sEstablecimiento.this.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(sEstablecimiento.this.getApplicationContext(),
"Publish cancelled",
Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(sEstablecimiento.this.getApplicationContext(),
"Error posting story",
Toast.LENGTH_SHORT).show();
}
}
})
.build();
feedDialog.show();
}
And use a boolean to test if the ShareDialog can be buil
if (FacebookDialog.canPresentShareDialog(getApplicationContext(),
FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {
FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(myActivity.this)
.setLink("page")
.setName("name")
.setPicture("photo")
.setDescription("description")
.build();
uiHelper.trackPendingDialogCall(shareDialog.present());
} else {
publishFeedDialog("page","name","photo","description");
}
I hope it could be usefull for someone.
Thanks for your pathience an forgive my lack of care about the question.

No information available for Provided link in Twitter Status update API

I am working in an application which requires to send tweets on Twitter Account. I am successfully able to login and fetching details of user. But however when i try to update status Code of Twitter. It's throwing a runtime exception as per below:-
java.lang.IllegalStateException: Authentication credentials are missing. See http://twitter4j.org/configuration.html for the detail.
Even url is not available which is being shown in Exception. This is truly confusing.
i am using following code. Please help.
AccessToken accessToken = getAccessToken();
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(CONSUMER_KEY)
.setOAuthConsumerSecret(CONSUMER_SECRET)
.setOAuthAccessToken(accessToken.getToken())
.setOAuthAccessTokenSecret(accessToken.getTokenSecret());
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getSingleton();
// twitter.setOAuthAccessToken(accessToken);
String latestStatus = "Hello Dude";
try {
twitter4j.Status status = twitter.updateStatus(latestStatus);
Toast.makeText(HomeActivity.this, "Successfully tweet==="+status.getText(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception in Ststus update in android=="+e.getMessage());
}
I am using same library for sending tweet on Twitter. You might have code wrong to work it proper.
Please refer this for sending tweet:
Twitter4J
Also check my code below to understand more on how to handle twitter error response also.
Code:
private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
#Override
public void onComplete(String value) {
//Toast.makeText(getApplicationContext(), "Login successfull", Toast.LENGTH_SHORT).show();
try {
StatusUpdate status = new StatusUpdate("Posting from Twitter application...");
//status.media(new File(sPhotoPATH));
mTwitter.updateStatus(status);
//Toast.makeText(getApplicationContext(), "Login successfull", Toast.LENGTH_SHORT).show();
//getFriendListForApp();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Fail to connect Twitter", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//getFriendListForApp();
}
#Override
public void onError(String value) {
Toast.makeText(MainActivity.this, "Fail to connect Twitter", Toast.LENGTH_LONG).show();
finish();
}
};
and another is:
public void updateStatus(final StatusUpdate status) throws Exception {
mProgressDlg.setMessage("Posting...");
mProgressDlg.show();
new Thread(new Runnable() {
#Override
public void run() {
int i = 0;
try {
mTwitter.updateStatus(status);
i = 0;
} catch (TwitterException e) {
e.printStackTrace();
System.out.println("Not Posted: In Catch");
message = e.getErrorMessage();
System.out.println("MESSAGE:::: "+message);
//asdasd
//Toast.makeText(context, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
//e.getMessage();
i= 1;
}
mPostHandler.sendEmptyMessage(i);
}
}).start();
}
Please let me know if you have any doubt from this.
Enjoy Coding... :)

android facebook api post

I have a problem. I want to use the facebook api and make a post to my wall without calling a dialog. Basically I have an app and I want people to be able to share the app, so I want to have a specific message to post. I keep getting a response of "Method not implemented". Heres the code for the post.
//I tried this also ->>String path = "http://graph.facebook.com/me/feed";
String path = "https://api.facebook.com/method/stream.publish";
Bundle b = new Bundle();
//And i tried this -> b.putString("access_token",facebook.getAccessToken());
b.putString("message", "this is just a test...");
try {
String ret = facebook.request(path, b);
Toast.makeText(fmasterActivity.this, ret, Toast.LENGTH_LONG).show();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am assuming that you are doing that bit of code after the user successfully authenticates?
This bit of code worked for me:
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
private void onFacebookShare() {
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
private void postToFBWall() {
if(mFacebook.isSessionValid()){
shareVideoOnFB();
} else {
showDialog(DIALOG_FBOOK_LOGIN);
}
}
public void shareVideoOnFB(){
Bundle params = new Bundle();
params.putString("message", "This string will appear as the status message");
params.putString("link", "This is the URL to go to");
params.putString("name", "This will appear beside the picture");
params.putString("caption", "This will appear under the title");
params.putString("description", "This will appear under the caption");
params.putString("picture", "This is the image to appear in the post");
mAsyncRunner.request("me/feed", params, "POST", new RequestListener() {
public void onMalformedURLException(MalformedURLException e) {}
public void onIOException(IOException e) {}
public void onFileNotFoundException(FileNotFoundException e) {}
public void onFacebookError(FacebookError e) {}
public void onComplete(String response) {
logoutFacebook();
}
});
Toast.makeText(ShareActivity.this, "Posting to your Wall...", Toast.LENGTH_SHORT).show();
}
You can call onFacebookShare() in your activity's onCreate(), and then when the user presses whatever to indicate that s/he wants to share on Facebook, call postToFBWall(). Of course you have to add in handling to show the login dialog.

Categories

Resources