cannnot save the result of parse query in an android variabe - android

I am currently using Parse.com's API for an android application. I want to retreive an array from parse and save it as a list to work with later. but tha problem is when i'm out of the query my list turnes empty. can u help me?
ParseUser currentUser = ParseUser.getCurrentUser();
String userId= currentUser.getObjectId();
final ParseQuery<ParseObject> pQuery = ParseQuery.getQuery("Friendship");
pQuery.whereEqualTo("user", userId);
pQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("friendsList")!=null) {
list11 = p.getList("friendsList");
Toast.makeText(getActivity().getApplicationContext(),
"Posted With Success "+ list11.get(2).toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
});
Toast.makeText(getActivity().getApplicationContext(),
"Posted With Success "+list11.get(1).toString(),
Toast.LENGTH_LONG).show();
the first Toast is working but the second one gives me a NullPointerException.

You can only put second Toast in done method like this:-
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("friendsList")!=null) {
list11 = p.getList("friendsList");
Toast.makeText(getActivity().getApplicationContext(),
"Posted With Success "+ list11.get(2).toString(),
Toast.LENGTH_LONG).show();
Toast.makeText(getActivity().getApplicationContext(),
"Posted With Success "+list11.get(1).toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
Because findInBackground method start a new background thread.when you show second toast then list11 may be empty. Due to this it throws a NullPointerException

Related

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();
}

use specific value from ParseObject to a new query

I'm trying to get the value relatedGuild from ParseObject relationShipObject that has been sent to another method.
My code:
private void getRelation(){
Log.i("Status:", "Retrieving current user...");
//Retrieve the current logged in user
ParseUser currentUser = ParseUser.getCurrentUser();
Log.i("Status:", "Retrieving relationship...");
//Retrieve the relationship object for currentUser
ParseQuery<ParseObject> relationQuery = ParseQuery.getQuery("relation");
query.whereEqualTo("relatedUser", currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> relationShip, ParseException e) {
if (e == null) {
for (ParseObject relationShipObject : relationShip) {
// This does not require a network access.
relationshipObject.get("relatedGuild");
getGuild(relationShipObject);
}
} else {
Log.d("relation", "Error: " + e.getMessage());
}
}
});
}
private void getGuild(ParseObject relationShipObject){
Log.d("relation", "relationShipObject:" + relationShipObject.getString("relatedGuild"));
}
When i call Log.d in method getGuild i get a value equal to null. Am I trying to retrieve the value from row relatedGuild the wrong way? If yes, do you have any solution to the problem?
Update:
When i change from getString to get("relatedGuild").toString(), i get a value that looks like this: com.parse.ParseObject#21u702b7. That means relationShipObjectcontains some kind of value i don't know how to retrieve.
Try this:
private void getRelation(){
Log.i("Status:", "Retrieving current user...");
//Retrieve the current logged in user
ParseUser currentUser = ParseUser.getCurrentUser();
Log.i("Status:", "Retrieving relationship...");
//Retrieve the relationship object for currentUser
ParseQuery<ParseObject> relationQuery = ParseQuery.getQuery("relation");
query.whereEqualTo("relatedUser", currentUser);
query.include("relatedGuild"); // <-THIS INCLUDES THE OBJECT BEHIND THE POINTER
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> relationShip, ParseException e) {
if (e == null) {
for (ParseObject relationShipObject : relationShip) {
// This does not require a network access.
relationshipObject.get("relatedGuild");
getGuild(relationShipObject);
}
} else {
Log.d("relation", "Error: " + e.getMessage());
}
}
});
}
private void getGuild(ParseObject relationShipObject){
Log.d("relation", "relationShipObject:" + relationShipObject.getString("relatedGuild"));
}

Retrieve data from a class in Parse.com

I have a class in Parse.com, as XYZ, and it has columns email, password, phone, age. I have email and password combination and I want to check whether there is such a combination in the class? How do I do this?
I have a class Donate, and I have been given an email(e) and password(pw). Here goes the code:
`ParseQuery<ParseObject> query = ParseQuery.getQuery("donate");
query.whereEqualTo("email", e);
query.whereEqualTo("password", pw);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
Toast.makeText(getApplicationContext(), "Success!!!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Something went wrong!!!", Toast.LENGTH_LONG).show();
}
}
}); `
And this always shows 'success' irrespective of the strings e, and pw.
ParseQuery return ParseException just if there was technical issue calling the server.
else, even though your query doesn't find exactly what you looked for,
it will return an empty list and the 'e' var will be null.
so what you need to do is :
ParseQuery<ParseObject> query = ParseQuery.getQuery("donate");
query.whereEqualTo("email", e);
query.whereEqualTo("password", pw);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
if (list.isEmpty() == false) { // add this
Toast.makeText(getApplicationContext(), "Success!!!", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Worng password!!!", Toast.LENGTH_LONG).show(); // add this
}
} else {
Toast.makeText(getApplicationContext(), "Something went wrong!!!", Toast.LENGTH_LONG).show();
}
}
});

Get a child of a parent using pointer

I am trying to get a child when I have his parent.
I created a child (comment) , a parent (post) and a pointer from the child to the parent-
// Create the post
ParseObject myPost = new ParseObject("Post");
myPost.put("title", "I'm Hungry");
myPost.put("content", "Where should we go for lunch?");
// Create the comment
ParseObject myComment = new ParseObject("Comment");
myComment.put("content", "Let's do Sushirrito.");
// Add a relation between the Post and Comment
myComment.put("parent", myPost);
// This will save both myPost and myComment
myComment.saveInBackground();
My query:
String t="";
ParseObject c;
ParseQuery<ParseObject> query =
ParseQuery.getQuery("Comment");
query.whereEqualTo("parent",myPost );
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list,com.parse.ParseException e) {
if (e == null) {
c= list.get(0);
t= c.getString("content");
Toast.makeText(getApplicationContext(), t , Toast.LENGTH_LONG).show();
} else {
Log.d("NY", "Model.getStudentById Error: " + e.getMessage());
}
}
});
but I did not get the comment.
I tried also to put query.include("parent"); but it did not work.
what should I do??
thanks
The only thing I can figure out is that you might be trying to retrieve the myPost object from another method before it's actually been saved to Parse.
When I copied your code into a test project, I couldn't get it to work. Here's an updated version that does work.
Note: I'm chaining the operations so that I'm sure (well, as sure as I can be... you still need good error/exception handling) that the previous operation completed before performing the next.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(this, "<value>", "<value>");
createPost();
}
private void createPost() {
ParseObject myPost = new ParseObject("Post");
myPost.put("title", "I'm Hungry");
myPost.put("content", "Where should we go for lunch?");
mPost = myPost;
ParseObject myComment = new ParseObject("Comment");
myComment.put("content", "Let's do Sushirrito.");
myComment.put("parent", myPost);
myComment.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Comment");
query.whereEqualTo("parent", mPost);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, com.parse.ParseException e) {
if (e == null) {
ParseObject c = list.get(0);
String t = c.getString("content");
Toast.makeText(getApplicationContext(), t, Toast.LENGTH_LONG).show();
} else {
Log.d("NY", "Model.getStudentById Error: " + e.getMessage());
}
}
});
}
});
}
The code above shows my "Hello World" Activity and then posts a Toast that says "Let's do Sushirrito."

Converting an anonymous user to a regular user and saving

I am writing a Parse Android application which uses anonymous users by enabling automatic user creation. I can successfully signup this user (to convert the anonymous user into a regular user) and after that, logging in. Both calls return successfully. When I then set data on the user object and trying to save the user, I get a stackoverflow in the ParseObject class.
My code looks like this (simplified example code):
user.setUsername("MyUserName");
final String password = new PasswordGenerator().nextSessionId();
user.setPassword(password);
try {
user.signUp();
ParseUser.logInInBackground(verification.getPhoneNumber(), password, new LogInCallback() {
#Override
public void done(final ParseUser parseUser, final ParseException e) {
if (parseUser == null) {
requestListener.onError(e);
} else {
parseUser.put("phone_no", "123");
parseUser.saveInBackground(new SaveCallback() { // This generates a stackoverflow
#Override
public void done(final ParseException e) {
int i = 0;
System.out.println("i = " + i);
}
});
// requestListener.onSuccess(null);
}
}
});
} catch (ParseException e) {
e.printStackTrace();
}
The stack overflow is generated when calling saveInBackground on the ParseUser. The stackoverflow looks like this:
java.lang.StackOverflowError
at com.parse.ParseObject.isDataAvailable(ParseObject.java:3212)
at com.parse.ParseObject.checkGetAccess(ParseObject.java:3284)
at com.parse.ParseObject.getString(ParseObject.java:2867)
at com.parse.ParseUser.getUsername(ParseUser.java:401)
at com.parse.ParseUser.signUpAsync(ParseUser.java:665)
at com.parse.ParseUser.resolveLazinessAsync(ParseUser.java:1397)
at com.parse.ParseUser.saveAsync(ParseUser.java:502)
at com.parse.ParseUser.signUpAsync(ParseUser.java:681)
at com.parse.ParseUser.resolveLazinessAsync(ParseUser.java:1397)
at com.parse.ParseUser.saveAsync(ParseUser.java:502)
at com.parse.ParseUser.signUpAsync(ParseUser.java:681)
The Parse version I use is 1.8.0.
Any ideas?
I found the solution! Turns out you have to save the anonymous user first before converting the user into a registered one. If you save the user first, convert the user into a registered one and then do a saveInBackground, you won't get a stackoverflow. So the full code to convert an anonymous user is:
final String accountUsername = username.getText().toString();
final String accountPassword = password.getText().toString();
final ParseUser user = ParseUser.getCurrentUser();
user.setUsername(accountUsername);
user.setPassword(accountPassword);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(final ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Signup Fail", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} else {
Toast.makeText(MainActivity.this, "Signup success", Toast.LENGTH_SHORT).show();
final ParseUser user = ParseUser.getCurrentUser();
user.put("phone_no", "31743379507");
user.saveInBackground(new SaveCallback() {
#Override
public void done(final ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Save data Fail", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} else {
Toast.makeText(MainActivity.this, "Save data success", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
Please note that the saveInBackground in the SignupCallback is optional. You could also set this data on the user before the signUpInBackground is called and save an extra roundtrip. This is pure for demonstration purposes.
Also, it is assumed the following code is placed in the Application class to allow anonymous users:
ParseUser.enableAutomaticUser();
ParseUser.getCurrentUser().saveInBackground();
Here you see the user is saved as soon it is created.
findViewById(R.id.createUser).setOnClickListener(newView.OnClickListener() {
#Override
public void onClick(final View v) {
final String accountUsername = username.getText().toString();
final String accountPassword = password.getText().toString();
final ParseUser user = ParseUser.getCurrentUser();
user.setUsername(accountUsername);
user.setPassword(accountPassword);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(final ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Signup Fail",
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Signup fail", e);
} else
{ Toast.makeText(MainActivity.this,"Signupsuccess",Toast.LENGTH_SHORT).show();
final ParseUser user = ParseUser.getCurrentUser();
user.put("phone_no", "31612345678");
user.saveInBackground(new SaveCallback() {
#Override
public void done(final ParseException e) {
if (e != null) {
Toast.makeText(MainActivity.this, "Save data Fail", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Signup fail", e);
} else {
Toast.makeText(MainActivity.this, "Save
data success", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
}
})

Categories

Resources