Its strange that I am using right code to make dialog with predefined content. But it isn't working :( guide me if I am wrong, thanks
Code:
Bundle params = new Bundle();
params.putString("message", "Predef Message");
Facebook facebook = new Facebook("APP_ID");
facebook.dialog(this, "feed", params, new DialogListener(){
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
return;
}});
I found that we can't predefined a message for posting on wall, check this https://developers.facebook.com/docs/reference/androidsdk/dialog/ it requires user interaction
Message for Post on wall, Share a link or any else require user interaction. So a workaround is share a link and add description to it :)
Try this it is work for me
public void postfb() {
Log.i("PostFB", "POST FB ENTERED..!!");
Facebook facebook;
// facebook = new Facebook(InfrqncyApplication.APP_ID);
facebook = new Facebook(APP_ID);
// replace APP_API_ID with your own
facebook.authorize(getActivity(), new String[] { "publish_stream",
"offline_access" }, null);
Bundle params = new Bundle();
params.putString("link", imagePostPath);
params.putString("name", etxtTitle.getText().toString().trim());
// params.putString("caption","Via Sharesi.es");
params.putString("description", etxtDescription.getText().toString());
params.putString("picture", imagePostPath);
facebook.dialog(getActivity(), "stream.publish", params,
new DialogListener() {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(getActivity(),
"Posted sucessfully !", Toast.LENGTH_SHORT)
.show();
AddPost();
} else {
Log.d("FB Sample App", "Canceled by User");
}
}
#Override
public void onFacebookError(FacebookError error) {
AddPost();
Log.e("fb", "fb error" + error);
}
#Override
public void onError(DialogError e) {
AddPost();
Log.e("fb", "fb dialog error" + e.getLocalizedMessage());
}
#Override
public void onCancel() {
AddPost();
}
});
}
Related
I am trying to have my Android Application share a URI image to facebook. When using the picture parameter, it forces you to use a URL of a picture. Since I am trying to share from my phones gallery, I was wondering if there was a way to have a URI read like a URL, or any other way to do this. Any suggestions?
UPDATE: I have updated this by adding my code that I am attempting to use. I understand that I am not using the newly rolled out API of Facebook. I just want to be able to post a picture from my phone gallery to Facebook, and not a picture from URL. Thank you!
private String[] arrPath;
int id = viewIt.getId();
if(facebook.isSessionValid()) {
Bundle params = new Bundle();
params.putString("name", "AndroidApp");
params.putString("caption", "Application for Android");
params.putString("description", "This is a description");
params.putString("link", "http://www.google.com/");
params.putString("picture", "file://" + arrPath[id]);
facebook.dialog(AndroidClass.this, "feed", params, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}else {
facebook.authorize(AndroidClass.this, new String[] {"email", "publish_stream"}, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(AndroidClass.this, "fberror", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(AndroidClass.this, "onError", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Editor editor = sp.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(AndroidClass.this, "onCancel", Toast.LENGTH_SHORT).show();
}
});
}
}
});
You could open a stream to the image from the URI and post it that way using ContentResolver.
Session session = Session.getActiveSession();
Bitmap photo = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
Request request = Request.newUploadPhotoRequest(session, photo, new Request.Callback());
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
I am trying to login into the Facebook using Facebook sdk .But it not logging in .Its opening the dialog box but after getting the credentials its not working . If i install the Facebook app it opens the Facebook app but login is not completed i cant get the token and user id . I cant post the message to the wall also . But it displays the toast that "message successfully displayed" but it is not posted in the Facebook wall.
Code:
public boolean isSession() {
access_token = sp.getString(TOKEN, "x");
expires = sp.getLong(EXPIRES, -1);
Log.d("TAG", access_token);
if (access_token != null && expires != -1) {
facebook.setAccessToken(access_token);
facebook.setAccessExpires(expires);
}
return facebook.isSessionValid();
}
private class LoginDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
Log.d("TAG", "LoginONComplete");
token =facebook.getAccessToken();
token_expires = facebook.getAccessExpires();
Log.d("TAG", "AccessToken: " + token);
Log.d("TAG", "AccessExpires: " + token_expires);
savePrefs3(EXPIRES,token_expires);
savePrefs(TOKEN,token);
mAsyncRunner.request("me", new IDRequestListener());
}
#Override
public void onFacebookError(FacebookError e) {
Log.d("TAG", "FacebookError: " + e.getMessage());
}
#Override
public void onError(DialogError e) {
Log.d("TAG", "Error: " + e.getMessage());
}
#Override
public void onCancel() {
Log.d("TAG", "OnCancel");
}
}
private class IDRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
try {
Log.d("TAG", "IDRequestONComplete");
Log.d("TAG", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
Uid = json.getString("id");
savePrefs("UID", Uid);
final String name = json.getString("name");
} catch (JSONException e) {
Log.d("TAG", "JSONException: " + e.getMessage());
} catch (FacebookError e) {
Log.d("TAG", "FacebookError: " + e.getMessage());
}
}
#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
}
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
howToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
please tell me where i am going wrong . after displaying a toast app gets closed. while loading the fb dialog if i touch the screen it either reloads or switching back to the app window.
Please give immediate reply
The Facebook object is depreciated.You can use the following code in your activity oncreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// setContentView(R.layout.facebook_dialog);
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user == null) {
Toast.makeText(LoginFacebook.this.getApplicationContext(),
"Facebook Error",
Toast.LENGTH_LONG).show();
finish();
}
else
{
Toast.makeText(LoginFacebook.this.getApplicationContext(),
user.getName()+" Logged in Successfully.",
T
Toast.LENGTH_LONG).show();
finish();
}
//login_fb.setEnabled(true);
//progress.setVisibility(View.INVISIBLE);
}
});
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
finish();
}
And use the following code in the Manifest.xml file under the application tag.
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name" >
</activity>
After Loging in to post to wall you have to call this method...
private void publishStory(String user) {
try {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("message", messageToPost);
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (Exception e) {
Log.i("Test",
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
progress.setVisibility(View.INVISIBLE);
toastmessage="Posted Successfully";
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
toastmessage,
Toast.LENGTH_SHORT).show();
}
}
};
Request request = new Request(session, user+"/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(ShareOnFacebook.this
.getApplicationContext(),
"Facebook Error",
Toast.LENGTH_SHORT).show();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
and declare the variables as..
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions","manage_pages","publish_stream");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
Not exactly the answer to your question, but if you are starting to develop your app: usage of Facebook object is deprecated in 3.x API.
In new API you should use Session object, along with UiLifecycleHelper
I have a LoginViaFacebook Acitivity and a login button for facebook Login.I use the following code to login to facebook
private String[] permissions = {"publish_stream",
"read_stream", "user_photos", "publish_checkins", "photo_upload",
"email", "user_birthday" };
if (access_token != null) {
Utility.fb.setAccessToken(access_token);
token = access_token;
Log.e("OnCretae Facebook Token------------", token);
}
if (expires != 0) {
Utility.fb.setAccessExpires(expires);
}
btn_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (CheckInternet.checkConn(LoginViaFacebook.this)) {
Utility.fb.authorize(LoginViaFacebook.this, permissions,
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onFacebookError",
Toast.LENGTH_LONG).show();
Log.e("Sajolllllllllllllllll", e + "");
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onError", Toast.LENGTH_LONG)
.show();
Log.e("Sajolllllllllllllllll", e + "");
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
editor = sp.edit();
token = Utility.fb.getAccessToken();
Log.e("Token---------", token);
editor.putString("access_token",
Utility.fb.getAccessToken());
editor.putLong("access_expires",
Utility.fb.getAccessExpires());
editor.commit();
Toast.makeText(getApplicationContext(),
"Login Successful",
Toast.LENGTH_LONG).show();
mProgress = ProgressDialog.show(
LoginViaFacebook.this, "",
"Please Wait...", true);
Thread t = new Thread(retriveProfileData);
t.start();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"onCancel", Toast.LENGTH_LONG)
.show();
}
});
}
}
});
I save the access token to login next time directly if user not logout
I have another activity namely Settings and have button Logout.I use following code to logout from facebook
lagoutLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final String[] items = new String[] { "Yes", "No" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
SettingsActivity.this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(
SettingsActivity.this);
builder.setTitle("Select Option");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick
// from
// camera
if (item == 0) {
try {
editor.remove("FacebookId");
editor.remove("EmailId");
editor.commit();
Log.e("Pre----------------", sp1
.getString("access_token", "d"));
editor1.remove("access_token");
editor1.remove("access_expires");
editor1.commit();
Log.e("After----------------", sp1
.getString("access_token", "d"));
Log.e("DATATTAT--------",
sp.getString("FacebookId",
"saf")
+ " "
+ sp.getString(
"EmailId", "as"));
String r = Utility.fb
.logout(SettingsActivity.this);
Log.e("Res-----------", r);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else { // pick from file
dialog.dismiss();
}
}
});
dialog = builder.create();
dialog.show();
}
});
The response from Facebook Logout method show true in Log.
But when i again run application it will automatically login to facebook
I can'nt find out the problem.Please help me
I use this code and it worked fine
public void logout() {
if (!isConnected(activity)) {
Toast.makeText(activity, "Internet not connected", Toast.LENGTH_LONG).show();
return;
}
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
asyncRunner.logout(this.context, new LogoutRequestListener());
}
And here is the listener
public class LogoutRequestListener extends BaseRequestListener {
public void onComplete(String response, final Object state) {
// callback should be run in the original thread,
// not the background thread
mHandler.post(new Runnable() {
public void run() {
SessionEvents.onLogoutFinish();
Intent intent= new Intent(activity,Login.class);
activity.startActivity(intent);
activity.finish();
}
});
}
}
For facebook sdk version 3 above
public void logoutFacebook() {
Session session = Session.getActiveSession();
if(session != null && session.isOpened()){
session.closeAndClearTokenInformation();
}
}
if you are extending and using facebook openSession when logging you must close it using closeSession and put it in your logout or you can simply put it onDestroy just like this
public void onDestroy() {
this.closeSession();
super.onDestroy();
}
Try this :
I hope this will be help to you...
if (mFacebook.isSessionValid()) {
try {
String str = mFacebook.logout(getApplicationContext());
SessionStore.clear(getApplicationContext());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you are viewing this answer from google suggestion and using facebook sdk v4 or above, just use this lines. It works perfectly.
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
I am new to facebook api and android.But somehow try to manage login to my facebook account and retrieve some information of my account i.e. id,first_name,last_name.The sdk(android) which is used on creating this application is sdk(android) level 8 but when i used sdk(android) level >8 application crash and error generate on logcat(networkonmainthreadException).I had done some search and found this is thread problem with sdk level and now i am going for Asynctask but got confused where to put the login code for facebook and what thing will return to mainactivity
My code for sdk level 8 is:-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
loginnfetch=(Button) findViewById(R.id.button1);
loginnfetch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
facebook=new Facebook(APP_ID);
restorecredential(facebook);
if(!facebook.isSessionValid())
{
loginandfetch();
}
else
{
fetch();
}
}
});
}
protected void fetch()
{
try {
JSONObject jobj=new JSONObject(facebook.request("me"));
int id=jobj.getInt("id");
String fname=jobj.getString("first_name");
String lname=jobj.getString("last_name");
//String emailid=jobj.getString("email");
Toast.makeText(getApplicationContext(), ".."+id+".."+fname+".."+lname, 0).show();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void loginandfetch()
{
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,new DialogListener() {
#Override
public void onFacebookError(FacebookError e)
{
Toast.makeText(getApplicationContext(), "ERROR WHILE LOGIN", 0).show();
}
#Override
public void onError(DialogError e) {
Toast.makeText(getApplicationContext(), "ERROR WHILE LOGIN", 0).show();
}
#Override
public void onComplete(Bundle values) {
saveCredentials(facebook);
fetch();
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "ERROR WHILE LOGIN", 0).show();
}
});
}
protected boolean restorecredential(Facebook facebook2)
{
SharedPreferences sharedPreferences = getApplicationContext()
.getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY,
Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
Please share some code if available or some link
thank you and sorry if something is not correct
From the ICS and above versions Android won't allowed any network operation in the UI thread.It should be done in separate thread so it won't hang the UI.Try your network communication code in the separate thread.
In your case,fetch facebook info using thread.
Try this ::
if(!facebook.isSessionValid())
{
new Thread(new Runnable() {
#Override
public void run() {
loginandfetch();
}
}).start();
}
else
{
new Thread(new Runnable() {
#Override
public void run() {
fetch();
}
}).start();
}
I have posted status on facebook like bellow. you can try something like this for your problem: (Facebook api 3.02b)
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(context, "Failed to Post", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Successfully Posted", Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, victimId+"/feed", bundle,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
I make an application in which I make an EditText and a button. I want to be post that message which is written on EditText on the Facebook friends wall after clicked on the button. Please give me some idea how we can perform this task using Facebook sdk.
The code is below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.post_wall);
share = (Button) findViewById(R.id.share);
friend_name = (TextView) findViewById(R.id.wall_to);
wall = (EditText) findViewById(R.id.wall);
savedInstanceState = new Bundle();
savedInstanceState.getString("to");
onComplete(savedInstanceState);
}
#Override public void onComplete(Bundle values)
{
Utility.currentPermissions.clear();
if (values.isEmpty())
{
//"skip" clicked ?
return;
}
// if facebookClient.authorize(...) was successful, this runs
// this also runs after successful post
// after posting, "to"(which is the id of friend) is added to the values bundle
// I use that to differentiate between a call from
// faceBook.authorize(...) and a call from a successful post
// is there a better way of doing this?
if (!values.containsKey("to"))
{
try
{
Log.d("Wall try", "Click successfully");
for (String key : parameters.keySet()) {
if (parameters.getByteArray(key) != null) {
parameters.putByteArray(key, parameters.getByteArray(key));
Log.d("key", parameters.getByteArray(key).toString());
}
}
mHandler.post(new Runnable() {
#Override
public void run() {
performActivityInfo();
}
});
}
catch (Exception e)
{
// TODO: handle exception
System.out.println(e.getMessage());
}
}
}
protected void performActivityInfo() {
Log.d("perform wall", "Perform Activity");
mHandler.sendEmptyMessage(FRIEND_WALL);
parameters.putString("message", wall.getText().toString());
facebookClient.dialog(this, "stream.publish", parameters, this);// "stream.publish" is an API call
Log.d("Wall post", "Click successfully");
}
public Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FRIEND_WALL:
Log.d("Handler WALL", "Handler");
postOnWall(wall.getText().toString());
break;
}
super.handleMessage(msg);
}
};
#Override
public void onError(DialogError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e)
{
System.out.println("Error: " + e.getMessage());
}
#Override
public void onCancel()
{
}
#Override
public void onClick(View v)
{
facebookClient = new Facebook(APP_ID);
// replace APP_API_ID with your own
Log.d("Wall click", "Click successfully");
facebookClient.authorize(this,
new String[] {"publish_stream", "read_stream", "offline_access"}, this);
}
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebookClient.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = facebookClient.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}
Thanks in Advance.
For getting the value from Edit Text just use :
EditText edittext;
edittext.getEditableText().toString();
Inside Button click Listener use this code then
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
String entered_value=edittext.getEditableText().toString();
try{
parameters.putString("message", entered_value);
parameters.putString("target_id", "XXXXX"); // target Id in which you need to Post
parameters.putString("method", "stream.publish");
String response = authenticatedFacebook.request(parameters);
Log.v("response", response);
}
catch(Exception e){}
}
});
where button is your button Object.