Getting Score of user from Google Play Game Service? - android

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.

Related

Firebase not getting updated

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?

How to pass Stripe token from Android to ParseServer?

Welcome all!
I am currently working to pass a token generated by Stripes API from an Android app to a ParseServer. Below is my code, please be advised that I commented out previous failed attempts to let you know what I have tried and to also spark your imagination. Please note that with trial and error the issue presents to be with saving the data to the server. I have double checked that the class User has write permissions and it has an Object attribute titled token.
// Test the data.
if (userCard.validateCard()) {
Stripe stripe = new Stripe(CardActivity.this, "correct data is here I removed it, for StackOverflow");
stripe.createToken(
userCard,
new TokenCallback() {
public void onSuccess(final Token token) {
// Send token to your server
// Query the users, and get the username.
ParseQuery<ParseObject> query = ParseQuery.getQuery("User");
ParseUser user = ParseUser.getCurrentUser();
String objectId = user.getObjectId();
// Query the current user.
//query.whereEqualTo("objectId", username);
ParseObject object;
try {
object = query.get(objectId);
object.put("token", token);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(CardActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
});
} catch (ParseException e) {
Toast.makeText(CardActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
// Attempt to update... Currently not working.
/*query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null && objects != null) {
for (ParseObject object : objects) {
object.put("token", token);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(CardActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
});
}
} else {
Toast.makeText(CardActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});*/
}
public void onError(Exception error) {
// Show error message
Toast.makeText(CardActivity.this,
error.getMessage(),
Toast.LENGTH_LONG
).show();
}
}
);
} else {
Toast.makeText(CardActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
A few things here:
1) Parse allows you to add/overwrite information to objects from their "shell". This is a ParseObject instance, set to a specified class, assigned an objectId, and then whatever values you want to add/change, and then saved. Any field you did not assign a value to will be ignored, so say you only set field3, field2 and field1 will not be overwritten to nothing.
2) ParseUser user = ParseUser.getCurrentUser() already returns a user object. You don't even need to create a shell from the id, this is a fully functioning parse object. You can then set the value you want and save it!
3) Queries and fetches (and cloud function calls) are asynchronous. This means that the code executes over time on a background thread, and your main thread will go on. So, things that require the results of these methods need to be called within the completion handler. You're doing object = query.get(objectId), but query.get() takes a bit to run so you're probably running through the rest of the code block before object has a proper value.
4) To my knowledge (not an Android developer, but I've used the JS and iOS SDKs) the Parse SDKs have a specific query for the User class that is a bit easier and safer to use than creating a ParseQuery set to the "User" class. Should be something like ParseUser.query()
So, not being an Android developer, I think what you want is more like this:
// Test the data.
if (userCard.validateCard()) {
Stripe stripe = new Stripe(CardActivity.this, "correct data is here I removed it, for StackOverflow");
stripe.createToken(
userCard,
new TokenCallback() {
public void onSuccess(final Token token) {
// Send token to your server
// Query the users, and get the username.
ParseQuery<ParseObject> query = ParseQuery.getQuery("User");
ParseUser user = ParseUser.getCurrentUser();
try {
user.put("token", token);
user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(CardActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}
});
} catch (ParseException e) {
Toast.makeText(CardActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void onError(Exception error) {
// Show error message
Toast.makeText(CardActivity.this,
error.getMessage(),
Toast.LENGTH_LONG
).show();
}
}
);
} else {
Toast.makeText(CardActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}

Quickblox-android join chat group is not working

i have integrated quickblox android SDk in my app and there are more than 500 dialogs group in list and when i try to join any group chat room, I am not getting entered in either of onSuccess() and onError() ,control flow just goes bypassing callback methods by using below code.
qbChatDialog.initForChat(QBChatService.getInstance());
qbChatDialog.addMessageListener(chatMessageListener);
DiscussionHistory discussionHistory = new DiscussionHistory();
discussionHistory.setMaxStanzas(0);
if (!qbChatDialog.isJoined()) {
qbChatDialog.join(discussionHistory, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
if (qbChatDialog != null) {
getMessage(qbChatDialog, false);
}
}
#Override
public void onError(QBResponseException e) {
Log.e("QB Join", e.toString());
Toast.makeText(QBChatActivity.this, "" + e.toString(), Toast.LENGTH_LONG).show();
}
});
} else {
if (qbChatDialog != null) {
getMessage(qbChatDialog, false);
}
}
I think the problem is Group type .
if you want to create a public group which anyone can join then you should create with QBDialogType.PUBLIC_GROUP.
In case of QBDialogType.GROUP participants should be add at the time of creation and only those participants can join the group which were added .
Solution is create your dialog with type QBDialogType.PUBLIC_GROUP if you want it to public .
QBChatDialog qbChatDialog=new QBChatDialog();
qbChatDialog.setType(QBDialogType.PUBLIC_GROUP);// For public group
qbChatDialog.setType(QBDialogType.GROUP);// For private group

Nexmo Verify SDK for Android

I'm using Nexmo Verify SDK to verify the phone number of the user. I am able to get the pin to the given phone number but when i enter the correct pin code and call checkPinCode method i get INVALID_CREDENTIALS error. This is the implementation.
//This is how i collected the phone number
final String phone = phoneNumber.getText().toString();
verifyClient.getVerifiedUser("LK",phone );
//This is how i collected the pin number
final String pin = pinNumberEditText.getText().toString();
verifyClient.checkPinCode(pin);
verifyClient.addVerifyListener(new VerifyClientListener() {
#Override
public void onVerifyInProgress(VerifyClient verifyClient, UserObject user) {
Toast.makeText(MainActivity.this, "Verifying", Toast.LENGTH_LONG).show();
}
#Override
public void onUserVerified(VerifyClient verifyClient, UserObject user) {
Toast.makeText(MainActivity.this, "Successfully Verified", Toast.LENGTH_LONG).show();
}
#Override
public void onError(VerifyClient verifyClient, com.nexmo.sdk.verify.event.VerifyError errorCode, UserObject user) {
Toast.makeText(MainActivity.this, "Error"+errorCode+user.getPhoneNumber(), Toast.LENGTH_LONG).show();
}
#Override
public void onException(IOException exception) {
Toast.makeText(MainActivity.this, "Exception", Toast.LENGTH_LONG).show();
}
});
Help much appreciated.
Thanks in advance

On Network call response data stores successfully but not present while reading. Using SnappyDb for storing the data.

I am making a network call through volley. On Response success I am trying to store data through SnappyDb which shows that it has stored successfully. But while reading any data is not present. But if I have data outside of response than it saves and reads too. Below is my code. I am struggling in this from last 2 days. Your help will be highly appreciated. Thanks
private void makeApiCall(String key) {
if (Utility.isNetworkAvailable(AddCustomerActivity.this)) {
final String finalKey = key;
showProgressDailog("Adding...");
NetworkEb.apiCallAddUser(customerEb, (key != null && !key.contains(":"))? true : false, new OnJsonResponse() {
#Override
public void onSuccess(JSONObject response) {
try {
int serverId = response.getInt("id");
customerEb.setKey(serverId + "");
customerEb.setSync(true);
snappyDbUtil.saveObjectFromKey("customer", DbName.CUSTOMER.name(), customerEb);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String response) {
Utility.showToast("Upload failed! Try Again");
progressDialog.dismiss();
}
});
} else {
if (key == null) {
key = snappyDbUtil.getNewKey(DbName.CUSTOMER.name());
customerEb.setKey(key);
customerEb.setSync(false);
Utility.showToast("Saved locally");
}
snappyDbUtil.saveObjectFromKey(key, DbName.CUSTOMER.name(), customerEb);
}
}
I found a solution for this. You need to save the data in UI thread by calling this
runOnUiThread(new Runnable() {
#Override
public void run() {
itemDataModel.setKey("ITEMS:" + key);
itemDataModel.setSync(true);
snappyDbUtil.saveObjectFromKey(itemDataModel.getKey(), DbName.ITEMS.name(), itemDataModel);
}
});
Here you have to also care for the keys to store with which only saves if we provide a db name as shown in the above code.

Categories

Resources