Android - Facebook Cancels - java

Every time I run my app and it tries to connect to facebook it cancels. It is already authroized and I can connect on my normal Facebook app. I have been looking for a solution for about two days now and can't find any. This is really the only problem holding me back from finishing my app... Hopefully I can get some answers.
I am using this Facebook SDK
Here is my facebook authorize code:
public void authFB(){
Log.i("IN","FB - Authorizing");
fb.authorize(this, new String[]{ "publish_stream" }, new DialogListener(){
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.putString("post_id",values.getString("post_id"));
editor.commit();
Log.i("IN","Login Successful");
checkFB();
}
#Override
public void onFacebookError(FacebookError e) {
Log.i("IN","Login UnSuccessful - fb error");
e.printStackTrace();
checkFB();
}
#Override
public void onError(DialogError e) {
Log.i("IN","Login UnSuccessful - error");
e.printStackTrace();
checkFB();
}
#Override
public void onCancel() {
Log.i("IN","Login UnSuccessful - cancel");
checkFB();
}
});
}
Here is my onCreate:
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prefs = getPreferences(MODE_PRIVATE);
String access_token = prefs.getString("access_token", null);
//String post_id = prefs.getString("post_id",null);
long expires = prefs.getLong("access_expires",0);
if(access_token != null){
fb.setAccessToken(access_token);
}
if(expires != 0){
fb.setAccessExpires(expires);
}
if(!fb.isSessionValid()){
authFB();
}
I have ZERO ideas about what is wrong. I have tried it on two different phones now and this is the debug I get:
03-07 18:18:43.460: INFO/IN(6741): Login UnSuccessful - cancel
That means onCancel is being called.
CONFUSED.
Thanks.

Fixed it myself.
I kept getting this error because I had this in my manifest for my activities:
android:launchMode="singleInstance"
I am posting this because hopefully it will help someone in the future.
The reason why it created an error is because it tried to create a secondInstance (duh) and that isnt allowed.

Related

Threads at onCreate() method execute before setting the view

I'm creating my splash screen for app. While loading it executes 4 methods. First one checks if Internet permission is granted, second one sends request to API to check if it is Online, third one is getting Token from Firebase and the fourth one is checking if user is already logged-in. I'm doing it using 4 threads. Each method in case of error sets the flag as false. Then when all the threads end their work (I used .join()) The last method checks the state of flag and launch new activity or just display Error and try everything once again.
The problem I have is that I'm getting the view after all the threads finish their work. For example I have black screen, then message ("Error occured") and only after that I can see UI. But on Error the UI is refreshed, so one more time I have black screen, then result and UI for 1sec until another restart.
My question is, can I in some way stop these Threads until my UI is ready ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
setContentView(R.layout.activity_splash);
checkProgress = findViewById(R.id.checkProgressText);
auth = FirebaseAuth.getInstance();
tokenUtils = new TokenUtils();
requestQueue = Volley.newRequestQueue(getApplicationContext());
animatedCircleLoadingView = findViewById(R.id.circle_loading_view);
//starting the animation
startLoading();
Thread[] checkers = new Thread[4];
checkers[0] = new Thread(this::checkInternetPermissions);
checkers[1] = new Thread(this::checkConnection);
checkers[2] = new Thread(this::getUserAuth);
checkers[3] = new Thread(this::getUserToken);
for (Thread t : checkers) {
try {
t.start();
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeActivity();
}
Check internet permission method:
private void checkInternetPermissions() {
checkProgress.setText(getString(R.string.check_internet_permissions_text));
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED)
requestPermissions(new String[]{Manifest.permission.INTERNET}, 1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode != 1) {
connectionFlag = false;
}
}
Check connection method:
private void checkConnection() {
checkProgress.setText(getString(R.string.checking_api_connection));
RequestFuture<String> requestFuture = RequestFuture.newFuture();
StringRequest request = new StringRequest
(Request.Method.GET, API_CHECK,
requestFuture,
requestFuture);
requestQueue.add(request);
String response = null;
try {
response = requestFuture.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
this.connectionFlag = false;
}
if (!Objects.equals(response, "ok"))
this.connectionFlag = false;
}
Get user token method:
private void getUserToken() {
checkProgress.setText(getString(R.string.getting_user_auth_token));
String token = null;
try {
token = tokenUtils.getFirebaseToken();
} catch (ExecutionException | InterruptedException e) {
this.connectionFlag = false;
}
if (Objects.isNull(token) || Objects.requireNonNull(token).isEmpty())
this.connectionFlag = false;
}
And finally get user auth method:
private void getUserAuth() {
checkProgress.setText(getString(R.string.checking_user_auth));
authStateListener = firebaseAuth -> {
firebaseUser = firebaseAuth.getCurrentUser();
if (Objects.isNull(firebaseUser) || Objects.requireNonNull(firebaseUser.getEmail()).isEmpty()) {
this.authFlag = false;
}
};
}
Last method which handle the states of flags:
private void changeActivity() {
checkProgress.setText(getString(R.string.finalizing_text_progress));
if (connectionFlag && authFlag) {
startActivity(new Intent(SplashActivity.this, MapActivity.class));
} else if (!connectionFlag) {
Toast.makeText(getApplicationContext(), "Error occurred.", Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
} else {
startActivity(new Intent(SplashActivity.this, LoginActivity.class));
}
}
Yes, You can try it with handler thread with some delay then it will work fine or you can start your thread on onResume() method at the time of onResume your view will have been created
I think, your way wrong. Because, API request working on asynchronous. Your app should run like this;
Check Internet connection.
API Request.
Get token in API Request onSuccess method.
Get User Auth.
I think, you shouldn't use Thread.

Google+ sign in for android not working, error code 4

I have followed the guide on how to setup google+ sign in. I did every step and basically copy and pasted the code.
Here is the scenario. I develop on two different computers. I have two different client-ids in my console. One for computer A and one for computer B.
When i install the application and launch it, it will attempt to sign in and fail with the following error from logcat. If i back out of the app and re-launch, it will then sign in fine. When it fails, it will seem to be trying to launch an Activity but the Activity is never launched. Here is the logcat.
06-04 10:14:57.801 19948-19948/carbon.android.game.legions D/AccountFragment﹕ ResolveSignInError ErrorCode:4
06-04 10:14:57.801 602-823/? I/ActivityManager﹕ START u0 {cmp=com.google.android.gms/.plus.activity.AccountSignUpActivity (has extras)} from pid -1
06-04 10:14:57.811 178-646/? D/audio_hw_primary﹕ select_devices: out_snd_device(2: speaker) in_snd_device(0: )
06-04 10:14:57.811 178-646/? D/ACDB-LOADER﹕ ACDB -> send_afe_cal
06-04 10:14:57.821 602-2816/? I/ActivityManager﹕ START u0 {act=com.google.android.gms.common.account.CHOOSE_ACCOUNT pkg=com.google.android.gms cmp=com.google.android.gms/.common.account.AccountPickerActivity (has extras)} from pid 20027
06-04 10:14:57.941 20027-20031/? D/dalvikvm﹕ GC_CONCURRENT freed 601K, 7% free 9304K/9940K, paused 2ms+2ms, total 19ms
06-04 10:14:58.071 949-959/? W/GLSUser﹕ GoogleAccountDataService.getToken()
What am i doing wrong? I followed the guide word for word and basically copy and pasted the code. The only difference is that i am inside of a Fragment and not an Activity. But, that shouldn't matter.
Here is the code:
public class AccountFragment extends Fragment implements View.OnClickListener,
ConnectionCallbacks,
OnConnectionFailedListener {
private static final int RC_SIGN_IN = 1524;
private GoogleApiClient googleApiClient;
private boolean intentInProgress;
private boolean signInClicked;
private ConnectionResult connectionResult;
private SignInButton signInButton;
public AccountFragment() {}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "The connection failed: " + connectionResult.getErrorCode());
if (!this.intentInProgress) {
this.connectionResult = connectionResult;
if (this.signInClicked) {
this.resolveSignInError();
}
}
}
#Override
public void onStart() {
super.onStart();
this.googleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
if (this.googleApiClient.isConnected()) {
this.googleApiClient.disconnect();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.googleApiClient = new GoogleApiClient.Builder(this.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
if (!this.googleApiClient.isConnecting() && !this.googleApiClient.isConnected()) {
this.signInClicked = true;
this.resolveSignInError();
} else {
Log.d(TAG, "OnClick else");
}
break;
default:
break;
}
}
#Override
public void onConnected(Bundle bundle) {
this.signInClicked = false;
Person currentPerson = Plus.PeopleApi.getCurrentPerson(this.googleApiClient);
Log.d(TAG, "User connected: " + currentPerson.getDisplayName());
Log.d(TAG, "User id: " + currentPerson.getId());
Toast.makeText(this.getActivity(), "User connected: " + currentPerson.getDisplayName(), Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
this.googleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
if (resultCode != Activity.RESULT_OK) {
this.signInClicked = false;
}
this.intentInProgress = false;
if (!this.googleApiClient.isConnecting()) {
this.googleApiClient.connect();
}
}
}
private void resolveSignInError() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.getActivity()) != ConnectionResult.SUCCESS) {
Log.e(TAG, "Google Play Services is not available.");
}
Log.d(TAG, "ResolveSignInError ErrorCode:" + this.connectionResult.getErrorCode());
if (this.connectionResult.hasResolution()) {
this.intentInProgress = true;
try {
this.connectionResult.startResolutionForResult(this.getActivity(), RC_SIGN_IN);
} catch (SendIntentException e) {
e.printStackTrace();
this.intentInProgress = false;
this.googleApiClient.connect();
}
}
}
}
I figured out my issue.
There were a couple of issues.
With all my testing, i have been attempting to sign in the whole time. And was successful sometimes. Somehow, i was remaining authenticated even though my app was not signed in. I added the ability to sign out and revoke access. After revoking access and attempting to sign in again, the Activity would launch to resolve any errors.
I was also having the issue that is being discussed here. My host Activity was consuming my onActivityResult(...) from my connectionResult.startResolutionForResult(...);. So, after some trial and error i finally found a solution to that issue as well. The question linked helped but did not fully solve the issue. Please view my answer to that question for how i solved the problem.
Lesson, make sure that you are signing out and revoking access while testing. If you are having these issues, try revoking access and then signing back in.
In my case i solve my problem by doing following step, its old que but others my also having this problem so
Follow these stem in android development Console
Open the Credentials page.
Click Add credentials > OAuth 2.0 client ID.
Select Android.
and fill the fingerprint and package name .
Click Create.
Then there will be successful sing in from google.
Hope this may solve your problem. !!!
Please msg me if any problem occurs.

Google Cloud Messaging - Check if device is already registered

I just set up GCM in my Android App. But I have the problem that I don't know how to check if the device is already registered. I work with the new google play services library.
The register part looks like this:
#Override
protected String doInBackground(String... arg0) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context_app);
}
regid = gcm.register(SENDER_ID);
msg = "Dvice registered, registration ID=" + regid;
Log.d("111", msg);
sendRegistrationIdToBackend(regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
How can I modify this that it checks if the device is already registered?
Store the registration id in a databade table or shared preference and when app starting..check whether it is null or not
Google has provided very clear documentation with code.You should use following code:
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
boolean registered =
ServerUtilities.register(context, regId);
// At this point all attempts to register with the app
// server failed, so we need to unregister the device
// from GCM - the app will try to register again when
// it is restarted. Note that GCM will send an
// unregistered callback upon completion, but
// GCMIntentService.onUnregistered() will ignore it.
if (!registered) {
GCMRegistrar.unregister(context);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
#Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
when you get registration Id, Store it in SharedPreferences, for example:
SharedPreferences shp = context.getSharedPreferences("anyNameYouLike",MODE_PRIVATE);
SharedPreferences.Editor editor=shp.edit();
editor.putString("RegID",registrationID).commit;
In the next time before you register check the "anyNameYouLike" if it contain field called RegID Like this:
private boolean isRegistered(Context context){
SharedPreferences shp = context.getSharedPreferences("anyNameYouLike",PRIVATE_MODE);
return shp.contains("RegID");
}

Getting a Malformed access token "t ​ype":"OAuthException","code":190

I am writing an android application to get the Facebook user albums and photos and display in my Android application.
I have created a Facebook App with APP_ID 281846961912565.
While creating the Facebook instance, I am passing this id as follows
facebook = new Facebook(APP_ID);
Using this instance, I am able to login to my FB account post on messages on facebook wall programatically.
After logging in, I get an access_token.
I'm using the access token to get the album ids using facebook.request("https://graph.facebook.com/me/albums?access_token="+facebook.getAccessToken());
Now I get {"error":{"message":"Malformed access token ACCESSTOKENACCESSTOKEN?access_token=ACCESSTOKENACCESSTOKEN","t‌​ype":"OAuthException","code":190}}
Can any of you please help me resolve this issue and point out what i am doing wrong.
My code is as follows:
private static final String[] PERMISSIONS = new String[] { "publish_stream","user_photos" };
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();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext()
.getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.facebook_dialog);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null) {
facebookMessage = "Test wall post";
}
messageToPost = facebookMessage;
}
R.layout.facebook_dialog is the dialog which pops up asking if a message should be shared on facebook or not. If yes the following method is called.
public void share(View button) {
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new LoginDialogListener());
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null) {
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
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!");
}
getImagesFromUserAlbum();
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
Later when I do a `private void getImagesFromUserAlbum() {
facebook.getAccessToken();
JSONArray albumss = null;
String response = null;
try {
response = facebook.request("me/albums");
// `
I get the error
{"error":{"message":"Malformed access token ACCESSTOKEN?access_token=ACCESSTOKEN","type":"OAuthException","code":190}}
Thanks for your help.
The code above is now the working copy. Thanks to Bartek.
If you look at the Errors page in the documentation you will see that when you get error 190 you should authorise/reauthorise the user.
I suspect that this happened to you because you first logged in, then added the permissions to access the albums to your application BUT did not log out and log back in. Hence, you need to obtain a new access token which will grant the new permissions to your application.
Please check is there &expires in your access token if yes then remove it because it is not part of access_token and try after that.

Updating Facebook from Android

I have the below script running and it works perfectly. What I am wondering is. Why does facebook give me a secret key if I dont have to implement it as I have not below.
Facebook facebook = new Facebook("APP_ID"); // Application ID of your app at facebook
boolean isLoggedIn = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Implementing SSO
facebook.authorize(this, new String[]{"publish_stream"}, new DialogListener(){
#Override
public void onComplete(Bundle values) {
//control comes here if the login was successful
// Facebook.TOKEN is the key by which the value of access token is stored in the Bundle called 'values'
Log.d("COMPLETE","AUTH COMPLETE. VALUES: "+values.size());
Log.d("AUTH TOKEN","== "+values.getString(Facebook.TOKEN));
updateStatus(values.getString(Facebook.TOKEN));
}
#Override
public void onFacebookError(FacebookError e) {
Log.d("FACEBOOK ERROR","FB ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
}
#Override
public void onError(DialogError e) {
Log.e("ERROR","AUTH ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
}
#Override
public void onCancel() {
Log.d("CANCELLED","AUTH CANCELLED");
}
});
}
//updating Status
public void updateStatus(String accessToken){
try {
Bundle bundle = new Bundle();
bundle.putString("message", "test update"); //'message' tells facebook that you're updating your status
bundle.putString(Facebook.TOKEN,accessToken);
//tells facebook that you're performing this action on the authenticated users wall, thus
// it becomes an update. POST tells that the method being used is POST
String response = facebook.request("me/feed",bundle,"POST");
Log.d("UPDATE RESPONSE",""+response);
} catch (MalformedURLException e) {
Log.e("MALFORMED URL",""+e.getMessage());
} catch (IOException e) {
Log.e("IOEX",""+e.getMessage());
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("onActivityResult","onActivityResult");
facebook.authorizeCallback(requestCode, resultCode, data);
}
The most likely reason is that you had already logged on for this app, or had previously logged on with the Facebook app, as a result of which Facebook had allocated you an access token - which is then valid until the app explicitly signs off, or the user disables app access (in the Facebook server-side user profile).
So when you do the authorize, the underlying Facebook SDK simply retrieves the access token, and you do not need to login.
You can disable the access token by going to Facebook for your user and doing Account settings (drop down at top right), then Apps (at left) and disabling your app's access. At which point, when you next run your app, the user will have to log in to Facebook and authorize your app.

Categories