How to show user data stored in child firebase android - java

I was tired how to retrieve single data from child in my firebase, but when using setAuthenticatedUser to retrieve user email it work successfully..
my question how to get my other sigle child like my email to TextView?
this my MainActivity.java after Logged in
private void setAuthenticatedUser(AuthData authData) {
mAuthData = authData;
if (authData != null) {
/* User auth has not expire yet */
// Get unique current user ID
mCurrentUserUid=authData.getUid();
// Get current user email
mCurrentUserEmail= (String) authData.getProviderData().get("email");
String email = mCurrentUserEmail;
tvEmail.setText(emails.toString()); // success
// Get current user Full Name
mCurrentUserFullname= (String) authData.getProviderData().get("fullName");
String fName = mCurrentUserFullname;
tvName.setText(fName.toString()); // aborted
} else {
// Token expires or user log out
// So show logIn screen to reinitiate the token
navigateToLogin();
}
}
this is my json in firebase
enter image description here
Thankyou for helping me, sorry with my english & keep learning :)

Related

FirebaseUser instance not null. Is it retrieving the first registered user on the same device even after clearing data?

I have the following case using one physical device:
User authenticate and signs in the app with (123)-456-7890 phone number. User has "User UID" gets created in Firebase Authentication.
Now I go to app info--> clear data. Use the same (123)-456-7890 phone number, and I do have method:
private boolean isUserNewUser(Task<AuthResult> task) {
return task.getResult() != null && task.getResult().getAdditionalUserInfo().isNewUser();
}
that checks if the user is a new user or not. Since it is the same phone number, the second user will not have the possibility to create a new User UID in Firebase Authentication, as a result won't authenticate.
Now, I close the app, launch it again, and I do have a method set in the first launcher activity that gets triggered and user instance is not null.
mAuthListener = firebaseAuth -> {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//User is signed in
ActivitiesHelper.intentActivityLauncher(this,
HomeActivity.class, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
//User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
};
Question:
How can it be possible that the callback is returning a non null instance of FirebaseUser?
. According to FirebaseInstanceId doc, Instance ID is stable except when:
App deletes Instance ID
App is restored on a new device
User uninstalls/reinstall the app
User clears app data
However every time you launch your app after clearing its data , a different Token is returned through the FirebaseInstanceIdService onTokenRefreshed() callback.
this is the normal behaviour of the service .
i advice you to go there and read about creating Custom Tokens

How to save the response data return by Facebook in Java class using Spring MVC

I am trying to save the user data which is return by the Facebook response.
I am using Facebook Javascript.Response is in JSon format and I want to parse it first and then save it in to my database using java.
<script>
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
/* var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
console.log("User id is" + uid);
console.log(accessToken); */
document.getElementById('accesstoken').value=response.authResponse.accessToken;
console.log(response.authResponse.accessToken);
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxxxxxx',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.2' // use version 2.2
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
// window.location="http://localhost:8080/SpringMvcHibernateJavaBased/list";
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
console.log(response);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
document.getElementById('usernamefb').value=response.name;
document.getElementById('userId').value=response.id;
document.getElementById('emailfb').value=response.email;
});
}
function checkLogoutState(){
FB.logout(function(response) {
FB.Auth.setAuthResponse(null, 'unknown');
});
};
function checkData()
{
return $.ajax({
})
}
</script>
I am using Spring MVC approach fully JAVA based not using any xml files.
I have searched lot but didn't get any solution
In "if (response.status === 'connected') {}" block you need to call another API of Facebook to fetch the user's details by passing user id and token and after receiving the data you can call your own controller through Ajax and save into DB if required.
Another solution can be, you may use "http://projects.spring.io/spring-social/" on server side itself.
Krish

Parse Local Datastore: I can't access ACL secured objects from the network after force closing the app? (Android)

After a successful login I'm calling:
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.isAuthenticated()
Now if I switch to another app via the home button or multitasking and return to my app the currentUser is still authenticated.
But if I force close the app and then reopen it the currentUser is not authenticated. Therefore it seems that I can't access any objects from the network which have the default Access Control List (ACL) added to them via:
Parse.enableLocalDatastore(this);
ParseACL.setDefaultACL(new ParseACL(), true);
Update with sample code:
// Pinning
ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");
gameScore.put("cheatMode", false);
gameScore.pinInBackground("NEW_GAMESCORES", null);
// Syncing Local Changes
ParseQuery<ParseObject> localQueryNewScores = ParseQuery
.getQuery("GameScore");
localQueryNewScores.fromPin("NEW_GAMESCORES");
localQueryNewScores.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scores, ParseException e) {
Log.d("score", "New scores = " + scores.size());
for (ParseObject score : scores) {
score.saveInBackground();
score.unpinInBackground("NEW_GAMESCORES", null);
score.pinInBackground("GAMESCORES", null);
}
}
});
// Syncing Network Changes
ParseQuery<ParseObject> networkQueryScores = ParseQuery
.getQuery("GameScore");
// Query for new results from the network.
networkQueryScores.findInBackground(new FindCallback<ParseObject>() {
public void done(final List<ParseObject> scores, ParseException e) {
Log.d("score", "Network scores = " + scores.size());
// Remove the previously cached results.
ParseObject.unpinAllInBackground("GAMESCORES",
new DeleteCallback() {
public void done(ParseException e) {
// Cache the new results.
ParseObject.pinAllInBackground("GAMESCORES",
scores);
}
});
}
});
// Querying the Local Datastore
ParseQuery<ParseObject> localQueryScores = ParseQuery
.getQuery("GameScore");
localQueryScores.fromPin("GAMESCORES");
localQueryScores.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scores, ParseException e) {
Log.d("score", "Local scores = " + scores.size());
}
});
Log output just after I've ran the code several times:
New scores = 2
Local scores = 0
Network scores = 0
New scores = 0
Local scores = 0
Network scores = 2
New scores = 2
Local scores = 2
Network scores = 2
New scores = 1
Local scores = 2
Network scores = 4
Log output just after I've force closed the app:
New scores = 0
Local scores = 4
Network scores = 0
New scores = 2
Local scores = 0
Network scores = 0
As you can see at Network scores = 0 after the force close I am unable to query any results from the network where I // Query for new results from the network to update the pinned objects in the Local Datastore with new results from the network. This happens even though I am constantly connected to the internet after the first login.
But as I need to sync back changes from the network to the Local Datastore I'm depending on this query.
So how can I still query the network for objects that are stored with ACL added to the currentUser, after I force close the app?
Update 2
I found others with the same problem which has been reported here:
developers.facebook.com/bugs/702967266408226
It seems to be a bug in the new Parse Android SDK 1.5. I will update this post as soon as it's clear that my problem was related to the reported bug.
Maybe save password to file, and if u reopen app after force close, log in with this saved password ?
You could save the username and password in a SharedPreferences and log in again when the user re opens your app.
I think you could just check to see whether getCurrentUser is null or not instead of using isAuthenticated.
boolean isLoggedIn = ParseUser.getCurrentUser() != null;
isAuthenticated states:
Whether the ParseUser has been authenticated on this device. This will
be true if the ParseUser was obtained via a logIn or signUp method.
Only an authenticated ParseUser can be saved (with altered attributes)
and deleted.
getCurrentUser is always the user that has signed up or logged in. So if it is not null, the user is logged in. isAuthenticated is just to see if the user object was retrieved from a login/sign up or not. For example, if you queried for other ParseUser objects, they would not be authenticated.
Also notice that when you do a logOut on the current user, getCurrentUser will be null.
I also noticed that if you were not using the Local Datastore, currentUser.isAuthenticated() would always return true even when force closing the application.
It seems that when you are using the Local Datastore, where the current user is retrieved locally, the object is no longer seen as "authenticated" as in the source is not from a login or sign up.
Parse Android Changelog
v1.5.1 — May 30, 2014
Fixed various bugs with Local Datastore.
The problem was indeed a Local Datastore bug which has been fixed today with the release of the new Parse Android SDK version 1.5.1.

Twitter API Twitter4j getUserID

I am using Twitter4j to get tweets from the user's I'm following. Getting 1000 per time, but I'm a bit stuck on how I would include user ID and username in the out put.
Here is the code I'm using in order to get the tweets:
try {
ResponseList<Status> a = twitter.getHomeTimeline(new Paging(1,1000));
for (Status b: a){
System.out.println(b.getText());
}
}
Does anybody know what I'd have to add in order to output the ID, Username and then the Tweet?
Thanks
Z19
You can get the id and user name using following methods.
User user = b.getUser() --> Return the user associated with the status.
then using user.getId() and user.getName() you can get the id and user name.
try {
ResponseList<Status> a = twitter.getHomeTimeline(new Paging(1,1000));
for (Status b: a){
long userId = b.getUser().getId();// user Id
String userName = b.getUser().getName(); // user name
String tweetText = b.getText(); // tweet
System.out.println(userId+" "+userName+" "+tweetText);
}
}
For more info you can refer following links:
Twitter 4j Status
Twitter 4j User

session servlets and href tag

what I'm trying to do is relative simple
In my webapp there are these two servlets:
(I will write some pseudocode)
servlet A code: :
HttpSession sess = req.getSession();
String str = (String) sess.getAttribute("log");
if(str == null)
{
// send html page with a form
// to enter password and name
// data will be proceessed by servlet B
}
else
{
// send html page with a form
// to enter only a name
//data will be proceessed by servlet B
}
servlet B code: :
HttpSession sess = req.getSession();
String logged = (String) sess.getAttribute("log");
if(logged == null)
{
//check if password correct
if(correct)
{
sess.setAttribute("log","ok");
// print name
// and tell the user
// that next time password
// will not be requested
}
else
{
// print error message
}
}
else
{
// print name
}
for some reason the second time the servlet A is called after that the user filled in password and name correctly
str is null so the if part gets printed.
EDIT:
I discovered that if the user after inserting the password and
being redirected to servletB writes the url of servletA by himself
all goes right , but it odesn't work when the user gets back to the previous
page using a link created by servletA:
A HREF=\"http://localhost:8080/Blog/ServletA\" back
again , any suggestions why this happens?
I believe its not entering in your if(correct) block i.e. correct condition is not getting satisfied. Correct the condition there and make sure, it sets the log attribute in the session. Once a attribute is set into the session, its there until session expires or your remove it.

Categories

Resources