Android
Users
Sign in with Facebook
21 min
how to add facebook login to your android app introduction in this guide, you will learn how to login using facebook login and parse user parse user class through back4app this tutorial uses a basic app created in android studio 4 1 1 with buildtoolsversion=30 0 3 buildtoolsversion=30 0 3 , compile sdk version = 30 compile sdk version = 30 and targetsdkversion 30 targetsdkversion 30 at any time, you can access the complete android project built with this tutorial at our github repositories kotlin example repository java example repository goal create a login with facebook feature to your android app using parse and back4app prerequisites to complete this tutorial, we need android studio an app created on back4app note follow the new parse app tutorial to learn how to create a parse app on back4app an android app connected to back4app note follow the install parse sdk tutoria l to create an android studio project connected to back4app a device (or virtual device ) running android 4 1 (jelly bean) or newer 1 facebook set up to start using facebook functions, you need to go to the facebook developer website and create an account and an app follow facebook’s quickstart guide by clicking here and pay attention to the following recommendations here are the steps included in facebook’s quickstart guide, which you need to follow carefully, as you are not going to follow them precisely as facebook suggests in step 3 instead of adding in the dependencies{} dependencies{} section at build gradle (module\ app) build gradle (module\ app) , add the following code in the dependencies{} dependencies{} section at build gradle (module\ app) build gradle (module\ app) remember to update the version of parse facebook utils sdk for android to the latest one you can find out which is the latest version at the jitpack website , following these steps at jitpack website paste parse community\ parsefacebookutils android parse community\ parsefacebookutils android in the git repo url git repo url box after doing that, click on the look up look up button then you should see the available versions of parse sdk for android, as shown in the following image in step 4, you’ll be asked to add internet permission at the application application element in /app/manifest/androidmanifest xml /app/manifest/androidmanifest xml file, but you have already added it while following install parse sdk tutorial so you don’t need to do this in step 6, you’ll need to provide key hashes, so you must have open ssl installed facebook’s guide doesn’t provide command lines to generate key hashes in linux, but doing that is simple, as all it requires from you is to open a terminal window and run the following command don’t follow the steps of facebook’s quickstart guide right after step 6 whats is sha 1 (secure hashing algorithm) sha 1, called the secure hashing algorithm, is the most common encryption algorithm sha 1, designed by united states national security agency sha 1 fingerprint is a unique key generated for your pc that can be used for signing its mainly used for submitting for using the some apis (like the facebook api we will use in this guide ) if you want to learn more details, you can visit the sha 1 wikipedia page you should follow the other steps described on facebook’s quickstart guide and not mentioned here 2 link your facebook app with back4app go to your app dashboard at back4app website and click on server settings server settings find the “facebook login” block and click on settings settings the “facebook login” block looks like this 3\ we need to add our facebook id, which we got from facebook guide to string xml(you should have followed the facebook guide and did this before) go to your android studio project, open your strings file /app/src/main/res/values/strings xml /app/src/main/res/values/strings xml , copy your facebook app id facebook app id and paste it in the facebook appid facebook appid field of the last page of back4app that you opened lastly, press the + + button 3 add provider element in the manifest file go back to your android studio project and inside the application application element in /app/manifest/androidmanifest xml /app/manifest/androidmanifest xml file, right after the meta data meta data element, add the following code 1 \<provider 2 android\ name="com facebook facebookcontentprovider" 3 \<! don't forget to put your facebook app id in the following link > 4 android\ authorities="com facebook app facebookcontentprovideryour facebook app id" 5 android\ exported="true" /> don’t forget to put your facebook app id in the code above 4 initialize parse facebook util sdks in your android studio project, in the java file called app app that extends application that you created to initialize the parse sdk, on its oncreate oncreate method, right after parse initialize() parse initialize() call, use the following code to initialize parse facebook utils sdk if you don’t have an app java app java file as described in this step, access the install parse sdk for android https //www back4app com/docs/android/parse android sdk documentation and make sure that you have followed all the steps required to install parse sdk correctly if you do not install parse sdk properly your facebook login with parse will not work 5 set up at the beginning of each parse activity, import the following 6 log in to implement your login activity, do the following import into your loginactivity loginactivity , in addition to the dependencies imported in step 4 2\ to implement facebook login, simply use the following code 1 final progressdialog dialog = new progressdialog(this); 2 dialog settitle("please, wait a moment "); 3 dialog setmessage("logging in "); 4 dialog show(); 5 collection\<string> permissions = arrays aslist("public profile", "email"); 6 parsefacebookutils loginwithreadpermissionsinbackground(this, permissions, (user, err) > { 7 dialog dismiss(); 8 if (err != null) { 9 log e("facebookloginexample", "done ", err); 10 toast maketext(this, err getmessage(), toast length long) show(); 11 } else if (user == null) { 12 toast maketext(this, "the user cancelled the facebook login ", toast length long) show(); 13 log d("facebookloginexample", "uh oh the user cancelled the facebook login "); 14 } else if (user isnew()) { 15 toast maketext(this, "user signed up and logged in through facebook ", toast length long) show(); 16 log d("facebookloginexample", "user signed up and logged in through facebook!"); 17 getuserdetailfromfb(); 18 } else { 19 toast maketext(this, "user logged in through facebook ", toast length long) show(); 20 log d("facebookloginexample", "user logged in through facebook!"); 21 showalert("oh, you!", "welcome back!"); 22 } 23 });1 val dlg = progressdialog(this) 2 dlg settitle("please, wait a moment ") 3 dlg setmessage("logging in ") 4 dlg show() 5 val permissions collection\<string> = listof("public profile", "email") 6 parsefacebookutils loginwithreadpermissionsinbackground(this, permissions) { user parseuser?, err parseexception? > 7 dlg dismiss() 8 when { 9 err != null > { 10 log e("facebookloginexample", "done ", err) 11 toast maketext(this, err message, toast length long) show() 12 } 13 user == null > { 14 toast maketext(this, "the user cancelled the facebook login ", toast length long) show() 15 log d("facebookloginexample", "uh oh the user cancelled the facebook login ") 16 } 17 user isnew > { 18 toast maketext(this, "user signed up and logged in through facebook ", toast length long) show() 19 log d("facebookloginexample", "user signed up and logged in through facebook!") 20 getuserdetailfromfb() 21 } 22 else > { 23 toast maketext(this, "user logged in through facebook ", toast length long) show() 24 log d("facebookloginexample", "user logged in through facebook!") 25 showalert("oh, you!", "welcome back!") 26 } 27 } 28 } in the example project, this code is placed inside a login via facebook login via facebook button callback 3\ after a successful login through facebook to our app, we can now get some basic logged user information as you can see, there are many more methods included in the code above the getuserdetailfromfb getuserdetailfromfb method is responsible for fetching user details here’s the code for this method 1 private void getuserdetailfromfb() { 2 graphrequest request = graphrequest newmerequest(accesstoken getcurrentaccesstoken(), (object, response) > { 3 parseuser user = parseuser getcurrentuser(); 4 try { 5 if (object has("name")) 6 user setusername(object getstring("name")); 7 if (object has("email")) 8 user setemail(object getstring("email")); 9 } catch (jsonexception e) { 10 e printstacktrace(); 11 } 12 user saveinbackground(e > { 13 if (e == null) { 14 showalert("first time login!", "welcome!"); 15 } else 16 showalert("error", e getmessage()); 17 }); 18 }); 19 20 bundle parameters = new bundle(); 21 parameters putstring("fields", "name,email"); 22 request setparameters(parameters); 23 request executeasync(); 24 }1 private fun getuserdetailfromfb() { 2 val request = 3 graphrequest newmerequest(accesstoken getcurrentaccesstoken()) { `object` jsonobject, graphresponse? > 4 val user = parseuser getcurrentuser() 5 try { 6 user username = `object` getstring("name") 7 } catch (e jsonexception) { 8 e printstacktrace() 9 } 10 try { 11 user email = `object` getstring("email") 12 } catch (e jsonexception) { 13 e printstacktrace() 14 } 15 user saveinbackground { 16 if (it == null) 17 showalert("first time login!", "welcome!") 18 else 19 showalert("error", it message) 20 } 21 } 22 val parameters = bundle() 23 parameters putstring("fields", "name,email") 24 request parameters = parameters 25 request executeasync() 26 } 4\ it’s interesting to add a method to display alert dialogs and make the process look more professional in this function, we also get a user parameter when going to the mainativity page, we send this user parameter in the intent, and in the mainactivity, we pull the information in this user and print it on the screen the method below does this 1 private void showalert(string title, string message) { 2 alertdialog builder builder = new alertdialog builder(this) 3 settitle(title) 4 setmessage(message) 5 setpositivebutton("ok", (dialog, which) > { 6 dialog cancel(); 7 intent intent = new intent(this, mainactivity class); 8 intent addflags(intent flag activity clear task | intent flag activity new task); 9 startactivity(intent); 10 }); 11 alertdialog ok = builder create(); 12 ok show(); 13 }1 private fun showalert(title string, message string?) { 2 val builder = alertdialog builder(this) 3 settitle(title) 4 setmessage(message) 5 setpositivebutton("ok") { dialog dialoginterface, which int > 6 dialog cancel() 7 val intent = intent(this\@loginactivity, mainactivity class java) 8 intent addflags(intent flag activity clear task or intent flag activity new task) 9 startactivity(intent) 10 } 11 val ok = builder create() 12 ok show() 13 } 5\ if you want to associate an existing parseuser to a facebook account, you can link it like so 1 collection\<string> permissions = arrays aslist("public profile", "email"); 2 if (!parsefacebookutils islinked(parseuser getcurrentuser())) { 3 parsefacebookutils linkwithreadpermissionsinbackground(parseuser getcurrentuser(), this, permissions, ex > { 4 if (parsefacebookutils islinked(parseuser getcurrentuser())) { 5 toast maketext(this, "woohoo, user logged in with facebook ", toast length long) show(); 6 log d("facebookloginexample", "woohoo, user logged in with facebook!"); 7 } 8 }); 9 } else { 10 toast maketext(this, "you have already linked your account with facebook ", toast length long) show(); 11 }1 val permissions= listof("public profile","email") 2 if (!parsefacebookutils islinked(parseuser getcurrentuser())){ 3 parsefacebookutils linkwithreadpermissionsinbackground(parseuser getcurrentuser(),this,permissions) { 4 if (parsefacebookutils islinked(parseuser getcurrentuser())){ 5 toast maketext(this, "woohoo, user logged in with facebook ", toast length long) show() 6 log d("facebookloginexample", "woohoo, user logged in with facebook!") 7 } 8 } 9 } else { 10 toast maketext(this, "you have already linked your account with facebook ", toast length long) show() 11 } 12 } in the example project, this code is placed inside a link your account to facebook link your account to facebook button callback 6\ if you want to unlink facebook from a user, simply do this 1 parsefacebookutils unlinkinbackground(parseuser getcurrentuser(), ex > { 2 if (ex == null) { 3 toast maketext(this, "the user is no longer associated with their facebook account ", toast length long) show(); 4 log d("myapp", "the user is no longer associated with their facebook account "); 5 } else { 6 toast maketext(this, ex getmessage(), toast length long) show(); 7 } 8 });1 parsefacebookutils unlinkinbackground(parseuser getcurrentuser()) { 2 if (it == null) { 3 toast maketext(this,"the user is no longer associated with their facebook account ",toast length long) show() 4 log d("myapp", "the user is no longer associated with their facebook account ") 5 } else { 6 toast maketext(this, it message, toast length long) show() 7 } 8 } in the example project, this code is placed inside a unlink your account from facebook unlink your account from facebook button callback 7\ it’s very important to use the following as a method outside the oncreate() oncreate() method of your loginactivity loginactivity to pass login results to the loginmanager via callbackmanager and avoid errors 1 @override 2 protected void onactivityresult(int requestcode, int resultcode, intent data) { 3 super onactivityresult(requestcode, resultcode, data); 4 parsefacebookutils onactivityresult(requestcode, resultcode, data); 5 }1 override fun onactivityresult(requestcode int, resultcode int, data intent?) { 2 super onactivityresult(requestcode, resultcode, data) 3 parsefacebookutils onactivityresult(requestcode, resultcode, data) 4 } 7 log out to implement facebook logout, simply use the code mentioned below 1 final progressdialog dialog = new progressdialog(this); 2 dialog settitle("please, wait a moment "); 3 dialog setmessage("logging out "); 4 dialog show(); 5 loginmanager getinstance() logout(); 6 parseuser logoutinbackground(e > { 7 if (e == null) 8 showalert("so, you're going ", "ok bye bye then", true); 9 else 10 showalert("error ", e getmessage(), false); 11 });1 val dlg = progressdialog(this) 2 dlg settitle("please, wait a moment ") 3 dlg setmessage("logging out ") 4 dlg show() 5 loginmanager getinstance() logout() 6 parseuser logoutinbackground { e > 7 if (e == null) 8 showalert("so, you're going ", "ok bye bye then", true) 9 else 10 showalert("error ", e message, false) 11 } in the example project, this code is placed inside a log out log out button callback the method alertdisplayer alertdisplayer is the same that you added in the loginactivity loginactivity , don’t forget to change its intent intent arguments though it’s done! at this stage, you can log in, register and log out of your app with facebook using parse server core features through back4app!