I have an app which updates a notes object in the Firebase Realtime Database on certain conditions.
This is the common code called when I need to update any note
public final class FirebaseUtils{
public static void updateNote(Context context, Note currentNote) {
Timber.i("Update note called with note %s", currentNote.toString());
if (mAuth.getCurrentUser() == null) {
return;
}
HashMap<String, Object> noteMap = currentNote.getNoteMap();
String noteId = currentNote.getId();
String userId = mAuth.getCurrentUser().getUid();
Timber.i("Id is %s", noteId);
mDatabase.getReference(AppConstants.REFERENCE_USERS)
.child(userId)
.child(AppConstants.USER_NOTES)
.child(noteId)
.setValue(noteMap)
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Timber.i("Note updated successfully");
Toast.makeText(context, "Edited note", Toast.LENGTH_SHORT).show();
} else {
Timber.e("Error updating note %s", task.getException().getMessage());
Toast.makeText(context, "Error editing note", Toast.LENGTH_SHORT).show();
}
});
}
}
Cases when note is updated
OnBackPressed in a specific activity
The onBackPressed callback is overriden and the note is updated there.
#Override
public void onBackPressed() {
String title = titleNotesAdd.getText().toString().trim();
String content = edtContent.toHtml().trim();
currentNote.setTitle(title);
currentNote.setContent(content);
if (CURRENT_ACTION.equals(AppConstants.ACTION_ADD_NEW_NOTE)) {
currentNote.setTimestamp(System.currentTimeMillis());
FirebaseUtils.addNoteToUser(this, currentNote.getNoteMap());
} else if (CURRENT_ACTION.equals(AppConstants.ACTION_EDIT_NOTE)) {
FirebaseUtils.updateNote(this, currentNote);
}
super.onBackPressed();
}
It is updated from a function on click of a bottom sheet item
public void setRemainder(){
currentNote.setRemainderSet(true);
currentNote.setRemainderTime(remainder.getTimeInMillis());
Utils.scheduleAlarm(this, currentNote);
FirebaseUtils.updateNote(this, currentNote);
}
When the back button is pressed, the note is getting updated fine in the Firebase Real-time Database. But when the setRemainder method is called, the note is not being updated in the database.
Why is this happening? Did I miss something?
Related
just coding my first app in android studio and doing some stuff with the firebase realtime database. Basically I'm trying to verify if a user has already created a username, and if not the app prompts the user to create one by re-directing them to the settings. This all works good, but the thing is that once the user has set their username and returns back to the main menu they're re-rerouted back to the settings page. I looked into it and the code keeps returning false when trying to get a snapshot of their username but I don't understand why? Thank you in advance!
Here's the code that I think isn't working in the main activity
#Override
protected void onStart() {
super.onStart();
if(currentUser == null){
sendUserToLoginActivity();
}else{
VerifyUserExistence();
}
}
private void VerifyUserExistence() {
String currentUserID = mAuth.getCurrentUser().getUid();
RootRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Boolean Name = snapshot.child("NAME").exists();
if(Name){
Toast.makeText(MainActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
}
else{
sendUserToSettingsActivity();
Toast.makeText(MainActivity.this, Name.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
Here's the update settings code:
private void UpdateSettings() {
String setUserName = userName.getText().toString();
String setStatus = userStatus.getText().toString();
if(TextUtils.isEmpty(setUserName)){
Toast.makeText(this, "Please set your username", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(setStatus)){
Toast.makeText(this, "Please set your status", Toast.LENGTH_SHORT).show();
}
else{
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid",currentUserID);
profileMap.put("NAME",setUserName);
profileMap.put("STATUS",setStatus);
RootRef.child("Users").child(currentUserID).setValue(profileMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
}else{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
Here's the stuff in the JSON file
{
"Users" : {
"B2tdbjK9QXUVOpmH8YZgrHdy7rB2" : {
"NAME" : "cvjjcfh",
"STATUS" : "xvjjjhzx",
"uid" : "B2tdbjK9QXUVOpmH8YZgrHdy7rB2"
},
"X685CimY11Q0HXW1haiHVIQByWW2" : {
"NAME" : "lolinio",
"STATUS" : "bsbsksk",
"uid" : "X685CimY11Q0HXW1haiHVIQByWW2"
}
}
}
BTW the part of the code that always returns false is
snapshot.child("NAME").exists();
I have a Registration form (username, password, phone number) and a submit button. I want to check if this username has been registered before. If it is not then create user with credentials in the form.
DB structure
- users
--- -L3HQjgyXe6iNC0r0Ftr
------ mobile: "+15553334444"
------ password: "yoyo"
------ uid: "-L3HQjgyXe6iNC0r0Ftr"
------ username: "myusername"
When I check against a username that exists, i get the correct Toast. However, if the username being checked does not exist, it does not run the code in the else statement under the Toast. Any suggestions?
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = txtUsername.getText().toString();
final String password = txtPassword.getText().toString();
final String number = txtNumber.getText().toString();
final boolean[] createUser = new boolean[1];
user = SerializableHelper.loadDataFromFile(OnBoardingActivity.this);
if (user != null) {
Log.d(TAG, "User uid: " + user.getUid());
Log.d(TAG, "User username: " + user.getUsername());
Toast.makeText(OnBoardingActivity.this, "You're already Registered!", Toast.LENGTH_SHORT).show();
} else {
Query query = mFBUsers.orderByChild("username").equalTo(username);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getValue(User.class).getUsername().equals(username)) {
Toast.makeText(OnBoardingActivity.this, "username already exists!", Toast.LENGTH_SHORT).show();
} else {
Log.d(TAG, "TELL APP TO CREATE NEW USER");
String tempUid = mFBUsers.push().getKey();
user = new User(tempUid, username, password, number);
// save user data locally before pushing to Firebase
SerializableHelper.saveSerializable(OnBoardingActivity.this, user);
mFBUsers.child(tempUid).setValue(user);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
One vey obvious problem in your code is that you are updating the createUser[0] inside the onDataChange method of ValueEventListener but you are using it outside it.
Do note that ValueEventListener is executed asynchronously. So it will proceed with execution of the remaining code without waiting for onDataChange to be called.
So if you want to wait for the updated value of createUser[0], you should call the entire if block of code from inside the onDataChange
Hope this helps. Let me know if you want me to elaborate further.
OK, I figured out what my problem code was
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getValue(User.class).getUsername().equals(username)) {
Toast.makeText(OnBoardingActivity.this, "username already exists!", Toast.LENGTH_SHORT).show();
return;
}
}
Log.d(TAG, "TELL APP TO CREATE NEW USER");
String tempUid = mFBUsers.push().getKey();
user = new User(tempUid, username, password, number);
// save user data locally before pushing to Firebase
SerializableHelper.saveDataToFile(OnBoardingActivity.this, user);
mFBUsers.child(tempUid).setValue(user);
}
I want to implement sign up with two activities with the help of firebase, first sign up activity contains email mobile and password, and in this activity i want to check whether the entered email ID or mobile is registered or not, if it does not then move the data(i.e. email, mobile no. and password) to next activity where final registration will happen. The two methods which are present in the code i.e. userMobileExists() and userEmailExists() to check the email and mobile. But the problem is these are asynchronous so when I go to next activity then the Toast appear that email is already registered.
I am returning valid, if all the valid are true then it goes to next activity , I debugged it and it returns valid before going inside the method. It is because of asynchronous code, Please suggest something how it can be achieved on the first activity only. Or tell if I should provide the whole code.
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "SignupActivity";
private static final int REQUEST_SIGNUP = 0;
private Firebase mRef = new Firebase("https://abcdef.firebaseio.com/");
private User user;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
boolean valid = true;
String email;
String mobile;
String password;
#Bind(R.id.input_email)
EditText _emailText;
#Bind(R.id.input_mobile)
EditText _mobileText;
#Bind(R.id.input_password)
EditText _passwordText;
#Bind(R.id.btn_next)
Button _signupButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.bind(this);
//For Full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
//Back button initialization
Button backButton = (Button) findViewById(R.id.back_signup);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(view.getContext(), LoginActivity.class);
startActivity(in);
}
});
mAuth = FirebaseAuth.getInstance();
// mRef = Firebase(Config.FIREBASE_URL);
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
}
protected void setUpUser() {
user.setPhoneNumber(_mobileText.getText().toString());
user.setEmail(_emailText.getText().toString());
user.setPassword(_passwordText.getText().toString());
}
//private void
public void signup() {
Log.d(TAG, "Signup");
//showProgressDialog();
if (validate() && userEmailExist() && userMobileExist()) {
onSignupSuccess();
} else {
onSignupFailed();
return;
}
//_signupButton.setEnabled(false);
email = _emailText.getText().toString();
mobile = _mobileText.getText().toString();
password = _passwordText.getText().toString();
// TODO: Implement your own signup logic here.
}
public void onSignupSuccess() {
//_signupButton.setEnabled(true);
Log.d(TAG, "NEXT BUTTTON");
//hideProgressDialog();
Intent in = new Intent(this, SignupActivity2.class);
in.putExtra("Email", _emailText.getText().toString());
in.putExtra("Mobile", _mobileText.getText().toString());
startActivity(in);
/*setResult(RESULT_OK, null);
finish();*/
}
public void onSignupFailed() {
// hideProgressDialog();
Toast.makeText(getBaseContext(), "SignUp failed", Toast.LENGTH_LONG).show();
// _signupButton.setEnabled(true);
}
public boolean validate() {
email = _emailText.getText().toString();
mobile = _mobileText.getText().toString();
password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (mobile.isEmpty() || mobile.length() != 10) {
_mobileText.setError("Enter Valid Mobile Number");
valid = false;
} else {
_mobileText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
public boolean userEmailExist() {
//private Firebase mRef = new Firebase("https://.firebaseio.com/users/");
mRef.child("users").orderByChild("email").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue()== _emailText.getText().toString()) {
Toast.makeText(getBaseContext(), "Email already exist. Please choose a different one", Toast.LENGTH_SHORT).show();
_emailText.setError("Email already exist. Please choose a different one");
valid = false;
} else {
email = _emailText.getText().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return valid;
}
public boolean userMobileExist() {
mRef.child("users").
orderByChild("cellPhone").equalTo(_mobileText.getText().toString()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
_mobileText.setError("Mobile Number already exist");
valid = false;
} else {
mobile = _mobileText.getText().toString();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
return valid;
}
#Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void showProgressDialog(){
if(mProgressDialog == null){
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog(){
if(mProgressDialog != null && mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
}
You need to grasp the concept of callbacks. You cannot return a variable that's assigned asynchronously.
As a quick solution to your problem, start with an interface
public interface OnUserActionListener {
void onExists(Boolean exists);
}
Then, make your methods be void and accept a parameter
public void userEmailExist(final String email, final OnUserActionListener listener) {
mRef.child("users")
.orderByChild("email")
.equalTo(email)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
listener.onExists( dataSnapshot.exists() );
}
...
// no return statement
}
Then, when you call that method, you can pass in the string value you want to search for, and implement your interface.
So replace this synchronous code
validate() && userEmailExist()
With the async version
if (validate()) { // This is synchonous
final String email = _emailText.getText().toString();
final String mobile = _mobileText.getText().toString();
// This is asynchronous
userEmailExist(email, new OnUserActionListener() {
#Override
public void onExists(Boolean exists) {
if (exists) {
Toast.makeText(getBaseContext(), "Email already exist. Please choose a different one", Toast.LENGTH_SHORT).show();
_emailText.setError("Email already exist. Please choose a different one");
onSignupFailed();
} else {
onSignupSuccess();
}
}
});
However you choose to define that interface is up to you
And again, worth repeating, don't assign a field valid within your callbacks. Try your best to implement all logic requiring a value to the callback itself
You can also implement the entire interface on the class, which is what I would recommend in this scenario as a SignUpActivity because you want to listen for user event actions such as success or error
Just an example using the method names you already have
public interface OnUserActionListener {
// Combine the email and phone into one action
void onUserExists(User user, Boolean exists);
void onSignupSuccess(User user);
void onSignupFailed(String reason);
}
public class SignupActivity extends AppCompatActivity
implements OnUserActionListner { // Implement this interface
// Define the needed methods
#Override
public void onUserExists(User user, Boolean exists) {
if (exists) {
onSignupFailed("User " + user + " already exists");
} else {
onSignupSuccess(user);
}
}
#Override
public void onSignupSuccess(User user) {
// Do something
}
#Override
public void onSignupFailed(String reason) {
Toast.makeText(this, reason, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle b) {
...
}
etc. etc.
Then, that other method call simply becomes.
if (validate()) { // This is synchonous
final String email = _emailText.getText().toString();
final String mobile = _mobileText.getText().toString();
// This is asynchronous & you defined the Activity as the interface
userEmailExist(email, SignupActivity.this);
I'm not satisfied with the accepted answer because when I used it in my project it still failed. After trying many thing I write my own code ... and it is working. If you want check whether user is already registered or not you can try the following code.
private void isUserAlreadySignUp(String phone){
firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("authUser");
// after getting reference of child, checked orderbykey so we get if phone is key we can get ref in dataSnapshot...
databaseReference.child( "userPhone" ).orderByKey().equalTo( phone ).addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Boolean isExists = dataSnapshot.exists();
if (isExists)
showToast( "This number is alredy Registerd..!!" );
else
{
// if mobile is not registered you can go ahead...
// You can write your further code here or call methods...
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
showToast("Error :" + databaseError);
wSignUpProgressBar.setVisibility( View.GONE );
}
} );
}
// For Toast msg...
private void showToast(String s){ Toast.makeText( getActivity(), s , Toast.LENGTH_SHORT ).show(); }
To register a users mobile number on the database after authenticating the user, you can call this method.
// Register User on the database --------------------------
private void registerUserOnDatabase( String userPhone){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference userRef = database.getReference("authUser").child("userPhone");
userRef.child( userPhone ).setValue( userPhone );
}
I am using firebase database and need to create unique child node in database to start One to One chat. i am calling FireBaseDatabase.updateChildren(RoomName) to set single room for 2 user.
I am having issue in calling FireBaseDatabase.addListenerForSingleValueEvent(new ValueEventListener()
and under this Listener none of the method calls not even on public void onCancelled(DatabaseError databaseError)
Here is my code
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(view, "Hello I am SnackBar", Snackbar.LENGTH_LONG).setAction("Action", null).show();
Log.d(TAG, "User Session Value " + userSession);
userSession = new UserSession(getActivity(), "Pref_FileName");
Log.d(TAG, "User Session Value After Init " + userSession);
final Map<String, Object> RoomName = new HashMap<>();
RoomTitle = userSession.getPhoneNO() + "-" + UserData.getPhone();
otherUserRoom = UserData.getPhone() + "-" + userSession.getPhoneNO();
Log.d(TAG, "Room Title Should Be " + RoomTitle);
DatabaseReference FireBaseDatabase = FirebaseDatabase.getInstance().getReference();
Log.d(TAG, "Chat room name from Database " + db.toString()); //GETTING THIS VALUE IN LOG
FireBaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(RoomTitle)) {
intent2.putExtra("Get_Other",RoomTitle);
Log.d(TAG,"Room Exists No Need To Create It "+RoomTitle); // THIS LOG NEVER GENERATE
RoomNameFinal=RoomTitle;
}
else if (dataSnapshot.hasChild(otherUserRoom)){
intent2.putExtra("Get_Other",otherUserRoom);
Log.d(TAG,"Room Exists No Need To Create It "+otherUserRoom);// THIS LOG NEVER GENERATE
RoomNameFinal=otherUserRoom;
}
else {
Log.d(TAG,"None Of the above Room exist so Create one with RoomTitle "+RoomName);// THIS LOG NEVER GENERATE
intent2.putExtra("Get_Other",RoomTitle);
RoomName.put(RoomTitle, "");
FireBaseDatabase.updateChildren(RoomName);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG,"On Cancelled Calling "+databaseError.getDetails()); // THIS LOG NEVER GENERATE
Log.d(TAG,"On Cancelled Calling "+databaseError.getMessage()); // THIS LOG NEVER GENERATE
Log.d(TAG,"On Cancelled Calling "+databaseError.toString()); // THIS LOG NEVER GENERATE
}
});
intent2.putExtra("Get_Phone", UserData.getPhone());
intent2.putExtra("Get_Image", UserData.getImage());
intent2.putExtra("Get_Name", UserData.getName());
Log.d(TAG,"Room Name Final "+RoomNameFinal);
startActivity(intent2);
}
});
Edit:Where i am adding child in my Firebase Database
You simply forget to indicate the name of your database reference in the function getReference().
For example, if you want to get the messages objects you need to set the DatabaseReference with something like
DatabaseReference myRef = database.getReference("message");
And the url of my database looks like :
https://myproject.firebaseio.com/message
This url is indicate on the top of the RealTimeDatabase tab in your Firebase dashboard.
Hope this help.
I solved by make some edit in code.I am not sure why this is happened but for some who still stuck at this issue, will get little help from this. Instead of calling FireBaseDatabase.updateChildren(RoomName) from directly in onDataChange i create a method which will be called from onDataChange
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(view, "Hello I am SnackBar", Snackbar.LENGTH_LONG).setAction("Action", null).show();
Log.d(TAG, "User Session Value " + userSession);
userSession = new UserSession(getActivity(), "Pref_File");
RoomName = new HashMap<>();
RoomTitle = userSession.getPhoneNO() + "-" + UserData.getPhone();
otherUserRoom = UserData.getPhone() + "-" + userSession.getPhoneNO();
Log.d(TAG, "Room Title Should Be " + RoomTitle);
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Log.d(TAG, "Chat room name from Database " + db.toString());
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG,"On Data Change Calling "+dataSnapshot);
if (dataSnapshot.hasChild(RoomTitle)) {
Log.d(TAG,"Room Exists No Need To Create It 1"+RoomTitle);
RoomName(RoomTitle,false);
}
else if (dataSnapshot.hasChild(otherUserRoom)){
Log.d(TAG,"Room Exists No Need To Create It 2 "+otherUserRoom);
RoomName(otherUserRoom,false);
}
else {
Log.d(TAG,"None Of the above Room exist so Create one with RoomTitle "+RoomName);
RoomName(RoomTitle,true);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG,"On Cancelled Calling "+databaseError.getDetails());
Log.d(TAG,"On Cancelled Calling "+databaseError.getMessage());
Log.d(TAG,"On Cancelled Calling "+databaseError.toString());
}
});
This method i created to call FireBaseDatabase.updateChildren(RoomName) which is not calling from If Else Statement of my previous code.
public void RoomName (String Name,boolean RoomExist){
if (RoomExist){
Log.d(TAG,"Room Not Exist Creating One in METHOD NAME ROOM NAME "+RoomExist);
RoomName.put(Name, "");
FireBaseDatabase.updateChildren(RoomName);
}
Log.d(TAG,"Method ROOM NAME CALLING Value Of ROOM NAME FINAL "+Name);
intent = new Intent(getActivity(), Chat_Screen.class);
intent.putExtra("Get_Phone", UserData.getPhone());
intent.putExtra("Get_Image", UserData.getImage());
intent.putExtra("Get_Name", UserData.getName());
intent.putExtra("Get_Other",Name);
startActivity(intent);
}
Now my onDataChange call as i want.I hope it will someone who has same kind of issue.
I am new to Android App development. I want to retrieve user's score from Google Play Game service and i am using following code to get the high score but i do not have any knowledge how it returns the value and how to save it.
Games.Leaderboards.loadCurrentPlayerLeaderboardScore(getApiClient(), getString(R.string.highscore), LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC);
Saving it to int or string does not worked.
The complete parameters for loadCurrentPlayerLeaderboardScore is like below
Games.Leaderboards.loadCurrentPlayerLeaderboardScore(getApiClient(),
getString(R.string.word_attack_leaderboard),
LeaderboardVariant.TIME_SPAN_ALL_TIME,
LeaderboardVariant.COLLECTION_PUBLIC).setResultCallback(
new ResultCallback<LoadPlayerScoreResult>() {
#Override
public void onResult(LoadPlayerScoreResult arg0) {
LeaderboardScore c = arg0.getScore();
long score = c.getRawScore();
}
}
R.string.word_attack_leaderboard is leaderboards id which get from google play game service
The method:
loadCurrentPlayerLeaderboardScore (GoogleApiClient apiClient, String leaderboardId, int span, int leaderboardCollection)
returns
PendingResult<Leaderboards.LoadPlayerScoreResult>
Then you must use the getScore() method of the Leaderboards.LoadPlayerScoreResult class to get it.
Please see these links...
The loadCurrentPlayerLeaderboardScore method
The LoadPlayerScoreResult in the PendingResult
EDIT: Here's how you can use it.
Games.Leaderboards.loadCurrentPlayerLeaderboardScore().setResultCallback(new ResultCallback<LoadPlayerScoreResult>() {
#Override
public void onResult(LoadPlayerScoreResult arg0) {
LeaderboardScore c = arg0.getScore();
}
});
This is how you get the score.
4 years later I was having a similar problem with this situation. Some stuff has been deprecated and stuff no longer works. So for those of you who want to know how to do it now, in 2018... check this answer-
First you have to get the LeaderBoardClient with
mLeaderboardsClient = Games.getLeaderboardsClient(MainActivity.this, googleSignInAccount);
Next you can the score
mLeaderboardsClient.loadCurrentPlayerLeaderboardScore(getString(R.string.leaderboard_id), LeaderboardVariant.TIME_SPAN_ALL_TIME, LeaderboardVariant.COLLECTION_PUBLIC)
.addOnSuccessListener(this, new OnSuccessListener<AnnotatedData<LeaderboardScore>>() {
#Override
public void onSuccess(AnnotatedData<LeaderboardScore> leaderboardScoreAnnotatedData) {
long score = 0L;
if (leaderboardScoreAnnotatedData != null) {
if (leaderboardScoreAnnotatedData.get() != null) {
score = leaderboardScoreAnnotatedData.get().getRawScore();
Toast.makeText(MainActivity.this, Long.toString(score), Toast.LENGTH_SHORT).show();
Log.d(TAG, "LeaderBoard: " + Long.toString(score));
} else {
Toast.makeText(MainActivity.this, "no data at .get()", Toast.LENGTH_SHORT).show();
Log.d(TAG, "LeaderBoard: .get() is null");
}
} else {
Toast.makeText(MainActivity.this, "no data...", Toast.LENGTH_SHORT).show();
Log.d(TAG, "LeaderBoard: " + Long.toString(score));
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_SHORT).show();
Log.d(TAG, "LeaderBoard: FAILURE");
}
});
The 3 parameters to .loadCurrentPlayerLeaderboardScore are as follows
ID of the leaderboard to load the score from.
Time span to retrieve data for. Valid values are TIME_SPAN_DAILY, TIME_SPAN_WEEKLY, or TIME_SPAN_ALL_TIME.
The leaderboard collection to retrieve scores for. Valid values are either COLLECTION_PUBLIC or COLLECTION_SOCIAL.