I am using following code to load an image from android app to facebook. I have installed facebook sdk for android. But the app is not doing the intended. I am getting "invalid application id" in the logcat. What mistake am I making ?
Button mButton=(Button)findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Facebook mFacebook=new Facebook(yourAppID)
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(imageLink);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
}
});
public class SampleUploadListener extends BaseRequestListener {
#SuppressWarnings("unused")
public void onComplete(final String response, final Object state) {
try {
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
String src = json.getString("src");
PublishImage.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Successfully Uploaded", Toast.LENGTH_SHORT)
.show();
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
public abstract class BaseRequestListener implements RequestListener {
public void onFacebookError(FacebookError e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
}
Logcat
06-15 20:00:55.398: W/KeyCharacterMap(629): No keyboard for id 0
06-15 20:00:55.398: W/KeyCharacterMap(629): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-15 20:01:02.438: D/dalvikvm(629): GC_EXTERNAL_ALLOC freed 1214K, 59% free 2755K/6599K, external 1995K/2266K, paused 630ms
06-15 20:01:08.998: D/MediaPlayer(629): getMetadata
06-15 20:01:15.529: D/Facebook-Example(629): Response: {"error_code":101,"error_msg":"Invalid application ID.","request_args":[{"key":"method","value":"photos.upload"},{"key":"format","value":"json"}]}
06-15 20:01:15.529: W/Facebook-Example(629): Facebook Error: Invalid application ID.
EDIT: This worked
class ButtonListener1 implements View.OnClickListener{
Facebook facebook=new Facebook(ID);
#Override
public void onClick(View v) {
facebook.authorize(Pic.this, new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError dialogError) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
postToWall(values.getString(Facebook.TOKEN));
}
private void postToWall(String accessToken) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
Bundle bundle = new Bundle();
bundle.putString(Facebook.TOKEN, accessToken);
bundle.putByteArray("facebookPictureData", data);
// The byte array is the data of a picture.
bundle.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
try {
facebook.request("me/photos", bundle, "POST");
} catch (FileNotFoundException fileNotFoundException) {
// makeToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
// makeToast(malformedURLException.getMessage());
} catch (IOException ioException) {
// makeToast(ioException.getMessage());
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}
UPDATE:
Here is the link to the Facebook.java class on facebook api reference website:
http://developers.facebook.com/docs/reference/androidsdk/authentication/. Scroll down a few lines to find the authorize method. Are you sure you are using the com.facebook.android.Facebook class from the android sdk and not a class that you might have spun on your own?
The basic auth flow on android apps is as follows:
1. Make an instance of the Facebook class (that you have).
2. Make a call to Facebook.authorize() with the right permissions you need.
3. In the DialogListener call back of the authorize method, you can save the access_token and expiration time for future use.
4. In the activity that you called authorize from, override the "onActivityResult method and if that method is called with Facebook's result code (Facebook.DEFAULT_AUTH_ACTIVITY_CODE), then call Facebook.authorizeCallback with the received intent.
5. After these 4 steps are done, you are free to make graph api requests with Facebook.request() or AsyncFacebookRunner.request(). In these request methods, the first parameter is the graph path you want. So, for example, if you called the request method with path "me", you would get back profile information of the logged in user.
END UPDATE-------
For starters, I think you necessarily need to have the graph path as the first parameter in your code on this line:
mAsyncRunner.request("*********7618/photos", params, "POST",
new SampleUploadListener(), null);
}
});
In my code it is the albumid/photos. Additionally, you need permissions from the user to upload to an album belonging to her. For that, you need to retrieve an access token using Facebook.authorize().
I am not sure I understand why you are getting the error related to the app id being not valid, however, from what I know this are the basic steps you need to do in order to post photos before you post photos.
I am sure someone will post a better answer soon, hope this helps in the meantime.
Related
I am Upload video from my application and get the information of that video (likes,comments)
Problem 1
I have done uploading but when i get video information it throws me error
Error
{"error":{"message":"Cannot specify type in both the path and query parameter.","type":"OAuthException","code":2500}}
I am using Facebook SDK 3.8
Problem 2
When i upload video it Only visible in my account but not visible from other account even though it is public
Code For Upload Video
private void Upload_Video() {
mDialog = new ProgressDialog(AndroidFacebookConnectActivity.this);
mDialog.setMessage("Uploding video...");
mDialog.show();
String path="/mnt/sdcard/abc/Mirror.mp4";
if (new File(path).exists()) {
try {
Bundle param;
try {
InputStream is = new FileInputStream(path);
byte[] data = readBytes(is);
param = new Bundle();
param.putString("title", "Test 2");
param.putString("message", "uploaded");
param.putByteArray("video.mov", data);
param.putString("contentType", "video/quicktime");
mAsyncRunner.request("kmavadhiya/videos", param, "POST",new FBRequestListener(), null);
Toast.makeText(getApplicationContext(), "Uploading...", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "No videos found in sdcard ",Toast.LENGTH_SHORT).show();
}
}
public byte[] readBytes(InputStream inputStream) throws IOException {
// This dynamically extends to take the bytes you read.
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// This is storage overwritten on each iteration with bytes.
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// We need to know how may bytes were read to write them to the byteBuffer.
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// And then we can return your byte array.
return byteBuffer.toByteArray();
}
Upload Request Listner
public class FBRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidFacebookConnectActivity.this, "Upload Video Successfully...",Toast.LENGTH_LONG).show();
mDialog.dismiss();
}
});
Log.e("response", response);
try {
JSONObject jObject = new JSONObject(response);
String Id = (String) jObject.get("id");
Log.d("Video Id = ",""+Id);
Bundle param = new Bundle();
param.putString("type", "uploaded");
mAsyncRunner.request("kmavadhiya/videos/"+Id, param, "GET",new VideoDataRequestListener(), null);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
e.printStackTrace();
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.e("", "onFileNotFoundException");
e.printStackTrace();
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.e("", "onMalformedURLException");
e.printStackTrace();
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.e("", "onFacebookError");
e.printStackTrace();
}
}
Video Data Listner
public class VideoDataRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.e("response", response);
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
If I changed This Line
mAsyncRunner.request("kmavadhiya/videos/"+Id, param, "GET",new VideoDataRequestListener(), null);
With
mAsyncRunner.request("kmavadhiya/videos/", param, "GET",new VideoDataRequestListener(), null);
** I got Blank Response**
Reference
Link 1
Graph Api Reference Link
I Forget To Request Permission At Login time So Its Authentication Error
Add This In Login click
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setPermissions(Arrays.asList("basic_info","user_about_me","email","video_upload","user_videos")) // Permission List That You Want To Get
.setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
Reference
Permission List
https://developers.facebook.com/docs/facebook-login/access-tokens/
Set Permission Reference
https://developers.facebook.com/docs/android/login-with-facebook#permissions
I am currently developing an Android Application target build is 4.0 Ice-Cream Sandwich.
So far, I am able to post a normal Text onto Facebook with this code:
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() {
}
});
}
However, I am unable to post a photo onto Facebook with Captions. I've search around online and one of the codes I found is this:
public void postToWall() {
// post on user's wall.
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(photoToPost);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
The problem is, the above code is not working as I don't know whats:
1.photoToPost
2.mAsyncRunner.request keeps giving me an error stating that I cannot put "null" as it is an invalid arguement
3.SampleUploadListener, supposedly is from the FacebookSDK is not working as well (I keep getting an error to create a Class)
Is there a simpler code out here ? Or could someone explain to me the errors I am experiencing.
I am using an "On Click" so far to post normal Text onto Facebook and it points to this method. My goal is to upload a Photo with a Caption onto Facebook.
Thank you all for helping !
1-This is your photo that will be send to wall , it can be an image from your SD card or anywhere else
2-This a class from Facebook SDK , that accepts facebook object (one u created before)
3-This a class from Facebook SDK again
it seems there is something wrong with your Facebook SDK
try to set it again using Right Click on Project >> Properties >> Android and see if library exist or not
The problem lies in following line
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
you are passing null as graph path this should be like this = "me/feed"
Update
write this line of code
mAsyncRunner.request("me/feed", params, "POST", new SampleUploadListener(), null);
then it should work.
public class CardShared extends Activity{
public static final String APP_ID = "YOUR APP ID";
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner ;
boolean isLoggedIn = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
//Implementing SSO
mFacebook.authorize(this, new String[]{"publish_stream"}, new DialogListener(){
public void onComplete(Bundle values) {
sharePicture(values.getString(Facebook.TOKEN));
Toast.makeText(getApplicationContext(), "Picture Shared Successfully", Toast.LENGTH_SHORT).show();
CardShared.this.finish();
}
public void onFacebookError(FacebookError e) {
Log.d("FACEBOOK ERROR","FB ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
}
public void onError(DialogError e) {
Log.e("ERROR","AUTH ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
}
public void onCancel() {
Log.d("CANCELLED","AUTH CANCELLED");
}
});
}
//updating Status
public void sharePicture(String accessToken){
byte[] data = null;
try {
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.image_to_be_uploaded);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params
.putString(Facebook.TOKEN, mFacebook
.getAccessToken());
params.putByteArray("picture", data);
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("onActivityResult","onActivityResult");
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String f = json.getString("src");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
}
put like this
mAsyncRunner.request("me/feed", params, "POST", new SampleUploadListener())
See this link. That will show you how to post image on FaceBook wall as how to post text on wall.
Its good to learn.
I am using Facebook sdk, (https://github.com/facebook/facebook-android-sdk/) to show the NewsFeed. I can be show the all newsfeed wall in my application.
Now I need to send the comment on the any wall which is visible by me. And how I can be like the wall and the comment through my application. Can anybody plz help me in this?
Thanks in advance.
To be clear:
you can only comment on posts (not the actual wall itself)
you can only like a comment or post (not the actual wall itself)
Using the Facebook SDK you can do the following for comments:
Facebook facebook = new Facebook(APP_ID);
String commentText = "I love blu-ray";
String postId = "7568536355_333422146668093"; //a lifehacker post about blu-ray
String graphPath = postId + "/comments";
Bundle params = new Bundle();
params.putString("message", commentText);
facebook.request(graphPath, params, "POST");
... and the following for likes:
Facebook facebook = new Facebook(APP_ID);
String postId = "7568536355_333422146668093"; //a lifehacker post about blu-ray
String graphPath = postId + "/likes";
facebook.request(graphPath, new Bundle(), "POST");
You can parse all feeds using graph api by passing
mAsyncRunner.request("me/home", params, new graphApiRequestListener());
it returns you json data with all your post and comments and likes
you can parse that data get all commnets
for further information search for hackbook for android example
You should get familiar with Facebook Android SDK usage of Graph API, Post object (comments connection) and Comment Object Graph API documentation (likes section).
You can't comment on the wall itself but on one of the posts.
You can post on the wall via Graph API
You can comment on post via Graph API
You can create likes for both Posts and Comments via Graph API
Update:
Example below about creating comment and liking it (samples of how to create comment for post and like the post already shown in other answer to this question):
// I assume you already have post_id (which is constructed from USERID_MESSAGEID)
Facebook mFacebook = new Facebook(APP_ID);
Bundle params = new Bundle();
params.putString("message", "This is a comment text");
String comment_id = facebook.request(post_id + "/comments", params, "POST");
// Once you have comment_id it can be used for liking it.
facebook.request(comment_id + "/likes", new Bundle(), "POST");
'Use Facebook Api as library download api and use it as library'
private static final String FACEBOOK_APPID = "Your Api key";
Facebook facebook = new Facebook(FACEBOOK_APPID);
facebook.authorize(this,new String[] { "user_photos,publish_checkins,publish_actions,publish_stream" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
postImageonWall();
try {
facebook.logout(TestActivity.this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// finish();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
use postImageOnWall method
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(filepath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.d("MalformedURLException", e.getMessage());
}
#Override
public void onIOException(IOException e, Object state) {
Log.d("onIOException", e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.d("FileNotFoundException", e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d("onFacebookError", e.getMessage());
}
#Override
public void onComplete(String response, Object state) {
Log.d("onComplete", response);
}
}, null);
}
I have integrated the Facebook-sdk successfully in to my appplication.
Now i am going to share a photo to Facebook. To do that I am using this code:
facebook.authorize(DrawingActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
byte[] data = null; Bitmap bi = BitmapFactory.decodeFile(APP_FILE_PATH + "/myAwesomeDrawing.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
and another code is:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
Now, I dont know why i am not able to get upload photo on the facebook?
Depending on what you want to do, you need to give a target (first null) to this line of code:
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
For example, if you're trying to make a post on the current users wall, it should look like:
mAsyncRunner.request("me/posts", params, "POST", new SampleUploadListener(), null);
You will need the correct permissions to do this: at least publish_stream.
See docs
I use the single sign on in my application (http://developers.facebook.com/docs/mobile/android/build/). It seems working fine on the emulator (i log in succefully and get the access_token). But in my Nexus S, the webview shows up, but I always get "login failed".
There is my code:
((Button)findViewById(R.id.BtnFacebook)).setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//startActivity(intentLoginFacebook);
facebook.authorize(Login.this, new String[] {"user_about_me","user_activities","user_birthday","user_education_history","user_events","user_groups","user_hometown","user_interests","user_likes","user_location","user_religion_politics","user_status","user_website","user_work_history","read_requests","read_stream","friends_events","email","create_event","manage_friendlists","offline_access","rsvp_event"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
String id = "";
String access_token = facebook.getAccessToken();
System.out.println("ACCESSTOKENNNN:" + access_token);
try {
String response = facebook.request("me");
JSONObject obj = new JSONObject(response);
id = obj.getString("id");
System.out.println("response: "+response);
} catch (IOException ex) {
Log.d("Facebook", ex.getMessage());
} catch (Exception e) {
Log.d("Facebook", e.getMessage());
}
//Verification du login/password
new LoginFacebook().execute(id,access_token);
System.out.println("IDDDDDDDD:" + id);
}
#Override
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Facebook error: login failed", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel() {
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Login failed", Toast.LENGTH_LONG).show();
}
});
}
});
Thanks for your help!
Most likely the SDK stores your access_token and expires_in paramters in SharedPreferences. You need to log the detailed error. If you get OAuth exception on an API call you need to delete access_token from SharedPreferences and simply reauthorize.
hope this helps