It is said that we can retrieve our data if we are having objectId for that particular row, but it is auto generated and we cant insert it while setting data , so how to get data if i am not having object id , or any other means so that i can set objectId on my means.
Code is here as in comment:
ParseObject gameScore = new ParseObject("My Parse File");
String objectId = gameScore.getObjectId();
ObjectId doesnt't exist until a save operation is completed.
ParseObject gameScore = new ParseObject("My Parse File");
To retrieve the object id you need to save the object and register for the save callback.
gameScore.saveInBackground(new SaveCallback <ParseObject>() {
public void done(ParseException e) {
if (e == null) {
// Success!
String objectId = gameScore.getObjectId();
} else {
// Failure!
}
}
});
ObjectId can be retrieved from the original ParseObject(gameScore) once the done save callback is fired.
You can use this for getting current user object id
ParseUser pUser= ParseUser.getCurrentUser();
String objId= pUser.getObjectId();
not sure if this will apply to android , but I was trying to retreive the objectid, but for an entry that is already created. I did something like this and it worked.
ParseObject gameScore = new ParseObject("My Parse File");
var obId = gameScore.id;
Got it from the Javascript docs on Parse.com
The three special values are provided as properties:
var objectId = gameScore.id;
var updatedAt = gameScore.updatedAt;
var createdAt = gameScore.createdAt;
You can't unfortunately use the ObjectId until the object's been saved. I'm having this same problem now. The only solution I can think of, and posted a similar question relating to it here
My solution would be to make a tempId on the object and refer to that locally until it has an actual ObjectId, perhaps using a saveInBackground or saveEventually() callback to set other objects relating to it, to it's newly created ObjectId instead of it's old temp one.. when it's made available
It takes times for your values to be stored in table. Use this to get ObjectId
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
// Saved successfully.
Log.d("main", "User update saved!");
Log.d("main", "ObjectId "+gameScore.getObjectId());
} else {
// The save failed.
Log.d("main", "User update error: " + e);
}
}
});
In case you're handling the thread yourself:
First save:
gameScore.save();
Then you'll be able to access the id:
String parseId = gameScore.getObjectId();
Related
I am trying to delete a document from a collection called "photo" but it doesn't work, there is no OnFailureException message as OnSuccess Toast is shown but the document still remain in the Firestore :(
Structure of the firestore:
This is the codes I use to delete the document:
Photo photo = (Photo) getIntent().getSerializableExtra("photo");
FirebaseFirestore db = FirebaseFirestore.getInstance();
String userId = mAuth.getCurrentUser().getUid();
CollectionReference photoRef = db.collection("main").document(userId).collection("photo");
DocumentReference document = photoRef.document(photo.getId());
String currentDocumentID = document.getId();
photoRef.document(currentDocumentID).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(ViewPhotoActivity.this, "Entry Deleted", Toast.LENGTH_SHORT).show();
startActivity(new Intent(ViewPhotoActivity.this, PhotoActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ViewPhotoActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
I am writing the answer from speculation as there is not enough information as to how you are creating the document.
DocumentReference document = photoRef.document(photo.getId());
In the above line you are creating a reference to a document with photo id. Looking at the document data it seems the photo id is not same as the document id.
Therefore when you create the above reference- you are not referring to the existing document with id="2BMG3..." rather a NEW document with id="jYBPX..."
String currentDocumentID = document.getId();
photoRef.document(currentDocumentID).delete()
How you can fix it depends on how you want to save/create the documents. One way could be to create the documents in photo collection with id= photo id in the first place.
For example, when creating, you could create the document reference as following:
CollectionReference photoRef = db.collection("main")
.document(userId)
.collection("photo")
.document(photo.getId());
And then set the data as:
photoRef.set(photo);
That'd set the data to a document you have created with id=photo id.
These examples can be improved if you show how you're adding documents to photo collection now. If you've been using .colection('photo').add() or .collection.document().set(photo) then the created document would have an auto-generated id different from the photo id.
I am sure there are several ways to do this which includes the answer I received above, the getID method is a little confusing to me as it doesn't work sometimes or give me a null exception, so I changed my code and use a simpler way, which is to create a unique ID for each document when they are being created, then set the document Id with that unique ID so I could retrieve them easily, for this case, I created the ID by combining the title and 6 random digits.
When creating the document, I added a unique ID field for each document:
//set a unique ID for each photo
String randomSixNumbers = getRandomNumberString();
String photoId = (title.toLowerCase() + randomSixNumbers).replace(" ", "").trim();
//set ID to new object
Photo photo = new Photo(photoId, title, photoDescription, filePath, datePhoto);
//add object to firestore and set document ID as the uniqueID instead of the default auto-generated documentID
photoRef.document(photoId).set(photo).addOnSuccessListener(...
delete the document using the unique ID:
photoRef.document(photo.getId()).delete().addOnSuccessListener(...
For now, this process seems okay, though I am not sure if it is a good practice or not? If not, could someone point out the downside/fault of this method?
And I noticed that I have to use intent to get the data passing from last activity to get the object data in current activity.
I want something like
objectid id name lastname pic
hx5w887 1 name1 lastname1 pic1
lops4wus 2 name2 lastname2 pic2
zh7w8sa 3 name3 lastname3 pic3
I don't want to change the objectId, just I want that field and every time I save an object increment in 1. I am searched a lot in google, about this, it is no possible at least you can something with Cloud Parse code, but I do not know how to make this function, I don't know if "Increment" can help me with this, and I do not know how to run the function anyway.
Parse.Cloud.afterSave("counter", function(request) {
var nameId = request.object.get("name").id;
var Name = Parse.Object.extend("Name");
var query = new Parse.Query(Name);
query.get(nameId).then(function(post) {
post.increment("idkey",+1);
post.save();
}, function(error) {
throw "Got an error " + error.code + " : " + error.message;
});
});
I deploy and
call the function in Android
ParseCloud.callFunctionInBackground("counter", new HashMap<String, Object>(), new FunctionCallback<String>() {
// #Override
public void done(String result, ParseException e) {
if (e == null) {
} else {
// handleError();
}
}
});
But nothing happens, what can be the problem? Sorry my bad english.
You can use ParseCloud 'beforeSave' functionality.
You can declare a code which will run before saving a new object of a specific class.
In this code you query for your class items, order it and get the first item (the highest value) then you can the next value (highest +1) to the new saved object.
For more info you can take a look at Parse documentation and in this thread (it is not in java but it is very similar)
EDIT: Since Parse is not longer is now an open source might be that things have changed.
How set objectId with Parse.com with primary key.Can you help me ?
When i create new row, i want setObjectId of row.
final ParseObject parseObject = new ParseObject(ChapsModel.PARSE_OBJECT);
parseObject.put(ChapsModel.PARSE_FIELD_NAME_CHAPS,
chapsModel.get(i)
.getNamChap());
parseObject.put(ChapsModel.PARSE_FIELD_LINK_CHAP,
chapsModel.get(i)
.getLinkChap());
parseObject.put(ChapsModel.PARSE_FILED_TEAM_TRANSLATE,
chapsModel.get(i)
.getTeamTranslate());
parseObject.put(ChapsModel.PARSE_FIELD_OBJECT_MANGA,
ParseObject.createWithoutData(MangaModel.PARSE_OBJECT,
chapsModel.get(i)
.getObjectManga()));
parseObject.saveInBackground(new SaveCallback() {
#Override
public void done(final ParseException e) {
if (e == null) {
Log.e(">>>>>",
"done" + ojectId);
// parseObject.setObjectId(ojectId);
} else {
Log.e(">>>>>",
"else" + e.getMessage());
}
}
});
Log
java.lang.RuntimeException: objectIds cannot be changed in offline mode.
Log:
Sorry my english. thank
It's not possible to set objectId with Parse.com with primary key.
Although parse.com doesn't allow us to set the objectId of a row, you can create a new column named anything you want and you can set that new column to any objectId you want. For example, you can create a new column named myObjectId and set it to a string.
From the parse.com website at https://www.parse.com/docs/js/guide#cloud_code
The Data Browser
The Data Browser is the web UI where you can update and create objects in each of your apps. Here, you can see the raw JSON values that are saved that represents each object in your class.
When using the interface, keep in mind the following:
The objectId, createdAt, updatedAt fields cannot be edited (these are set automatically).
I'm using Parse.com for developing a small application.
In a couple of actives i'm inserting values to a Class, and Immediately after that i'm Retrieving the values inserted from the previous activity, it's showing Error, it seems that it takes some seconds to save before being able to retrieve.
so i'm asking how can I know that the saved has been completed with Parse. is there any callback function which can let me know, so I would be able to retrieve that information
here is the code where i'm saving values
ParseUser user = ParseUser.getCurrentUser();
ParseQuery<ParseObject> query = ParseQuery.getQuery("test");
query.whereEqualTo("user", user.getUsername());
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
} else {
file = new ParseFile("profil.png", image);
file.saveInBackground();
object.put("name", nom.getText().toString());
object.put("Profil",file);
object.saveInBackground();
}
I have found an answer to my question
https://parse.com/docs/android/api/com/parse/SaveCallback.html
thank to Bjorn Kaiser
Hi I was wondering how I can get a ParseUser object from a ParseObject. I need to do this because a ParseQuery returns a List. Here is my code and thank you for the help!
// get the currentUser
currentUser = ParseUser.getCurrentUser();
List<ParseObject> friendsList = currentUser.getList("friendsList");
// search for the person the user wants to add as a friend
List<ParseObject> userResults = new ArrayList<ParseObject>();
ParseQuery otherUserQuery = ParseUser.getQuery();
otherUserQuery.whereEqualTo("username", "jyo2");
try {
userResults = otherUserQuery.find();
} catch (ParseException e1) {
// fail
e1.printStackTrace();
}
// get the friend from the query if there was one and add it to the
// currentUser friends list
if (userResults.size() != 0) {
ParseObject currentObject = userResults.get(0);
friendsList.add(currentObject);
currentUser.put("friendsList", friendsList);
}
// save the update
try {
currentUser.save();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try to view the friends
List<ParseObject> currentFL = currentUser.getList("friendsList");
ParseObject currentPU = currentFL.get(0);
System.out.println("THIS IS SIZE" + currentFL.size());
System.out.println(currentPU.get("name"));
Use the existing "User" class in Parse but subclass it using
#ParseClassName("_User")
public class PUser extends ParseUser {
As per this article. You actually specifically need to refer to the _User "ParseClassName" when subclassing this object. It's super hairy, I was stuck on this for ages because for other classes you only need to "register" the class with Parse using it's literal name as per the Parse Data Browser, which in this case is "User", "Info", "Post" etc, but the User class specifically requires the underscore
Edit Sorry, I should have mentioned, then you simply cast the subclass PUser when you get your returned objects from the query. You may need to change the query to be a User query instead of an object one too.
I know this is an old question, but this wasn't clear for me and there wasn't a complete thread on the issue I had, on SO. Hope this helped.
I don't think you need to "cast" is to ParseUser, a parseuser is a parseobject as well, apart from having some basic pre-defined properties attached to it, which you can anyways query like you'd query any other parseobject