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
Related
I want to import facebook birthdays of my friends to my app. Currently my app is capable of creating new birthday events. But its very long procedure to add each and every birthday, so instead I want a code to import all facebook friends birthdays to my app. I have used facebook session but get nothing much till now
facebook = new Facebook(Constants.FB_APP_ID);
Session session = new Session(getApplicationContext());
if (session.isOpened()) {
Toast.makeText(getApplicationContext(), session.getState().toString(),
Toast.LENGTH_LONG).show();
} else
Toast.makeText(getApplicationContext(), session.getState().toString(),
Toast.LENGTH_LONG).show();
fbRunner = new AsyncFacebookRunner(facebook);
Also i have created a request
private void importBirthdayFromFB() {
Toast.makeText(getApplicationContext(), "Clicked on fb button",
Toast.LENGTH_LONG).show();
fbRunner.request("maxparera/friends", new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public void onComplete(String response, Object state) {
String keys = "";
try {
JSONObject profile = new JSONObject(response);
// getting name of the user
Iterator<String> keysIterator = profile.keys();
if (keysIterator != null) {
while (keysIterator.hasNext()) {
keys += keysIterator.next().toString();
}
Toast.makeText(getApplicationContext(), keys, Toast.LENGTH_LONG).show();
}
final String name = profile.getString("name");
// getting name of the user
Toast.makeText(getApplicationContext(), Name: " + name, Toast.LENGTH_LONG).show();
} catch (final JSONException e) {
e.printStackTrace();
} catch (final Exception e) {
e.printStackTrace();
}
}
});
But I am not getting any name, instead getting exception, sating OAuthException
Please suggest me ASAP
Maybe your session dont have permission to get your friend's birthday.
You can request permission like below:
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_friends, read_friendlists));
Layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
</LinearLayout>
Note: I uses Facebook SDK 3.8, you can refer to its sample for more detail.
LoginButton is a component of Facebook SDK.
For full of my code:
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
Log.i(TAG, "session: " +session.toString());
Log.i(TAG, "state: " +state.toString());
if(exception!=null)
Log.i(TAG, "exception: " +exception.toString());
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
//REQUEST PERMISSION
authButton.setReadPermissions(Arrays.asList("user_friends, read_friendlists));
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
try{
Log.i(TAG, "Logged in...");
Log.i(TAG, "Execute my request");
Request r = new Request(session,"/me/friendlists",null,HttpMethod.GET,new Request.Callback() {
public void onCompleted(Response response) {
Log.i(TAG, "onCompleted");
try {
//I HAD FRIEND LIST
Log.i(TAG, "FRIEND: " + response.getGraphObject().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
r.executeAsync();
Log.i(TAG, "Finish my request");
}catch (Exception ex){
Log.e(TAG, ex.getMessage());
}
} else if (state.isClosed()) {
try{
}
catch(Exception ex){
ex.printStackTrace();
}
Log.i(TAG, "Logged out...");
}
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
I am using Facebook in my android app and it work just fine.
However, i realize that useless screen appears when i login every time saying that "you have already-authorized to this app" with OK and Cancel option.
How can i avoid or remove this screen from my app.
I searched on Google and i found some answer for older Facebook SDK But how to achieve it with new Facebook SDK(3.0 and above)?
this is my code,
public void onClick(View v)
{
Bundle myParams = new Bundle();
myParams.putString("message", " DOWNLOAD THE 'Saragama' ANDROID APP FROM " + url_android.toString()
+ ". Fully integrated with Facebook and Twitter.");
myParams.putString("name", mSharingText.getText().toString());
myParams.putString("caption", "www.saragama.com");
myParams.putString("description", "Various religios music, chants, mantras, christian songs, islamic music, quran and more on saragama");
myParams.putString("link", "http://android.saragama.com");
myParams.putString("picture", albumImageURL);
if (PlusUtilities.isInternetConnected())
{
// ~post your data
Session session = Session.getActiveSession();
if (session != null)
{
MyLog.w("session state", session.getState().toString());
if (session.getState().equals(SessionState.OPENED) || session.getState().equals(SessionState.OPENED_TOKEN_UPDATED))
{
publishStory(myParams);
}
else
{
plusUtilities1.showAlertDialog("Please login first!");
}
}
else
{
plusUtilities1.showAlertDialog("Please login first!");
}
}
else
{
plusUtilities1.showAlertDialog("Problem occured with your internet connection!");
}
}
// Facebook Login-------------------------------------------------------------------------------------
private void loginToFacebook()
{
if (PlusUtilities.isInternetConnected())
{
Session session = Session.getActiveSession();
// if session is in exceptional state
if (session.getState() == SessionState.CLOSED_LOGIN_FAILED || session.getState() == SessionState.OPENING)
{
session.closeAndClearTokenInformation();
}
if (!session.isOpened() && !session.isClosed())
{
String[] PERMISSION_ARRAY_PUBLISH =
{"publish_actions" };
List<String> PERMISSION_LIST = Arrays.asList(PERMISSION_ARRAY_PUBLISH);
session.openForPublish(new Session.OpenRequest(FacebookActivity.this).setPermissions(PERMISSION_LIST).setCallback(
statusCallback1));
}
else
{
Session.openActiveSession(this, true, statusCallback1);
}
}
else
{
plusUtilities1.showAlertDialog("Please check your internet connection!");
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent data)
{
super.onActivityResult(requestCode, responseCode, data);
// plusUtilities1.ShowToast("onActivityResult");
MyLog.i("onActivityResult requestCode :responsecode:session state", requestCode + ":" + responseCode + ":"
+ Session.getActiveSession().getState().toString());
switch (requestCode)
{
case MyRaagaLoginActivity.REQUEST_CODE_FACEBOOK_LOGIN:
if (responseCode == RESULT_OK)
{
MyLog.e("Login", "trying to facebook Login");
Session.getActiveSession().onActivityResult(Act1, requestCode, responseCode, data);
}
else
{
plusUtilities1.ShowToast("User access denied!");
}
break;
default:
MyLog.i("case:", "default");
break;
}
}
/**
* function to get active facebook session if already exist or create the new session
*
* #param savedInstanceState
* =check if Session exist and restored in bundle during onSaveInstanceState() system call
* #author DeepakD
*/
public void GetOrCreateFacebookActiveSession(Bundle savedInstanceState)
{
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
Session session = Session.getActiveSession();
// if session is null try to find if session is saved previously
if (session == null)
{
if (savedInstanceState != null)
{
session = Session.restoreSession(this, null, statusCallback1, savedInstanceState);
}
// if still session is null then create the new session
if (session == null)
{
session = new Session(this);
}
// set the created session as active session
Session.setActiveSession(session);
}
updateFBbutton();
}
/**
* set login or logout button
*/
private void updateFBbutton()
{
Session session = Session.getActiveSession();
if (session.isOpened())
{
FbLoginbtn.setText("FBLogout");
FbLoginbtn.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
onClickFBLogout();
}
});
}
else
{
FbLoginbtn.setText("FBLogin");
FbLoginbtn.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
loginToFacebook();
}
});
}
}
/**
* Logout from facebook
*/
private void onClickFBLogout()
{
Session session = Session.getActiveSession();
if (!session.isClosed())
{
session.closeAndClearTokenInformation();
plusUtilities1.ShowToast("Logout successful");
}
}
/**
* This class is used to fetch the current status of active session
*
* #author DeepakD
*
*/
private class SessionStatusCallback1 implements Session.StatusCallback
{
#Override
public void call(Session session, SessionState state, Exception exception)
{
updateFBbutton();
plusUtilities1.DissmissPD();
MyLog.w("session state", session.getState().toString());
if(session.getState()==SessionState.CLOSED_LOGIN_FAILED)
{
//login failed
plusUtilities1.ShowToast("Unable to connect,please try later..");
session.closeAndClearTokenInformation();
}
if (session.getState()== SessionState.OPENED)
{
//login successful
plusUtilities1.ShowToast("Login successful");
}
}
}
/**
* actually post the data on facebook
*
* #param myParams
* Bundle of parameters to be post
*/
private void publishStory(Bundle myParams)
{
plusUtilities1.ShowPD("Sharing data...");
Session session = Session.getActiveSession();
if (session != null)
{
// Check for publish permissions
List<String> permissions = session.getPermissions();
try
{
if (!isSubsetOf(PERMISSIONS, permissions))
{
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
Request.Callback callback = new Request.Callback()
{
public void onCompleted(Response response)
{
plusUtilities1.DissmissPD();
MyLog.w("post response", "" + response.toString());
if (response.getError() == null)
{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
}
catch (JSONException e)
{
Toast.makeText(FacebookActivity.this, "JSON error " + e.getMessage(), Toast.LENGTH_LONG)
.show();
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(FacebookActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
FacebookRequestError error = response.getError();
Log.e("post response", response.toString());
if (error != null)
{
Toast.makeText(FacebookActivity.this, error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(FacebookActivity.this, "Posted successfully!",
Toast.LENGTH_LONG).show();
FlurryAgent.logEvent("Audio Facebook share -" + EventName);
}
}
else
{
plusUtilities1.showAlertDialog("Something went wrong while posting!");
}
}
};
MyLog.w("BUNDLE TO BE POSTED;", myParams.toString());
Request request = new Request(session, "/me/feed", myParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
public static boolean isSubsetOf(Collection<String> subset, Collection<String> superset)
{
for (String string : subset)
{
if (!superset.contains(string))
{
return false;
}
}
return true;
}
protected void onStart()
{
super.onStart();
MyLog.i("FacebookActivity", "onStart");
FlurryAgent.onStartSession(this, KeysCls.Flurry_Analytics_Key);
FlurryAds.displayAd(this, "AppCircle_Ads", linlayAdLayout);
if (PlusUtilities.isInternetConnected())
{
Session.getActiveSession().addCallback(statusCallback1);
}
else
{
plusUtilities1.showAlertDialog("Please check your internet connection and try again!");
}
}
/**
* convert post's simple text to text with links
*
* #param Name
* #param Link
* #return
*/
String wallpostWithLink(String Name, String Link)
{
jo = new JSONObject();
try
{
jo.put("name", Name);
jo.put("link", Link);
}
catch (Exception e)
{
e.printStackTrace();
}
return jo.toString();
}
#Override
protected void onStop()
{
super.onStop();
FlurryAgent.onEndSession(this);
}
Go to developers.facebook.com and in Settings-> Basic->Single Sign On -> YES
In facebook sdk 4.0 try to activate and deactivate app in onResume and onPause like this:
#Override
protected void onResume() {
super.onResume();
// update your UI
// Logs 'install' and 'app activate' App Events.
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
// Logs 'app deactivate' App Event.
AppEventsLogger.deactivateApp(this);
}
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'm trying to use FB Connect on my app, and everything works fine in the emulator and debugging in a Galaxy Nexus, but after uploading it to google play it stops working.
If I install the app downloading it from Play, my facebook.authorize function returns a DialogError (I just don't know what error because I'm only able to view logcat when the installation is made with eclipse). And it only happens if I have the facebook app installed. So when I uninstall the fb app it works nice...
Maybe is some wrong configuration I've made while preparing facebook SDK on my computer? I pasted all my code below, but don't have any log...
public class FacebookConnectActivity extends Activity {
private static final String TAG_JSON = "json";
static Facebook facebook = new Facebook("11111111111111");
AsyncFacebookRunner mAsyncRunner;
private static SharedPreferences mPrefs;
JSONObject json = null;
Context ctx = this;
boolean callback = false;
private static Context staticContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resgatar_produto_layout);
FacebookConnectActivity.staticContext = getApplicationContext();
Log.e("FacebookConnect", "Activity Started");
mPrefs = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.e("FacebookConnect",
"Access Token retrieved from SharedPreferences");
}
if (expires != 0) {
facebook.setAccessExpires(expires);
Log.e("FacebookConnect",
"Access Expires retrieved from SharedPreferences");
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "user_photos",
"user_birthday", "user_hometown", "user_relationships",
"user_location", "user_work_history", "publish_actions" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
Log.e("FacebookConnect", "User authorized");
Log.e("FacebookConnect",
"onComplete called at facebook.authorize");
Log.e("FacebookConnect", "Access Token: "
+ facebook.getAccessToken().toString());
try {
mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me",
new SampleRequestListener());
Log.e("FacebookConnect",
"AsyncFacebookRunner request started (facebook.authorize.onComplete)");
Bundle params = new Bundle();
params.putString("link",
"https://apps.facebook.com/qranio_game/");
params.putString("picture", "http://www.qranio.com/site/images/logo_qranio_facebook.png");
int count = 0;
while (json == null && count<20){
Log.e("FacebookConnect",
"Waiting for json (facebook.authorize.onComplete)");
waiting(1000);
count++;
}
if (!(count<20)){
noConnectionAlert();
}
String usuario = json.getString("first_name");
params.putString("name", usuario+" está jogando Qranio para Android");
params.putString("caption", "Qranio - Making Learning Fun");
params.putString("description", "O Qranio é uma plataforma online que propicia o Saber. Você joga, " +
"aprende, acumula Qi$ e troca por prêmios incríveis! Venha jogar também!");
//JSONArray fbArr = new JSONArray("{\"name\":\"Jogar\",\"link\":\"https://apps.facebook.com/qranio_game/\"}");
params.putString("actions", "{\"name\":\"Jogar\",\"link\":\"https://apps.facebook.com/qranio_game/\"}");
params.putString("display", "touch");
facebook.dialog(ctx, "feed", params,
new SampleDialogListener());
Log.e("FacebookConnect",
"Post on Wall Dialog called (facebook.authorize.onComplete)");
// facebook.
// if (facebook.isSessionValid()){
// }else{
// Log.e("FacebookConnect",
// "Invalid facebook session while trying to fetch user data");
// }
} catch (FacebookError fbe) {
Log.e("FacebookConnect",
"facebook.authorize FacebookError "
+ fbe.toString());
} catch (Exception e) {
Log.e("FacebookConnect",
"facebook.authorize Exception "
+ e.toString());
}
}
#Override
public void onFacebookError(FacebookError error) {
Log.e("FacebookConnect",
"FacebookError authorizing: "
+ error.toString());
final AlertDialog alertDialog = new AlertDialog.Builder(
FacebookConnectActivity.this).create();
alertDialog.setTitle("Erro");
alertDialog
.setMessage("Ocorreu um erro com o Facebook, por favor tente novamente.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.show();
}
#Override
public void onError(DialogError e) {
//Here is where I'm getting the error when downloaded from Play
Log.e("FacebookConnect",
"Error authorizing: " + e.toString());
final AlertDialog alertDialog = new AlertDialog.Builder(
FacebookConnectActivity.this).create();
alertDialog.setTitle("Erro");
alertDialog
.setMessage("Erro ao tentar conectar com o facebook, tente novamente.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.show();
}
#Override
public void onCancel() {
Log.e("FacebookConnect", "Autorizing canceled");
finish();
}
});
} else {
mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me", new SampleRequestListener());
Log.e("FacebookConnect",
"Valid session found, AsyncFacebookRunner request started");
startDataProcess();
}
}
public void noConnectionAlert(){
final AlertDialog alertDialog = new AlertDialog.Builder(
FacebookConnectActivity.this).create();
alertDialog.setTitle("Erro");
alertDialog
.setMessage("Verifique sua conexão com a internet e tente novamente.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
alertDialog.dismiss();
finish();
}
});
alertDialog.show();
}
public static void waiting (int n){
long t0, t1;
t0 = System.currentTimeMillis();
do{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < n);
}
public static void logoutFB() {
if (facebook.isSessionValid()) {
Log.e("AndroidDashboarDesign",
"Valid FB session found, logging out");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.logout(staticContext, new BaseRequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.e("AndroidDashboarDesign", "Complete FB logout");
}
#Override
public void onIOException(IOException e, Object state) {
Log.e("AndroidDashboarDesign",
"(logout) IOException: " + e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.e("AndroidDashboarDesign",
"(logout) FileNotFoundException: " + e.getMessage());
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.e("AndroidDashboarDesign",
"(logout) MalFormedURLException: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.e("AndroidDashboarDesign", "(logout) FacebookError: "
+ e.getMessage());
}
});
}
}
public void startDataProcess() {
int count = 0;
while (json == null && count<20){
Log.e("FacebookConnect",
"Waiting for json (Valid session found)");
waiting(1000);
count++;
}
if (!(count<20)){
noConnectionAlert();
}else{
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
Log.e("FacebookConnect", "startDataProcess() executed");
Intent a = new Intent(FacebookConnectActivity.this,
FacebookDataProcess.class);
a.putExtra(TAG_JSON, json.toString());
startActivity(a);
finish();
}
}
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
Log.e("FacebookConnect", "SampleDialogListener complete");
final String postId = values.getString("post_id");
if (postId != null) {
Log.e("FacebookConnect",
"(SampleDialogListener) Dialog Success! post_id="
+ postId);
//mAsyncRunner.request(postId, new WallPostRequestListener());
//Log.e("FacebookConnect", "WallPostRequestListener started");
Toast.makeText(FacebookConnectActivity.this, "Mensagem postada com sucesso!", Toast.LENGTH_LONG).show();
startDataProcess();
} else {
Log.e("FacebookConnect",
"(SampleDialogListener) No wall post made, maybe canceled by user."); // Usuario
// clicou
// em
// Cancelar
startDataProcess();
}
}
public void onError(DialogError e) {
Log.e("FacebookConnect",
"Error authorizing: " + e.toString());
final AlertDialog alertDialog = new AlertDialog.Builder(
FacebookConnectActivity.this).create();
alertDialog.setTitle("Erro");
alertDialog
.setMessage("Erro ao tentar conectar com o facebook, não foi possível publicar em seu mural.");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
startDataProcess();
alertDialog.dismiss();
}
});
alertDialog.show();
}
public void onCancel() { // Usuario clicou no X do dialog
Log.e("FacebookConnect", "Post to Wall Canceled with \"X\" button");
startDataProcess();
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.e("FacebookConnect", "WallPostRequestListener complete");
Log.e("FacebookConnect", "(WallPostRequestListener) Got response: "
+ response);
String message = "<empty>";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("message");
} catch (JSONException e) {
Log.e("FacebookConnect",
"(WallPostRequestListener) JSON Error in response: "
+ e.toString());
} catch (FacebookError e) {
Log.e("FacebookConnect",
"(WallPostRequestListener) Facebook Error: "
+ e.getMessage());
// Toast.makeText(ctx, "Erro ao postar no Facebook.",
// Toast.LENGTH_LONG).show();
}
startDataProcess();
}
}
public class SampleRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: executed in background thread
Log.e("FacebookConnect", "SampleRequestListener complete");
Log.e("SampleRequestListener",
"Response: " + response.toString());
json = Util.parseJson(response);
Log.e("FacebookConnect", "JSON: " + json.toString());
// postOnWall();
// startDataProcess();
// 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.e("FacebookConnect",
"JSON Error in response (SampleRequestListener): "
+ e.getMessage());
} catch (FacebookError e) {
Log.e("FacebookConnect",
"Facebook Error at SampleRequestListener: "
+ e.getMessage());
}
}
}
public void postOnWall() {
Looper.prepare();
Bundle params = new Bundle();
params.putString("link", "www.qranio.com");
facebook.dialog(ctx, "feed", params, new SampleDialogListener());
Log.e("FacebookConnect", "SampleDialogListener started");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
callback = true;
Log.e("FacebookConnect",
"Authentication authorizeCallback called (onActivityResult)");
}
}
You used a different keystore file when you signed your application for distribution.
To fix this, run the same command but change the alias and the location of the keystore to the keystore file that you used for distribution
keytool -exportcert -alias YOUR_ALIAS_HERE -keystore ~/path/to/yourapp.keystore | openssl sha1 -binary | openssl base64
and paste the resulting string into your Facebook app's dashboard settings under the Android Key Hash section.
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.