I was able to connect to Facebook with my application on android, and see my name, surname, etc. fields. Then I went to Facebook.com on my computer, and remove my application from allowed applications, and then re-enabled(FOR TESTING).
Then when I run my application I get the following error in Logcat:
FacebookError: Error validating access token: Session does not match current stored session.
This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.
I tried everything, searched the forums - but no luck.
My code:
public static final String TAG = "FACEBOOK";
private Facebook mFacebook;
public static final String APP_ID = "00112233211545";// I changed this when i publish to Stackoverflow
private AsyncFacebookRunner mAsyncRunner;
private static final String[] PERMS = new String[] { "read_stream" };
private SharedPreferences sharedPrefs;
private Context mContext;
private TextView username;
private ProgressBar pb;
public void setConnection() {
mContext = this;
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.extendAccessTokenIfNeeded(this, null);
}
public void getID(TextView txtUserName, ProgressBar progbar) {
username = txtUserName;
pb = progbar;
if (isSession()) {
Log.d(TAG, "sessionValid");
mAsyncRunner.request("me", new IDRequestListener());
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
}
public boolean isSession() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
String access_token = sharedPrefs.getString("access_token", "x");
Long expires = sharedPrefs.getLong("access_expires", -1);
Log.d(TAG, access_token);
if (access_token != null && expires != -1) {
mFacebook.setAccessToken(access_token);
mFacebook.setAccessExpires(expires);
}
return mFacebook.isSessionValid();
}
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
Log.d(TAG, "LoginONComplete");
String token = mFacebook.getAccessToken();
long token_expires = mFacebook.getAccessExpires();
Log.d(TAG, "AccessToken: " + token);
Log.d(TAG, "AccessExpires: " + token_expires);
sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(mContext);
sharedPrefs.edit().putLong("access_expires", token_expires)
.commit();
sharedPrefs.edit().putString("access_token", token).commit();
mAsyncRunner.request("me", new IDRequestListener());
}
public void onFacebookError(FacebookError e) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
public void onError(DialogError e) {
Log.d(TAG, "Error: " + e.getMessage());
}
public void onCancel() {
Log.d(TAG, "OnCancel");
}
}
private class IDRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
try {
Log.d(TAG, "IDRequestONComplete");
Log.d(TAG, "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String id = json.getString("id");
final String name = json.getString("name");
osnovni_meni.this.runOnUiThread(new Runnable() {
public void run() {
username.setText("Welcome: " + name+"\n ID: "+id);
pb.setVisibility(ProgressBar.GONE);
}
});
} catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
} catch (FacebookError e) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
}
public void onIOException(IOException e, Object state) {
Log.d(TAG, "IOException: " + e.getMessage());
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.d(TAG, "FileNotFoundException: " + e.getMessage());
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.d(TAG, "MalformedURLException: " + e.getMessage());
}
public void onFacebookError(FacebookError e, Object state) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
}
protected void onActivityResult1(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public void facebook_login(View view) throws IOException, JSONException
{
TextView txtUserName = (TextView) findViewById(R.id.txtUserName);
ProgressBar pbLogin = (ProgressBar) findViewById(R.id.pbLogin);
pbLogin.setVisibility(ProgressBar.VISIBLE);
setConnection();
getID(txtUserName, pbLogin);
}
You most likely get isSessionValid = true - which you need to ignore and run mFacebook.authorize anyway.
Related
My Scenario is like this
Activity -> clicked a button that will open other app (for example Facebook app-> loading -> gets data -> passing back to activity -> go back to the activity and call AsyncTask.
In my AsyncTask, I call onPreExecute to show a dialog, but after going back from other apps it doesn't proceed to showdialog and instead of finishing the AsyncTaskit goes to 'onDetachedFromWindow' and crashes. I'm wondering why and how can I solve this?
I'm having an error like this when it crashes
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#41fb6a60 is not valid; is your activity running?
Here is my onActivityResult() in my Activity
public class LoginActivity extends Activity {
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e(TAG, "I'm in onActivity " + resultCode);
if (requestCode == Constants.FACEBOOK_AUTH_RESULT_CODE) {
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
private class LoginDialogListener implements Facebook.DialogListener {
public void onComplete(Bundle values) {
Log.d(TAG, "LoginONComplete");
String token = facebook.getAccessToken();
long token_expires = facebook.getAccessExpires();
Log.d(TAG, "AccessToken: " + token);
Log.d(TAG, "AccessExpires: " + token_expires);
if (isPublishStreamAuthorized()) {
facebookSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
facebookSharedPreferences
.edit()
.putLong(Constants.FACEBOOK_ACCESS_EXPIRES,
token_expires).commit();
facebookSharedPreferences.edit()
.putString(Constants.FACEBOOK_ACCESS_TOKEN, token)
.commit();
facebookAsyncRunner.request("me", new IDRequestListener());
} else {
logoutFacebook();
}
}
public void onFacebookError(FacebookError e) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
public void onError(DialogError e) {
Log.d(TAG, "Error: " + e.getMessage());
Toast.makeText(getApplicationContext(), Constants.NO_INTERNET_CONNECTION,
Toast.LENGTH_LONG).show();
}
public void onCancel() {
Log.d(TAG, "OnCancel");
logoutFacebook();
}
}
private class IDRequestListener implements AsyncFacebookRunner.RequestListener {
public void onComplete(String response, Object state) {
try {
Log.d(TAG, "IDRequestONComplete");
Log.d(TAG, "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
id = json.getString("id");
fname = json.getString("first_name");
lname = json.getString("last_name");
email = json.getString("email");
name = json.getString("name");
gender = json.getString("gender");
locale = json.getString("locale");
verified = json.getString("verified");
// check if email is null
if(email == null) {
email = "";
}
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
Utils.setFacebookUser(context, name, id);
saveUserFBDetailsTask
= new SaveUserFBDetailsAsyncTask(id, fname, lname, email, name,
gender, locale, verified);
saveUserFBDetailsTask.execute();
/*
* String fbId, String fbFName, String fbLName, String email,
String fbName, String gender, String locale, String verified
* */
}
});
}
catch (JSONException e) {
Log.d(TAG, "JSONException: " + e.getMessage());
}
catch (FacebookError e) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
}
public void onIOException(IOException e, Object state) {
Log.d(TAG, "IOException: " + e.getMessage());
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.d(TAG, "FileNotFoundException: " + e.getMessage());
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.d(TAG, "MalformedURLException: " + e.getMessage());
}
public void onFacebookError(FacebookError e, Object state) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
}
Here is my AsyncTask inside my activity
class SaveUserFBDetailsAsyncTask extends AsyncTask<String, String, String> {
private String fbId, fbFName, fbLName, email, fbName, gender,
locale, verified,
result, errorCode, message, userId, cards, response;
private JSONObject returnData;
public SaveUserFBDetailsAsyncTask(String fbId, String fbFName, String fbLName, String email,
String fbName, String gender, String locale, String verified) {
this.fbId = fbId;
this.fbFName = fbFName;
this.fbLName = fbLName;
this.email = email;
this.fbName = fbName;
this.gender = gender;
this.locale = locale;
this.verified = verified;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
Here is my Facebook.java
public void authorize(Activity activity, String[] permissions,
int activityCode, final DialogListener listener) {
boolean singleSignOnStarted = false;
mAuthDialogListener = listener;
// Prefer single sign-on, where available.
if (activityCode >= 0) {
singleSignOnStarted = startSingleSignOn(activity, mAppId,
permissions, activityCode);
}
// Otherwise fall back to traditional dialog.
if (!singleSignOnStarted) {
startDialogAuth(activity, permissions);
}
}
public void authorizeCallback(int requestCode, int resultCode, Intent data) {
if (requestCode == mAuthActivityCode) {
// Successfully redirected.
if (resultCode == Activity.RESULT_OK) {
// Check OAuth 2.0/2.10 error code.
String error = data.getStringExtra("error");
if (error == null) {
error = data.getStringExtra("error_type");
}
// A Facebook error occurred.
if (error != null) {
if (error.equals(SINGLE_SIGN_ON_DISABLED)
|| error.equals("AndroidAuthKillSwitchException")) {
Util.logd("Facebook-authorize", "Hosted auth currently "
+ "disabled. Retrying dialog auth...");
startDialogAuth(mAuthActivity, mAuthPermissions);
} else if (error.equals("access_denied")
|| error.equals("OAuthAccessDeniedException")) {
Util.logd("Facebook-authorize", "Login canceled by user.");
mAuthDialogListener.onCancel();
} else {
String description = data.getStringExtra("error_description");
if (description != null) {
error = error + ":" + description;
}
Util.logd("Facebook-authorize", "Login failed: " + error);
mAuthDialogListener.onFacebookError(
new FacebookError(error));
}
// No errors.
} else {
setAccessToken(data.getStringExtra(TOKEN));
setAccessExpiresIn(data.getStringExtra(EXPIRES));
if (isSessionValid()) {
Util.logd("Facebook-authorize",
"Login Success! access_token="
+ getAccessToken() + " expires="
+ getAccessExpires());
mAuthDialogListener.onComplete(data.getExtras());
} else {
mAuthDialogListener.onFacebookError(new FacebookError(
"Failed to receive access token."));
}
}
// An error occurred before we could be redirected.
} else if (resultCode == Activity.RESULT_CANCELED) {
// An Android error occurred.
if (data != null) {
Util.logd("Facebook-authorize",
"Login failed: " + data.getStringExtra("error"));
mAuthDialogListener.onError(
new DialogError(
data.getStringExtra("error"),
data.getIntExtra("error_code", -1),
data.getStringExtra("failing_url")));
// User pressed the 'back' button.
} else {
Util.logd("Facebook-authorize", "Login canceled by user.");
mAuthDialogListener.onCancel();
}
}
}
}
I just used the latest Facebook SDK to solve it.
I've been stuck for days looking for a simple tutorial on making a facebook wall post with an icon or image and some text using the graph API. I've tried countless tutorials and they all seem very complicated and I can't get them to work. Even the samples that come with the SDK do not create sessions.
I have been sucessful in setting up the SDK and getting my APP_ID all that is left is the Java code for a custom button to share my app on the users wall.
You can post image on Facebook in two different ways. If you want to post a picture from a URL, you can post it as below:
Bundle parameters = new Bundle();
parameters.putString("description","your description/message");
parameters.putString("link", "your link");
parameters.putString("name", "Name of your application/ any name you want to post");
// parameters.putString("caption", " caption if any!");
parameters.putString("picture", "Link to your image");
try
{
facebook.request("me");
response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
}
catch (Exception e)
{
e.printStackTrace();
}
or if you want to post an image from SD card, you can create a Bitmap from the image you want to post and then convert it into ByteArray and post it as below:
Bundle parameters = new Bundle();
Log.e("byte array", ""+mByteArray);
parameters.putString("message", "your message");
parameters.putByteArray("picture", mByteArray);
try
{
facebook.request("me");
response = facebook.request("me/photos", parameters, "POST");
Log.d("Tests", "got response: " + response);
}
catch (Exception e)
{
e.printStackTrace();
}
P.S. The first method is to post image on user's Facebook wall, and the latter is for uploading picture with message in user's photo album on Facebook, which will also be posted as an update!
you can post your image with text from your application in a very simply way.
Call this method while clicking on the button widget say btnImagePostToWall like...
btnImagePostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postImageToWall();
}
});
Get Profile information by making request to Facebook Graph API....
public void postImageToWall() {
facebook.authorize(
this,
new String[] { "user_photos,publish_checkins,publish_actions,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) {
postImageonWall();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
private void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data); // image to post
params.putString("caption", "My text on wall with Image "); // text to post
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(),
null);
}
Just create a class SampleUploadListener which implements AsyncFacebookRunner.RequestListener...
class SampleUploadListener implements AsyncFacebookRunner.RequestListener {
#Override
public void onComplete(String response, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
}
Hope this will help you a bit.... :-)
here you go. you may have to do some debugging etc, but this worked for me.
FbLoginActivity class: performs authentication and posts to your wall and/or your app's wall.
usage:
Intent i = new Intent(getApplicationContext(), FbLoginActivity.class);
i.putExtra("SCORE", score);
startActivity(i);
FbLoginActivity:
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
public class FbLoginActivity extends Activity {
private final String TAG = "FbLoginActivity";
private String token; // used to identify the fb user
private static final String FACEBOOK_APP_ID = "your_key_here";
//private String[] permissions = { "email", "friends_about_me", "friends_location"};
private String[] permissions = {"publish_stream" };
private String rankText;
public static String userName;
private AlertDialog alertDialog;
private boolean isMyWall = false, isAppWall = true;
// facebook SSO
Facebook fb = new Facebook(FACEBOOK_APP_ID);
private AsyncFacebookRunner runner = new AsyncFacebookRunner(fb);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.register);
showFbDialog();
SessionEvents.addAuthListener(new SampleAuthListener());
}
private void accessUserData(String token) {
// get information about the currently logged in user
runner.request("me", meRequestListener);
}
private String getRankText() {
String txt = "your text to be shared here"
return txt;
}
private void postToFb() {
// post to feed
Bundle params = new Bundle();
params.putString("to", "me");
params.putString("message", "test msg");
try {
runner.request("me/feed", params, "POST", meRequestListener, null);
} catch(Throwable t) {
Log.e(TAG, "caught throwable: " + t, t);
Toast.makeText(this, "Error on login, is Facebook Installed?", Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(), MaleRankingActivity.class));
}
}
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, fb.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(fb);
//mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
private RequestListener meRequestListener = new RequestListener () {
//called on successful completion of the Request
public void onComplete(final String response, final Object state){
Log.d(TAG, "<onComplete> response: " + response);
try {
JSONObject fbResponse = new JSONObject(response);
// set userName
userName = fbResponse.getString("name");
Log.d(TAG, "<onComplete> fbResponse: " + fbResponse);
} catch (JSONException e) {
Log.e(TAG, "caught exception: " + e, e);
}
}
// called if there is an error
public void onFacebookError(FacebookError error, final Object state){}
public void onMalformedURLException(java.net.MalformedURLException e, Object state){}
public void onFileNotFoundException(FileNotFoundException arg0, Object arg1) {
// TODO Auto-generated method stub
}
public void onIOException(IOException arg0, Object arg1) {
// TODO Auto-generated method stub
}
};
private void authorizeAndPost() {
final Bundle params = new Bundle();
try {
// force authorization
//fb.logout(this);
/*
* Get existing access_token if any
*/
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null) {
fb.setAccessToken(access_token);
}
if(expires != 0) {
fb.setAccessExpires(expires);
}
fb.authorize(this, permissions, new DialogListener() {
public void onComplete(Bundle values) {
Log.d(TAG, "<onComplete> entry");
// get rank text
rankText = getRankText();
// set text
params.putString("message", rankText);
// post to ur wall
if (isMyWall) {
runner.request("me/feed", params, "POST", new WallPostRequestListener(), null);
}
// post to rate ur date wall
if (isAppWall) {
runner.request("259166150820823/feed", params, "POST", new WallPostRequestListener(), null);
}
// toast
CharSequence text = "Posted date to Facebook!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
toast.show();
// start ranking activity
Intent intent = new Intent(getApplicationContext(), ShareResultActivity.class);
intent.putExtra("share_result", "You have successfully posted your date to Facebook!");
token = fb.getAccessToken();
Log.d(TAG, "<onComplete> fb access token: " + token);
//intent.putExtra("userId", token);
long token_expires = fb.getAccessExpires();
Log.d(TAG, "<onComplete> token expires: " + token_expires);
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(FbLoginActivity.this);
prefs.edit().putLong("access_expires", token_expires).commit();
prefs.edit().putString("access_token", token).commit();
//fb.setAccessExpires(300000); // for testing
// access user data
accessUserData(token);
//postDateToFb();
startActivity(intent);
}
public void onFacebookError(FacebookError e) {
Log.e(TAG, "fb error: " + e.getMessage(), e);
}
public void onError(DialogError e) {
Log.e(TAG, "dialog error: " + e.getMessage(), e);
}
public void onAuthFail(String error) {
Log.d("<fbExample>", "login failed: " + error);
}
public void onCancel() {
Log.d(TAG, "fb cancelled");
}
});
} catch(Throwable t) {
Log.e(TAG, "caught throwable: " + t, t);
Toast.makeText(this, "Error on login, is Facebook Installed?", Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(), LandingActivity.class));
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.d("Facebook-Example", "Got response: " + response);
String message = "I just rated my date a creeper!";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("message");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
final String text = "Your Wall Post: " + message;
FbLoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
//mText.setText(text);
}
});
}
public void onCancel() {
Log.d(TAG, "fb cancel");
}
public void onComplete(Bundle arg0) {
Log.e(TAG, "fb complete.");
}
public void onError(DialogError arg0) {
Log.e(TAG, "fb err:" + arg0.getMessage());
}
public void onFacebookError(FacebookError arg0) {
Log.e(TAG, "fb err:" + arg0.getMessage());
}
public void onFacebookError(FacebookError arg0, Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage());
}
public void onFileNotFoundException(FileNotFoundException arg0,
Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
}
public void onIOException(IOException arg0, Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
}
public void onMalformedURLException(MalformedURLException arg0,
Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
}
}
public class SampleAuthListener implements SessionEvents.AuthListener {
public void onAuthSucceed() {
Log.d("<fbExample>", "fb auth token: " + fb.getAccessToken());
}
public void onAuthFail(String error) {
Log.d("<fbExample>", "login failed: " + error);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
fb.authorizeCallback(requestCode, resultCode, data);
}
private void showFbDialog() {
alertDialog = new AlertDialog.Builder(this)
.setTitle("I want to:")
.setMultiChoiceItems(new String[] {"Post to my wall", "Post to app's wall" },
new boolean[]{false, true, false, true, false, false, false},
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton,
boolean isChecked) {
/* User clicked on a check box do some stuff */
Log.d(TAG, "multichoice got click, whichButton: " + whichButton + ", isChecked: " + isChecked);
if (whichButton == 0 && isChecked) {
isMyWall = true;
}
if (whichButton == 1 && isChecked) {
isAppWall = true;
} else if (whichButton == 1 && !isChecked) {
isAppWall = false;
}
}
})
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
Log.d(TAG, "Ok got click");
authorizeAndPost();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
Log.d(TAG, "Cancel got click");
startActivity(new Intent(getApplicationContext(), YourActivity.class ));
}
})
.create();
alertDialog.show();
}
}
I am working on websocket communication with Autobahn.
On the main.class of my app, I set to call 'connect()' when users click a button.
// Toggle Button event
tButton = (ToggleButton) findViewById(R.id.toggleButton1);
tButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if(isChecked){
}else{
}
}
});
And after that, there is MyOffers.class, and if this class is accessed,
MyOffers_Fragment class is produced four times automatically, because MyOffers.class contains 'carousel view' and there are four products.
On 'MyOffers_Fragment' class, when users click one of the image of products, message should be sent.
if (pos == 0) {
product_photo.setImageResource(R.drawable.myoffers_0);
product_photo.setOnClickListener(new ImageButton.OnClickListener(){
public void onClick(View v){
String id = "Product0";
Log.d(TAG, "Current product is : " + id);
A.sendMessage(id);
}
});
}
But 'mConnection.sendTextMessage(id1);' this line makes 'NullPointerException' error.
There is a class 'Websocket_Connector.class'
public class WebSocket_Connector {
private static final String TAG = "ECHOCLIENT";
public final WebSocketConnection mConnection = new WebSocketConnection();
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
public void sendMessage(String message) {
connect("ws://192.168.x.xxx:xxxx");
mConnection.sendTextMessage(message);
}
}
I called 'connect()' in the main page class, and after that try to send message.
But, it's not working..Can you please help me out?
public class WebSocket_Connector {
private static final String TAG = "ECHOCLIENT";
public final WebSocketConnection mConnection = new WebSocketConnection();
private String tmpString = "";
public void connect(final String wsuri) {
Log.d(TAG, "Connecting to: " + wsuri);
try {
mConnection.connect(wsuri, new WebSocketHandler() {
#Override
public void onOpen() {
Log.d(TAG, "Status: Connected to " + wsuri );
Log.d(TAG, "Connection successful!\n");
mConnection.sendTextMessage(tmpString);
tmpString = "";
}
#Override
public void onTextMessage(String payload) {
Log.d(TAG, "Got echo: " + payload);
}
#Override
public void onClose(int code, String reason) {
Log.d(TAG, "Connection closed.");
}
});
} catch (WebSocketException e) {
Log.d(TAG, e.toString());
}
public void sendMessage(String message) {
if (mConnection.isConnected())
mConnection.sendTextMessage(message);
else {
tmpString = message;
connect("ws://192.168.x.xxx:xxxx");
}
}
}
I'm creating app that has share button on Facebook and I'm getting an error:
This Page Contains the following errors:
error on line 2 at column 182: Entityref: expecting ';'
Below is a rendering of the page up to the first error.
I don't get this error when I run the app on the Emulator. I'm only getting this kind of error when I run the app on the device.
What is the possible cause of this error?
Your help is highly appreciated. Thanks!
Code below is sample code for Facebook SDK:
public class FacebookShare extends Activity
{
private String APP_ID, APP_SECRET, Name, Link, Description, Picture;
private int fbTYPE;
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
private Activity ctx;
private Bitmap bitmap;
SharedPreferences mPrefs;
public FacebookShare(Activity ctx)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.ctx = ctx;
}
public void shareFB(int TypeOfSharing)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.fbTYPE = TypeOfSharing;
loginToFacebook();
}
public void loginToFacebook()
{
Log.v("debugging", "Entered Login to facebook");
String access_token = mPrefs.getString("access_token", "");
long expires = mPrefs.getLong("access_expires", 0);
if (!access_token.equals(""))
{
facebook.setAccessToken(access_token);
Log.v("Access Token", facebook.getAccessToken());
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
Log.v("debugging", "Session is Invalid");
facebook.authorize(ctx, new String[]{
"email","publish_stream"
}, facebook.FORCE_DIALOG_AUTH, new DialogListener()
{
public void onCancel()
{
// Function to handle cancel event
}
public void onComplete(Bundle values)
{
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
if (fbTYPE == 1)
{
postToWall();
}
else if (fbTYPE == 0)
{
postToWall(getBitmap());
}
}
public void onError(DialogError error)
{
Log.v("debugging", error.getMessage());
}
public void onFacebookError(FacebookError fberror)
{
Log.v("debugging", fberror.getMessage());
}
});
Log.v("debugging", "Passed from authorization");
}
else
{
if (fbTYPE == 1)
{
Log.v("debugging", "Entered Post to facebook");
postToWall();
}
else if (fbTYPE == 0)
{
Log.v("debugging", "Entered Post image to facebook");
postToWall(getBitmap());
}
}
}
public void clearCredentials()
{
try
{
facebook.logout(ctx);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void postToWall()
{
// post on user's wall.
Bundle params = new Bundle();
params.putString("description", getDescription());
params.putString("picture", getPicture());
params.putString("name", getName());
params.putString("link", getLink());
facebook.dialog(ctx, "feed", params, new DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
Toast.makeText(ctx, "Thanks for sharing JOLENPOP", Toast.LENGTH_SHORT).show();
}
public void onCancel()
{
// Login_Activity.asyncFBLogin fblogin = null;
// fblogin.execute();
}
});
}
public void postToWall(Bitmap bmImage)
{
Log.v("debugging", "entered postToWall(bitmap)");
byte[] data = null;
Bitmap bm = Bitmap.createBitmap(bmImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "post");
params.putString("message", getDescription());
params.putByteArray("image", data);
try
{
String response = facebook.request("me");
response = facebook.request("me/photos", params, "POST");
if (response == null || response.equals("") || response.equals("false"))
{
Log.v("response String", response);
return;
}
else if (response.toLowerCase().contains("error"))
{
Log.v("response String", response);
return;
}
}
catch (Exception e)
{
return;
}
Toast.makeText(ctx, "Your photo has been successfuly published!", Toast.LENGTH_LONG).show();
}
public void getProfileInformation()
{
mAsyncRunner.request("me", new RequestListener()
{
public void onComplete(String response, Object state)
{
Log.d("Profile", response);
String json = response;
try
{
JSONObject profile = new JSONObject(json);
// getting name of the user
String name = profile.getString("name");
// getting email of the user
String email = profile.getString("email");
runOnUiThread(new Runnable()
{
public void run()
{
// Toast.makeText(getApplicationContext(), "Name: " + name
// + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state)
{
}
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
public void onFacebookError(FacebookError e, Object state)
{
}
});
}
/**
* setters
* */
public void setFacebook(Facebook facebook)
{
this.facebook = facebook;
}
public void setAsyncRunner(AsyncFacebookRunner mAsyncRunner)
{
this.mAsyncRunner = mAsyncRunner;
}
public void setPrefs(SharedPreferences mPrefs)
{
this.mPrefs = mPrefs;
}
public void setName(String val)
{
this.Name = val;
}
public void setLink(String val)
{
this.Link = val;
}
public void setBitmap(Bitmap val)
{
this.bitmap = val;
}
public void setDescription(String val)
{
this.Description = val;
}
public void setPicture(String val)
{
this.Picture = val;
}
/**
* getters
* */
public String getAppID()
{
return this.APP_ID;
}
public String getName()
{
return this.Name;
}
public String getLink()
{
return this.Link;
}
public String getDescription()
{
return this.Description;
}
public String getPicture()
{
return this.Picture;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
Here how I used it:
fbShare = new FacebookShare(this);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
then;
Bitmap screenshot = this.glSurfaceView.mRenderer.screenCapture;
fbShare.setName("JOLENPOP");
fbShare.setDescription("I got a score of " + this.glSurfaceView.mRenderer.Score + " in JOLENPOP! Try to beat me!");
fbShare.setBitmap(screenshot);
fbShare.setPrefs(mPrefs);
fbShare.shareFB(0);
I want ask how can I redirect into someone's profile after successfully logging into Facebook?
Example : If successly logged in and authorized, it will direct into this page :
http://www.facebook.com/torasanshochiku.
I used this tutorial to connect Facebook
this is my FacebookConnectionActivity :
public abstract class FBConnectionActivity extends Activity {
public static final String TAG = "FACEBOOK";
private Facebook mFacebook;
public static final String APP_ID = "271496479563642";
private AsyncFacebookRunner mAsyncRunner;
private static final String[] PERMS = new String[] { "read_stream" };
private SharedPreferences sharedPrefs;
private Context mContext;
private TextView username;
private ProgressBar pb;
public void setConnection() {
mContext = this;
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
public void getID(TextView txtUserName, ProgressBar progbar) {
username = txtUserName;
pb = progbar;
if (isSession()) {
Log.d(TAG, "sessionValid");
mAsyncRunner.request("me", new IDRequestListener());
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
}
public boolean isSession() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
String access_token = sharedPrefs.getString("access_token", "x");
Long expires = sharedPrefs.getLong("access_expires", -1);
Log.d(TAG, access_token);
if (access_token != null && expires != -1) {
mFacebook.setAccessToken(access_token);
mFacebook.setAccessExpires(expires);
}
return mFacebook.isSessionValid();
}
private class LoginDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
Log.d(TAG, "LoginONComplete");
String token = mFacebook.getAccessToken();
long token_expires = mFacebook.getAccessExpires();
Log.d(TAG, "AccessToken: " + token);
Log.d(TAG, "AccessExpires: " + token_expires);
sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(mContext);
sharedPrefs.edit().putLong("access_expires", token_expires)
.commit();
sharedPrefs.edit().putString("access_token", token).commit();
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);
final String id = json.getString("id");
final String name = json.getString("name");
FBConnectionActivity.this.runOnUiThread(new Runnable() {
public void run() {
username.setText("Welcome: " + name+"\n ID: "+id);
pb.setVisibility(ProgressBar.GONE);
}
});
} 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) {
Log.d(TAG, "IOException: " + e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.d(TAG, "FileNotFoundException: " + e.getMessage());
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.d(TAG, "MalformedURLException: " + e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d(TAG, "FacebookError: " + e.getMessage());
}
}
//#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
}
What you can do to redirect a user to someone's profile is use the generic profile page link.
It looks something like this -
//facebook.com/profile.php?id=USER_FBID
Where USER_FBID is the users Facebook ID. So all you need to do is have the users FBID and you can navigate directly to their profile with the link. Note that I'm using a protocol relative URL to keep the user in the same protocol when redirecting. If the user was browsing securely with HTTPS then they will be redirected to a secure link. If the user is not browsing securely then they will be directed to a normal HTTP link.