ParseException: Invalid session token error - android

I did a simple sign up user interface just to check parse but for some reason every time i try to register a user it gives me this error
this is the code:
final ProgressDialog dlg = new ProgressDialog(this);
dlg.setTitle("Please wait.");
dlg.setMessage("Signing up. Please wait.");
dlg.show();
String username_str = username.getText().toString();
String password_str = password.getText().toString();
String re_password_str = re_password.getText().toString();
String email_str = email.getText().toString();
String phone_str = phone.getText().toString();
if(!re_password_str.equals(password_str)){
dlg.dismiss();
Toast.makeText(this,"Passwords does not match!!",Toast.LENGTH_SHORT).show();
password.setText("");
re_password.setText("");
}else if(email_str.isEmpty()|| phone_str.isEmpty()){
dlg.dismiss();
Toast.makeText(this,"email or phone cannot be empty!!",Toast.LENGTH_SHORT).show();
}else {
ParseUser new_user = new ParseUser();
new_user.setUsername(username_str);
new_user.setPassword(password_str);
new_user.setEmail(email_str);
new_user.put("phone", phone_str);
new_user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
dlg.dismiss();
if(e == null){
Intent i = new Intent(SignupActivity.this,MainActivity.class);
startActivity(i);
}else{
Log.d("signup error", e.toString());
Toast.makeText(SignupActivity.this,e.toString(),Toast.LENGTH_SHORT).show();
}
}
});
I've already spent 2 days in finding the problem but without any success....

I have deleted manually some data from the Parse Database. After that I was having this error when I was trying to save a new user in background:
com.parse.ParseRequest$ParseRequestException: invalid session token
My solution was to uninstall the apk and install it again. It solved the session problem for me.
Important: I did this in the Debug Database, so uninstalling a Debug App and install it again was fine.

You might not have logged out from your previous session. Make sure you have a log out logic. Also check if any of your users have logged in before signing in or signing up another user.
The belog code might help,
var currentUser = Parse.User.current();
if (currentUser) {
// do stuff with the user
Parse.User.logOut();
}
Also don't forget to add e.preventDefault(); in your sign up function.
This is how I had my signUp function..
$('.form-signup').on('submit', function(e) {
var currentUser = Parse.User.current();
if (currentUser) {
// do stuff with the user
Parse.User.logOut();
}
e.preventDefault();
var user = new Parse.User();
var username = $('#username').val();
var password = $('#password').val();
var email = $('#email').val();
user.set("username", username);
user.set("password", password);
user.set("email", email);
user.signUp(null, {
success: function(user) {
//signup successfull
alert("user created..!! User name: "+ username);
window.location = "login.html";
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
console.log("Error: " + error.code + " " + error.message);
//alert("User not created..!! " + error.message);
$("H5").html("User not created..!! " +error.message);
}
});
});

The reason for this problem is that you may be testing another Parse application on the same virtual device so the user credentials are still used for the new application. So, the solution for this is
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add this line and run your application
ParseUser.getCurrentUser().logOut();

It is due to data deletion from database but local storage still have that data. So you have to clear data from local storage.
Eg.
For Javascript (browser):
window.localStorage.clear()
For React Native:
AsyncStorage.clear();
For android:
Either clear cache or reinstall app

Yes I think after signing up a user you might have deleted that row from the users class, so first, write this code in your Activity
if(ParseUser.getCurrentUser()!=null){
Toast.makeText(this,"yes not null",Toast.LENGTH_SHORT).show();
ParseUser.logOut();
}
else{
Toast.makeText(this," null",Toast.LENGTH_SHORT).show();
}
You can find the difference when you run your app, first, it will toast you "yes not null" and after if you run your app again it will show you "null"
Now you can signup your user :)
This worked for me.
Hope it works for you as well.
You can find more info at.

It seems like a known bug in the Parse SDK. There is already a bug reported on the forum. They claim to have this fixed in the latest version 1.7.3. But it's not working for me either.
Refer to this https://developers.facebook.com/bugs/756392341145634/?search_id

I manually cleared the session and I had the same problem while trying to sign up a new user from the same device I signed up previously. Clearing the data for the App in DEVICE settings fixed the problem.

If you encounter this problem in your web app, clear the local storage of all Parse data. On Chrome this is:
Developer Tools (F12)
Application
Local Storage
Choose Parse entries and press Delete key (or Backspace)

Related

Unity - SignInWithCredentialAsync causes internal error when using Firebase with Facebook Login

I am a Unity programmer and I am using Firebase to manage user accounts. I tried to set up Facebook Login. No problems with the Facebook sdk and I can log in successfully. However, when the credential returned by Facebook sdk is used as a parameter of FirebaseAuth.DefaultInstance.SignInWithCredentialAsync, it returns internal error.
And here is my code:
void authCallBack(IResult result) {
if (result.Error != null) {
Debug.Log(result.Error);
}
else {
if (FB.IsLoggedIn) {
Debug.Log("Log in successfully.");
AccessToken token = AccessToken.CurrentAccessToken;
Credential credential = FacebookAuthProvider.GetCredential(token.TokenString);
accessToken(credential);
}
else
Debug.Log("not logged in");
}
}
public void accessToken(Credential firebaseResult) {
FirebaseAuth auth = FirebaseAuth.DefaultInstance;
Debug.Log("Auth CurrentUser: " + FirebaseAuth.DefaultInstance.CurrentUser);
if (!FB.IsLoggedIn){
return;
}
if (auth.CurrentUser != null && !string.IsNullOrEmpty(auth.CurrentUser.UserId)){
Debug.Log("CurrentUser ID: " + auth.CurrentUser.UserId);
auth.CurrentUser.LinkAndRetrieveDataWithCredentialAsync(firebaseResult).ContinueWith(task =>
{
if (task.IsCanceled || task.IsFaulted)
{
Debug.LogError("LinkWithCredentialAsync encountered an error: " + task.Exception);
// TODO: Show error message to player
return;
}
FirebaseUser newUser = task.Result.User;
Debug.LogFormat("Credentials successfully linked to Firebase user: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
} else {
auth.SignInWithCredentialAsync(firebaseResult).ContinueWith(task =>
{
if (task.IsCanceled || task.IsFaulted) {
Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception.InnerExceptions[0].Message);
// TODO: Show error message to player
return;
}
FirebaseUser newUser = task.Result;
Debug.LogFormat("Credentials successfully created Firebase user: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
}
}
More details in VS Debugging:
When I test it on my Android device, it comes out an error message g_methods_cached only.
Can anyone help?
P.S. Here is another question asked yesterday and I don't know if it is relevant.
FirebaseAuthWebException not found. Please verify the AAR
Oh, I have made a silly mistake!
In the Facebook Developer page, there is the App Secret in Setting > Basic. And it has to be added into Firebase Console with the App ID. No problem right now. And then......
I just copied the App Secret without showing and pasted into Firebase Console.
Which means I have set 8 black dots (●●●●●●●●) as my App Secret in my Firebase Console. I know it is too silly. But just in case there is someone careless like me.

Can you get a current users friendlist with facebook API? [duplicate]

I am trying to get my friend name and ids with Graph API v2.0, but data returns empty:
{
"data": [
]
}
When I was using v1.0, everything was OK with the following request:
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];
But now I cannot get friends!
In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.
Although Simon Cross's answer is accepted and correct, I thought I would beef it up a bit with an example (Android) of what needs to be done. I'll keep it as general as I can and focus on just the question. Personally I wound up storing things in a database so the loading was smooth, but that requires a CursorAdapter and ContentProvider which is a bit out of scope here.
I came here myself and then thought, now what?!
The Issue
Just like user3594351, I was noticing the friend data was blank. I found this out by using the FriendPickerFragment. What worked three months ago, no longer works. Even Facebook's examples broke. So my issue was 'How Do I create FriendPickerFragment by hand?
What Did Not Work
Option #1 from Simon Cross was not strong enough to invite friends to the app. Simon Cross also recommended the Requests Dialog, but that would only allow five requests at a time. The requests dialog also showed the same friends during any given Facebook logged in session. Not useful.
What Worked (Summary)
Option #2 with some hard work. You must make sure you fulfill Facebook's new rules: 1.) You're a game 2.) You have a Canvas app (Web Presence) 3.) Your app is registered with Facebook. It is all done on the Facebook developer website under Settings.
To emulate the friend picker by hand inside my app I did the following:
Create a tab activity that shows two fragments. Each fragment shows a list. One fragment for available friend (/me/friends) and another for invitable friends (/me/invitable_friends). Use the same fragment code to render both tabs.
Create an AsyncTask that will get the friend data from Facebook. Once that data is loaded, toss it to the adapter which will render the values to the screen.
Details
The AsynchTask
private class DownloadFacebookFriendsTask extends AsyncTask<FacebookFriend.Type, Boolean, Boolean> {
private final String TAG = DownloadFacebookFriendsTask.class.getSimpleName();
GraphObject graphObject;
ArrayList<FacebookFriend> myList = new ArrayList<FacebookFriend>();
#Override
protected Boolean doInBackground(FacebookFriend.Type... pickType) {
//
// Determine Type
//
String facebookRequest;
if (pickType[0] == FacebookFriend.Type.AVAILABLE) {
facebookRequest = "/me/friends";
} else {
facebookRequest = "/me/invitable_friends";
}
//
// Launch Facebook request and WAIT.
//
new Request(
Session.getActiveSession(),
facebookRequest,
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
FacebookRequestError error = response.getError();
if (error != null && response != null) {
Log.e(TAG, error.toString());
} else {
graphObject = response.getGraphObject();
}
}
}
).executeAndWait();
//
// Process Facebook response
//
//
if (graphObject == null) {
return false;
}
int numberOfRecords = 0;
JSONArray dataArray = (JSONArray) graphObject.getProperty("data");
if (dataArray.length() > 0) {
// Ensure the user has at least one friend ...
for (int i = 0; i < dataArray.length(); i++) {
JSONObject jsonObject = dataArray.optJSONObject(i);
FacebookFriend facebookFriend = new FacebookFriend(jsonObject, pickType[0]);
if (facebookFriend.isValid()) {
numberOfRecords++;
myList.add(facebookFriend);
}
}
}
// Make sure there are records to process
if (numberOfRecords > 0){
return true;
} else {
return false;
}
}
#Override
protected void onProgressUpdate(Boolean... booleans) {
// No need to update this, wait until the whole thread finishes.
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
/*
User the array "myList" to create the adapter which will control showing items in the list.
*/
} else {
Log.i(TAG, "Facebook Thread unable to Get/Parse friend data. Type = " + pickType);
}
}
}
The FacebookFriend class I created
public class FacebookFriend {
String facebookId;
String name;
String pictureUrl;
boolean invitable;
boolean available;
boolean isValid;
public enum Type {AVAILABLE, INVITABLE};
public FacebookFriend(JSONObject jsonObject, Type type) {
//
//Parse the Facebook Data from the JSON object.
//
try {
if (type == Type.INVITABLE) {
//parse /me/invitable_friend
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
// Handle the picture data.
JSONObject pictureJsonObject = jsonObject.getJSONObject("picture").getJSONObject("data");
boolean isSilhouette = pictureJsonObject.getBoolean("is_silhouette");
if (!isSilhouette) {
this.pictureUrl = pictureJsonObject.getString("url");
} else {
this.pictureUrl = "";
}
this.invitable = true;
} else {
// Parse /me/friends
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
this.available = true;
this.pictureUrl = "";
}
isValid = true;
} catch (JSONException e) {
Log.w("#", "Warnings - unable to process Facebook JSON: " + e.getLocalizedMessage());
}
}
}
Facebook has revised their policies now. You can’t get the whole friendlist anyway if your app does not have a Canvas implementation and if your app is not a game. Of course there’s also taggable_friends, but that one is for tagging only.
You will be able to pull the list of friends who have authorised the app only.
The apps that are using Graph API 1.0 will be working till April 30th, 2015 and after that it will be deprecated.
See the following to get more details on this:
User Friends
Facebook Application Development FAQ
In Swift 4.2 and Xcode 10.1:
If you want to get the friends list from Facebook, you need to submit your app for review in Facebook. See some of the Login Permissions:
Login Permissions
Here are the two steps:
1) First your app status is must be in Live
2) Get required permissions form Facebook.
1) Enable our app status live:
Go to the apps page and select your app
https://developers.facebook.com/apps/
Select status in the top right in Dashboard.
Submit privacy policy URL
Select category
Now our app is in Live status.
One step is completed.
2) Submit our app for review:
First send required requests.
Example: user_friends, user_videos, user_posts, etc.
Second, go to the Current Request page
Example: user_events
Submit all details
Like this submit for all requests (user_friends , user_events, user_videos, user_posts, etc.).
Finally submit your app for review.
If your review is accepted from Facebook's side, you are now eligible to read contacts, etc.
As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.
this is against Facebook policy, so depending on the country where you live, this may not be legal
you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
this is bypassing the OAuth concept
on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API
Sample implementation using WatiN:
class FacebookUser
{
public string Name { get; set; }
public long Id { get; set; }
}
public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
var users = new List<FacebookUser>();
Settings.Instance.MakeNewIeInstanceVisible = false;
using (var browser = new IE("https://www.facebook.com"))
{
try
{
browser.TextField(Find.ByName("email")).Value = email;
browser.TextField(Find.ByName("pass")).Value = password;
browser.Form(Find.ById("login_form")).Submit();
browser.WaitForComplete();
}
catch (ElementNotFoundException)
{
// We're already logged in
}
browser.GoTo("https://www.facebook.com/friends");
var watch = new Stopwatch();
watch.Start();
Link previousLastLink = null;
while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
{
var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).LastOrDefault();
if (lastLink == null || previousLastLink == lastLink)
{
break;
}
var ieElement = lastLink.NativeElement as IEElement;
if (ieElement != null)
{
var htmlElement = ieElement.AsHtmlElement;
htmlElement.scrollIntoView();
browser.WaitForComplete();
}
previousLastLink = lastLink;
}
var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).ToList();
var idRegex = new Regex("id=(?<id>([0-9]+))");
foreach (var link in links)
{
string hovercard = link.GetAttributeValue("data-hovercard");
var match = idRegex.Match(hovercard);
long id = 0;
if (match.Success)
{
id = long.Parse(match.Groups["id"].Value);
}
users.Add(new FacebookUser
{
Name = link.Text,
Id = id
});
}
}
return users;
}
Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.
Try /me/taggable_friends?limit=5000 using your JavaScript code
Or
try the Graph API:
https://graph.facebook.com/v2.3/user_id_here/taggable_friends?access_token=
If you are still struggling with this issue on a development mode.
Follow the same process as mentioned below:
create a test app of your main app,
create test users, automatically install app for test users and assign them 'user_friend' permission.
Add your test users as a friend with each other.
I followed the same process after going through alot of research and finally it worked.
In the Facebook SDK Graph API v2.0 or above, you must request the user_friends permission from each user in the time of Facebook login since user_friends is no longer included by default in every login; we have to add that.
Each user must grant the user_friends permission in order to appear in the response to /me/friends.
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email","user_friends","public_profile"], from: self) { (result, error) in
if (error == nil) {
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if (fbloginresult.grantedPermissions.contains("email")) {
// Do the stuff
}
else {
}
}
else {
}
}
}
So at the time of Facebook login, it prompts with a screen which contain all the permissions:
If the user presses the Continue button, the permissions will be set. When you access the friends list using Graph API, your friends who logged into the application as above will be listed
if ((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "/me/friends", parameters: ["fields" : "id,name"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
print(result!)
}
})
}
The output will contain the users who granted the user_friends permission at the time of login to your application through Facebook.
{
data = (
{
id = xxxxxxxxxx;
name = "xxxxxxxx";
}
);
paging = {
cursors = {
after = xxxxxx;
before = xxxxxxx;
};
};
summary = {
"total_count" = 8;
};
}

Android Studio Login/Register System ideas

I want to make a diet helper app for android devices, using android studio and
I need ideas on what to use to implement the login/register system, I followed a tutorial on youtube but it was outdated and I ended up wasting my time, then I've read on google, that android studio has a library called volley that I can use with PHP and MySql to make the login system.
Do you have other ideas, or is that the best one to go with?
I'm open to suggestions so shoot!
Update:
I've created a post about how to do this using a PHP backend for your Android application. https://keithweaver.ca/posts/4/android-php-custom-login
Additionally to the link above, this is how you can setup a server.
https://github.com/kweaver00/tutorials/blob/master/setup-server.md
https://keithweaver.ca/posts/9/setup-ubuntu-server-quickly
Original Post:
This is one solution and isn't guaranteed to be the best.
You can really use anything to communicate with a server. Async Tasks or Retrofit are both popular.
Assuming you have set up a server with a LAMP stack. Make sure you have an SSL so you don't pass user information that isn't encrypted.
Create a user table in mysql
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
pass varchar 250 default->null
signupdate date default-> null
Create a log in sessions table of some sort
Ex.
id int default->NULL AI primary-key
user varchar 250 default->null
token varchar 250 default->null
addedDate date default->null
Create a log in php script (I know this probably isnt the best way to right php code)
$connection = mysqli_connect("localhost", "phpmysqluser", "password", "dbname") or die("Error 404: unable to connect");
$username = $_POST['user'];
$pass = $_POST['pass'];
//add code to remove slashes and etc.
$result = mysqli_query($connection, "SELECT * FROM userTable WHERE user='$username' AND pass='$pass'") or die("Error: this line has error");
class response{
public $loggedin =0;
public $message = "";
}
$response = new response();
if(mysqli_num_rows($result) == 1){
$logInToken = generateLogInToken();
//have a function that creates a unique token and stores it for X days or minutes
$response->loggedin = 1;
$response->message = $logInToken;
}else{
$response->message = "wrong info";
}
echo json_decode($response);
This should output a json file like this depending on your user and pass variables.
{
"loggedin" : 1,
"message" : "asdnlansdkansd"
}
Right another script that passes in the log in token and user name to check if it's valid.
$connection .... //same as above
//well it really should be a include_once cause if you change credentials
$token = $_POST['token'];
$user = $_POST['user'];
$registeredDate = "";
$today = date('Y-m-d');
$result = mysqli_query($connection, "SELECT * FROM tokenTable WHERE user='$user' AND token='$token'") or die("Error...");
class response{
public $status = 0;
}
$response = new response();
if(mysqli_num_rows($result) == 1){
//check token has been register today and if not sign them out
while($row = mysqli_fetch_array($result)){
$registeredDate = $row['addedDate'];
}
if($registeredDate == $today){
//token is valid
$response->status = 3;
}else{
//expired
$response->status = 2;
}
}else{
//user and token are not valid
$response->status = 1;
}
echo json_decode($response);
Giving a json object like:
{
"status" : 3
}
In your Android app on open, run the code to check if the account is valid if there is anything stored locally. Or just go to log in screen.
On splash screen in the onCreate (you dont need a splash screen, its actually not recommended but its the easiest way to explain the process):
if(userNameAndTokenStoredInSharedPref()){
String token = getTokenFromSharedPref();
String userName = getUserNameFromSharedPref();
checkAgainstServer(token, userName);
}else{
Intent openLogInWindow = new Intent(this, LogInActivity.class);
startActivity(openLogInWindow);
}
still in the slash activity but out of the oncreate:
protected void checkAgainstServer(String token, String user){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(token, user, new Callback<UserStatusCallBack>() {
#Override
public void success(UserStatusCallBack userStatusCallback, retrofit.client.Response response) {
if(userStatusCallback.getStatus() == 1){
//Invalid token
}else if(userStatusCallback.getStatus() == 2){
//Expired token
}else if(userStatusCallback.getStatus() == 3){
//Success
Intent openMainWindow = new Intent(this, MainActivity.class);
startActivity(openMainWindow);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The log in activity would be something like:
logBtn.setOnClickListener(new View.onClick...
String userName = userNameEditText.getText().toString().toLowerCase().trim();
String password = passwordEditText.getText().toString().trim();
if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)){
callServerLogInScript(userName, password);
}
userNameEditText.setText("");
logBtn.setVisibility(View.GONE);
}
lower down the file:
protected void callServerLogInScript(String user, String pass){
//using retrofit
ThisAppRestClient.get().postCheckTokenAndUser(user, pass, new Callback<LogInCallBack>() {
#Override
public void success(LogInCallBack logInCallback, retrofit.client.Response response) {
if(logInCallback.getLoggedIn() == 1){
//succssful
storeUserNameInSharedPref(user);
storeTokenInSharedPref(logInCallback.getMessage());
Intent openMainActivity = new Intent(this, MainActivity.class);
startActivity(openMainActivity);
}else{
//incorrect log in
logBtn.setVisibility(View.VISIBLE);
}
}
#Override
public void failure(RetrofitError error) {
//Retrofit errors like timeouts, etc.
}
}
}
The reason for not storing the user name and password directly is if the device is rooted they can manipulate the data locally but not on your server.
It depends which you want to use. If you have your own server to host, then use php,mysql. If not, you can also use other third party which provides you to add if you know php,mysql to create.
Another option is if you don't want to use php mysql to store datas, then you can proceed with parse.com
So if you want to use parse.com, just register it. It's free to use.
Hope it will match your requirement, say for eg: if you want to create registration(everything saving in datas will be handled),you need to give exact object name that matches what you given in parse.com
Even you can also create in code itself without object name. I will show you a piece of example how to create and insert for registration..
ParseUser user = new ParseUser();
user.setEmail((txtEmail));//create an edittext and get the values in strings and store..
user.setPassword(txtPassword);//same for password
user.setUsername(txtUsername);//username
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
//completed..it has been registered
Toast.makeText(getApplicationContext(),
"Successfully Signed up, please log in.",
Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(),
"Sign up Error", Toast.LENGTH_LONG)
.show();
}
}
});
Simple one if you don't want to use php,mysql. Well documentation and easy to integrate and use it. Happy coding.
FYI: Android studio is IDE for development. And volley is HTTP library that makes networking for Android.

How to disable facebook native app for user login

I have a problem with facebook user login in my android application. I want users use their facebook account to login my system but when I click login button facebook native app starts and user enters email and password then native app closes and my app starts again. I dont want to use native app for this login proccess i want to open facebook login pop-up only like the other phones that does not have facebook native app.
How can i do this?
thanks
Edit:
I use the methods below for login
protected void loginToFacebook()
{
if( !mFacebook.isSessionValid() ) {
Toast.makeText(mActivity, "logining", Toast.LENGTH_SHORT).show();
mFacebook.authorize(mActivity,permissions, new LoginDialogListener());
}
else {
try {
JSONObject json = Util.parseJson(mFacebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
Toast.makeText(mActivity, mFacebook.getAccessToken()+email+"-" + firstName + " " + lastName + ". No need to re-authorize.", Toast.LENGTH_SHORT).show();
appState.mFbToken = mFacebook.getAccessToken();
appState.mFbEmail = email;
mFacebookListener.onFacebookLoginSelected();
}
catch( Exception error ) {
Toast.makeText( mActivity, error.toString(), Toast.LENGTH_SHORT).show();
}
}
}
For listening the response
public final class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
try {
//The user has logged in, so now you can query and use their Facebook info
JSONObject json = Util.parseJson(mFacebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
Toast.makeText( mActivity, mFacebook.getAccessToken() +email+"-" + firstName + " " + lastName + "!", Toast.LENGTH_SHORT).show();
SessionStore.save(mFacebook, mActivity);
appState.mFbToken = mFacebook.getAccessToken();
appState.mFbEmail = email;
mFacebookListener.onFacebookLoginSelected();
}
catch( Exception error ) {
Toast.makeText( mActivity, error.toString(), Toast.LENGTH_SHORT).show();
}
}
public void onFacebookError(FacebookError error) {
Toast.makeText( mActivity, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();
}
public void onError(DialogError error) {
Toast.makeText( mActivity, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();
}
public void onCancel() {
Toast.makeText( mActivity, "Something went wrong. Please try again.", Toast.LENGTH_LONG).show();
}
}
If native app starts my dialoglistenner does not work but if web based login pop-up starts my listenner works good.
Any Idea?
Please update below code of your application.
mFacebook.authorize(mActivity, permissions, Facebook.FORCE_DIALOG_AUTH,
new LoginDialogListener());
instead of
mFacebook.authorize(mActivity, permissions, new LoginDialogListener());
And see below link for more information
Facebook Login Issue
I'm sure this is possible, unfortunately I forgot how to do it. But as far as I remember the idea is that you should force the login dialog to appear. If I'm not mistaken a boolean parameter should be set to the dialog to force it appear.
iOS and Android use something called Single Sign-on (SSO), which means anyone attempting to use Facebook in a 3rd Party app will launch the Facebook App for easier login. If the user has Facebook App installed, it will always launch the app for login - there is no way around it.
It's actually there for make it easier for the user. The user would usually be logged into the App already so using a 3rd Party FB App would only take a single touch / tap to authorise and use. You will find that user's without the FB app will see the web-based login page.
Don't enable SSO. This should resolve your problem.

How to retrieve an Facebook-AuthToken from the accounts saved on Android

I'm trying to retrieve the AuthToken for Facebook (saved by Facebook for Android) by using the following piece of code.
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType("com.facebook.auth.login");
if (accounts.length > 0) {
for(int j = 0; j < accounts.length; j++) {
Account account = accounts[j];
if(account.type != null && account.type.equals("com.facebook.auth.login")) {
Log.e(RuntimeVars.MY_NAME, "FACEBOOK-TYPE FOUND");
am.getAuthToken(account, "com.facebook.auth.login", null, ConversationList.this,
new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle b = arg0.getResult();
Log.e(RuntimeVars.MY_NAME, "THIS AUTHTOKEN: " + b.getString(AccountManager.KEY_AUTHTOKEN));
}
catch (Exception e) {
Log.e(RuntimeVars.MY_NAME, "EXCEPTION#AUTHTOKEN");
}
}
}, null);
}
}
}
The login credentials are found and FACEBOOK-TYPE FOUND is written into LogCat, but neither THIS AUTHTOKEN: [...] nor EXCEPTION#AUTHTOKEN is logged. So I suppose am.getAuthToken is never called.
What am I missing?
In general, if there is a better (and at least working) approach to retrieve the Facebook authtoken from the Android accounts please let me know.
Thanks a lot for your help!
Best regards
S.
Why not use the Facebook SDK?
The Facebook class in it has a member to get the OAuth 2.0 access token (if that is what you need), getAccessToken().
To explain the fact that neither of your logging statements are being reached, consider:
Line ~8:
am.getAuthToken(account, "com.facebook.auth.login", null, ConversationList.this,
... can return a token if it's immediately available. Maybe that's the answer you're looking for? Quoting the AccountManager documentation:
If a previously generated auth token
is cached for this account and type,
then it is returned. Otherwise, if a
saved password is available, it is
sent to the server to generate a new
auth token. Otherwise, the user is
prompted to enter a password.
Try calling AccountManager.blockingGetAuthToken instead. If that works, then there's something more interesting at fault here...
Also, make sure your manifest has the USE_CREDENTIALS permission set correctly.
add try { before am.getAuthToken and catch Exception where this method declaration ends.This will give you why and where excepption is happening

Categories

Resources