i do this in my onCreate method:
Parse.enableLocalDatastore(this);
Parse.initialize(this);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("Becky", "is dumb");
testObject.put("SammyHuang", "is smart");
testObject.saveInBackground();
then i have a button does this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("SammyHuang");
query.getInBackground("2wTGHJ230q", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
// object will be your game score
becky = object.getString("Becky");
sammy = object.getString("SammyHuang");
System.out.println(sammy);
}
else {
System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbruh");
// something went wrong
}
}
});
i copy the object id "2wTGHJ230q" from the parse website and tried to get it display in terminal but overtime i run it it prints "bruh", i can't figure what went wrong. thx in advanced.
edit:
i fix the getQuery("SammyHuang") to getQuery("TestObject"), it still prints "bruh".
re edit:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class MainActivity extends AppCompatActivity {
private String sammy;
private String becky;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// [Optional] Power your app with Local Datastore. For more info, go to
// https://parse.com/docs/android/guide#local-datastore
Parse.enableLocalDatastore(this);
Parse.initialize(this);
setContentView(R.layout.activity_main);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("Becky", "is dumb");
testObject.put("SammyHuang", "is smart");
testObject.saveInBackground();
}
public void helloFunc(View view){
final TextView lol = (TextView)findViewById(R.id.moron);
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestObject");
query.getInBackground("u2VE9tIAwA", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
becky = new String(object.getString("Becky"));
sammy = new String(object.getString("SammyHuang"));
} else {
System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbruh");
e.printStackTrace();
System.out.println("bbbbbbbbbbbbbbbbbbbbbbbbruh");
// something went wrong
}
}
});
lol.setText("becky " + becky + "\n" + "sammy " + sammy);
}
}
i don't know why the lol.setText give me null. seems like assign the variable "becky" and "sammy" within the method getinbackground is not working. and also i am confused about how can this method has a parameter that is a object with another method define within it.
You save the object as a TestObject (when you do new ParseObject("TestObject")) so you also need to retrieve it as one by doing ParseQuery.getQuery("TestObject").
I think it would be a good idea for you to check the Parse documentation on saving and retrieving objects.
And in case you run into an error again, make sure to check the message of the ParseError, as it usually contains a great deal of information that can help you find the issue.
Related
I get this java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() error when trying to add a comment to Firebase, I have tried many methods online but none seem to be of help, I have been stuck for days here. This is my data base
I am trying to add all comments inside an individual post when I try that I get the null pointer pathString() error, which I can't seem to figure out the cause.
Below is my code.
public class PostDetailActivity extends AppCompatActivity {
String postId,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the id of the post using intent(The issue seems to be from the postId)
Intent intent = getIntent();
postId = intent.getStringExtra("postId");
private void postComment() {
btnAddComment.setVisibility(View.INVISIBLE);
String comment = editTextComment.getText().toString().trim();
//Validate
if(TextUtils.isEmpty(comment)){
// Nothing was entered
Toast.makeText(PostDetailsActivity.this, "Comment is empty...", Toast.LENGTH_SHORT).show();
btnAddComment.setVisibility(View.VISIBLE);
return;
}
String timeStamp = String.valueOf(System.currentTimeMillis());
// Every individual post would have a child called "comments" that would contain comments of the post
DatabaseReference commentReference = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
HashMap<String, Object> hashMap = new HashMap<>(); //insert info into the hashMap
hashMap.put("commentID", timeStamp);
hashMap.put("comment", comment);
hashMap.put("timestamp", timeStamp);
hashMap.put("userID", firebaseUser.getUid());
hashMap.put("uEmail", firebaseUser.getEmail());
hashMap.put("uName", firebaseUser.getDisplayName());
hashMap.put("userImage", myDP);
//Put the data into the database
commentReference.child(timeStamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
showMessage("Comment added");
editTextComment.setText("");
btnAddComment.setVisibility(View.VISIBLE);
updateCommentCount();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//Failed
showMessage("Failed to add comment : "+ e.getMessage());
}
});
}
}
According to the error message you're passing a null value to the child() method, which is not allowed. In the code you shared, these are the lines that call child():
DatabaseReference commentReference = FirebaseDatabase.getInstance().getReference("Posts").child(postId).child("Comments");
...
commentReference.child(timeStamp).setValue(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
Based on the error message and this code, it seems that either postId or timeStamp is null.
You can most easily detect which one it is by either placing a breakpoint on both lines and running the app in a debugger, or by logging the variables in the line just above where you use them.
Also see:
What is a NullPointerException, and how do I fix it?
I'm trying to make a parse query from my activity. It's working fine, i'm able to retrieve my objects but there are always empty (ie match.user1 always null)
ParseUser user = ParseUser.getCurrentUser();
ParseQuery<Match> query = ParseQuery.getQuery(Match.class);
query.whereEqualTo("user1", user);
query.include("user1");
query.include("user2");
query.findInBackground(new FindCallback<Match>() {
#Override
public void done(List<Match> list, ParseException e) {
if(e == null){
// list[0].user1 = null
}
}
});
In my ApplicationController
ParseObject.registerSubclass(Match.class);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "XXX", "XXX");
What's wrong in my code ?
Thanks
Try get the references object (in your case columns 'user1' and 'user2') as following:
list.get(0).getParseObject('user1')
this give you the reference object then you can access it's values (columns) user the getters methods
I'm meeting a problem in my current app, the app containt following/follower system, when I look to user profil I want to retrieve an information if I'm already following this user or not. this is my code
private class CheckinIfFollowing extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//preexcution
}
#Override
protected Void doInBackground(Void... params) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Follow");
query.whereEqualTo("from", ParseUser.getCurrentUser());
query.whereEqualTo("to", userId);
query.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if(e==null){
Toast.makeText(UserProfil.this, "blue", Toast.LENGTH_SHORT).show();
//btn_follow.setButtonColor(getResources().getColor(R.color.bleu));
}else{
if(e.getCode() == ParseException.OBJECT_NOT_FOUND)
{
Toast.makeText(UserProfil.this, "pink", Toast.LENGTH_SHORT).show();
//btn_follow.setButtonColor(getResources().getColor(R.color.pink));
}
else
{
//unknown error, debug
}
}
}
});
return null;
}
#Override
protected void onPostExecute(Void result) {
// followingButton(AlreadyFollowing);
// btn_follow.setClickable(true);
}
}
I'm executing the AsyncTask but nothing shown in the screen.
Btw the "from" and "to" column of the Follow class in parse.com are pointers to _User.
First of all (that's not directly related to your issue, just an observatino): if you're using <something>InBackground method of a query, you don't have to put it inside an AsyncTask. It's already being executed in the background. In your case, you are basically (simplifying a bit here) executing an async task from an async task.
Although you didn't say what's stored in the userId object, I'm assuming (based on it's name) it's an objectId of a ParseUser object and not a ParseUser object itself. And I believe that's a reason for your issue. This line to be exact:
query.whereEqualTo("to", userId);
You said:
Btw the "from" and "to" column of the Follow class in parse.com are
pointers to _User.
If you're storing Pointer to another ParseObject you should probably be passing this type of an object if you're using this field in a query (and not an objectId - String). So in your case you should be passing an instance of ParseUser instead of its objectId.
You can use createWithoutData method of ParseObject to create an object (with objectId) that you can use for your query.
I have a parse class named "classA". I want to build a query where I want to search for rows in "classA" having certain "objectId". I have written the following code. But it always returns an empty list of ParseObjects. I have tried with separate columns existing in "classA". All the time, empty list returned. Please help.
I have used this query before on another class "classB" inside the same application and that works perfectly. I have also tried, "try-catch" block implementation using "query.find". That also returns empty list. Thanks in advance. Please explain what's wrong.
Need more code snippets, please let me know.
Button btn = (Button) findViewById(R.id.query_btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText objIdET= (EditText) findViewById(R.id.obj_id);
String objId= objIdET.getText().toString();
Log.d("check", objId); // Prints correct value here..
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("classA");
fridgeID.whereEqualTo("objectId", objId);
List<ParseObject> lp = new ArrayList<ParseObject>();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
Log.d("#results", String.valueOf(objects.size()));
}
});
}
}
});
Replace FridgeId with query
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("classA");
query.whereEqualTo("objectId", objId);
List<ParseObject> lp = new ArrayList<ParseObject>();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
Log.d("#results", String.valueOf(objects.size()));
}
});
Use getInBackground() if you have objectId of that row.
ParseQuery<ParseObject> query = ParseQuery.getQuery("classA");
query.getInBackground(objId, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
Log.d("#results", String.valueOf(objects.size()));
} else {
// Handle the error
}
}
}
Call findInBackground() if you don't have objectId and setting some condition. You can also set condition on objectId field like this.
ParseQuery<ParseObject> query = ParseQuery.getQuery("classA");
query.whereEqualTo("objectId", objId);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
Log.d("#results", String.valueOf(objects.size()));
} else {
// Handle the error
}
}
}
You are getting an empty list of Parse objects because there aren't any rows corresponding to the user (which you are logged in with).
Parse.com implements privacy of its data by using a field called ACL. So if user A adds an entry to your table, by default the ACL is set to Read+Write for User A and none for other users. So user B will not be able to find any objects of userA.
To read more : https://parse.com/docs/android/guide#security
If you want to create a mechanism by which only users belonging to a certain group can read+write each other's objects, you can Roles (Parse feature).
https://parse.com/docs/android/guide#roles
Check if you have set the correct keys when you initialize the parse in your application.
If you want to get list of users, and ParseQuery.getQuery doesn't work - try this:
val query: ParseQuery<ParseUser> = ParseUser.getQuery()
query.findInBackground() {...}
So I'm Implementing an app using Parse.com as back end, There is basically 3 class in Parse. The first one User where I have the User's Information, and Gallery where I have images "like Instagram, and Finally Follow Class where I have the relation following and followers.
Now I have an activity where I have to display all the images for the people I'm following only. I couldn't write a correct relational queries to get the correct result.
so this is the code that display all the images in the database not only for the people I'm following.
public class FollowingImages extends ParseQueryAdapter<ParseObject> {
public FollowingImages (Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Gallery");
query.include("createdBy");
return query;
}
});
}
// Customize the layout by overriding getItemView
#Override
public View getItemView(final ParseObject object, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.list_item, null);
}
super.getItemView(object, v, parent);
// retrieving the Images from Parse.com
return v;
}
I don't know where should I apply the relational query in the constructor or inside getItemView.
please any help would be highly appreciated.
You will want to apply constraints to your query.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Gallery");
query.whereEqualTo("createdBy", "theUserId");
query.findInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The find request failed.");
} else {
Log.d("score", "Retrieved the object.");
}
}
});
See the official guide for more details.
You could use the matchesKeyInQuery constraint method.
You can use the matchesKeyInQuery method to get objects where a key matches the value of a key in a set of objects resulting from another query.
(after parse docs)
So in your case (I am writing it by hand) it may be something like:
ParseQuery<Follow> whoDoIFollow = ParseQuery.getQuery("Follow")
.select("From")
.whereEqualTo("To", <user>);
ParseQuery<Gallery> theirImages = ParseQuery.getQuery("Gallery")
.whereMatchesKeyInQuery("createdBy", "From", whoDoIFollow);
If I am correct that should be an optimal way from the point of data transferred as everything happens on the server side and you only get the results(images).
Just replace
public FollowingImages (Context context) {
super(context, new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery<ParseObject> whoDoIFollow = ParseQuery.getQuery("Follow")
.select("From")
.whereEqualTo("To", <user>);
ParseQuery<ParseObject> theirImages = ParseQuery.getQuery("Gallery")
.whereMatchesKeyInQuery("createdBy", "From", whoDoIFollow);
return theirImages;
}
});
}