Is it possible to write a cloud code function directly into android studio? If not where could I write one? I can't find it on my parse dashboard
thanks
Cloud code is only written in the express module of your app inside cloud/main.js file, you can create cloud functions there and call them from your android app.
Example:
Parse.Cloud.define("getPosts", function(request, response){
var query = new Parse.Query("Posts");
//TODO: query constraints here
query.equalTo("key",request.params.text);
query.find().then(function(results){
response.success(results);
});
});
and you can call this function from android as below:
public static void getPosts(String text, final onSearch onSearch) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("text", text);
ParseCloud.callFunctionInBackground("getPosts", hashMap, new
FunctionCallback<List<Post>>() {
#Override
public void done(List<Post> object, ParseException e) {
//TODO: use search results...
}
});
}
you can see other cloud functions and parameters in the docs: Cloud Code Guide
Related
If I want to add data with same key name but different values, how can I do it without replacing the existing ones? For example the database looks like this:
database
|______user1
|______sameKey: data1
|______sameKey: data2
if I use: DatabaseRef.child(user1).child("sameKey").setValue(data);, it will overwrite the sameKey with the new data, but I want it to simply be a different record of data. How to achieve that?
if you want to display a different record with the same key, just wrap it up under a push key, which is an alafanumeric random value
mDatabaseRef.child(user1).push().child("sameKey").setValue(data);
Now , if you just want to update the current data and not replace it
you will need to use a map and use updateChildren take a look at this example
Map<String,Object> mapData = new HashMap<>();
mapData.put("sameKey",data);
mDatabaseRef.child(user1).child(sameKey).updateChildren(mapData).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Write was successful!
// ...
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Write failed
// ...
}
});
with this you will only replace data that is updated and not the entire node
take a look at Updating or deleting data here
https://firebase.google.com/docs/database/android/read-and-write?hl=en
Hi to everyone watching this post.
I have my app, and I want to know how to call my Firebase Cloud Functions in it. I've been reading from the Firebase guides but I am really struggling to understand how it works.
I have a function where I want to create parties, and I have some values to be inserted such as address, date, owner, etc.
If anyone who knows about this can help me I would be really grateful, I can provide any more information that you could need. Thanks!
As Frank said, it is better when you ask a question on StackOveflow to include all the code you have already written.
However, from your comment, I understand you are referring to the code snippet that is in the documentation (copied/pasted below), and that you have problems with data.put.
private Task<String> addMessage(String text) {
// Create the arguments to the callable function.
Map<String, Object> data = new HashMap<>();
data.put("text", text);
data.put("push", true);
return mFunctions
.getHttpsCallable("addMessage")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
#Override
public String then(#NonNull Task<HttpsCallableResult> task) throws Exception {
// This continuation runs on either success or failure, but if the task
// has failed then getResult() will throw an Exception which will be
// propagated down.
String result = (String) task.getResult().getData();
return result;
}
});
}
This Java code snippet shows that the data that is passed (sent) to the Callable Cloud Function is contained in an HashMap, named data.
You will find a lot of tutorials on the web on how to use an HashMap, but in a nutshell:
"A Java HashMap is a hash table based implementation of Java’s Map interface. A Map, as you might know, is a collection of key-value pairs. It maps keys to values." Source: https://www.callicoder.com/java-hashmap/
A way to add new key-value pairs to the HashMap is by using the put() method. So this part of the code in the snippet is about adding data to the HashMap that will be sent to the CloudFunction.
And in the Cloud Function you will get this data as follows (as explained in the doc):
exports.addMessage = functions.https.onCall((data, context) => {
// ...
const text = data.text;
const push = data.push;
// ...
});
I'm trying to update a specific field in a document using POJO, as written in the doc. I could use SetOptions.mergeFields(). But it's updating other fields with null instead of keeping the other fields (which excluded from mergeFields) untouched. Is it intended?
Here is my code :
UserModel userModel = new UserModel();
userModel.setStatus(0);
setTask = documentReferenceToUse.set(userModel, SetOptions.mergeFields("status"));
setTask.addOnSuccessListener(new OnSuccessListener<Void>()
{
#Override
public void onSuccess(Void aVoid)
{
if (!emitter.isDisposed())
{
emitter.onComplete();
}
}
}).addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
if (!emitter.isDisposed())
{
emitter.onError(e);
}
}
});
And here is my document structure :
[Solved]
Turned out the issue came from my Firebase wrapper code. So there is no actual problem on the Firebase SDL side.
Edit: After taking another closer look at your code, I found that you need to change this line of code:
setTask = documentReferenceToUse.set(model, SetOptions.mergeFields("status"));
with:
setTask = documentReferenceToUse.set(userModel, SetOptions.mergeFields("status"));
You are passing as the first argument, not the object that you have just created but another one. So, the correct object that must be used is: userModel.
You can also use another approach, by getting that entire object from the database. Having the object, you can use setters to change the value of the fileds beneath it. After you have used the setters, you can use set() method directly on the reference to add the object the database.
documentReferenceToUse.set(userModelFromDatabase);
You can also use a Map in order to make an update:
Map<String, Object> map = new HashMap<>();
map.put("status", 0);
documentReferenceToUse.update(map);
I am using Azure services for android.
I am using syncTable and i am getting data from the service.
But i want to order the coming data .
Anyone knows how to do it?
following is the code :
//fetching data from syncTable
mToDoTable= mClient.getSyncTable("ToDoItem",ToDoItem.class);
i am getting all data on button click like following :
private void initElementsWithListeners() {
btnTableData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toDoDao.getAllDataFromTable(mToDoTable);
}
});
but i want the data coming from the service should be ordered by "fieldName" for the sync table. how should i do that ?
Thanks in advance.
#swanandvaidya, According to the tutorial, you can create a Query for your MobileServiceSyncTable to order data by a specified field, please see the code below.
mToDoTable = mClient.getSyncTable("ToDoItem", ToDoItem.class);
// Offline Sync
final List<ToDoItem> results = refreshItemsFromMobileServiceTableSyncTable();
private List<ToDoItem> refreshItemsFromMobileServiceTableSyncTable() throws ExecutionException, InterruptedException {
//sync the data
sync().get();
Query query = QueryOperations.add()
.orderBy("<fieldName>", QueryOrder.Ascending);
// or using `QueryOrder.Descending`
return mToDoTable.read(query).get();
}
I'm using Google's mobile backend starter for a project and I want to set the key name myself for some of entities instead of using the auto-generated one.
If I were doing this without the backend I could do something like it describes in the datastore documentation which creates an employee entity with the key name "asalieri":
Entity employee = new Entity("Employee", "asalieri");
Here's the code I'm using to create the entity. I've been trying to use the CloudEntity.setId() function. Upc is a string and it doesn't work when I use a hardcoded string either.
CloudEntity avg = new CloudEntity("Aggregate");
avg.setId(upc);
avg.put("averagePrice", sum/count);
insertAverage(avg);
private void insertAverage(CloudEntity avg) {
CloudCallbackHandler<CloudEntity> handler = new CloudCallbackHandler<CloudEntity>() {
#Override
public void onComplete(final CloudEntity result) {
Toast.makeText(AddProduct.this, "Average updated.", Toast.LENGTH_LONG).show();
}
#Override
public void onError(final IOException exception) {
handleEndpointException(exception);
}
};
// execute the insertion with the handler
getCloudBackend().insert(avg, handler);
}
When I run the app everything works fine except that the new entity doesn't have the custom ID that I set.
The only thing I can think of is that setId() isn't supposed to do what I think it does but I've been digging through the code and haven't been able to find another way to do what I want.
Does anyone know why this isn't working?
I'm a Googler on the MBS project. I recreated your issue and first glance shows this as a bug on our side. I'll edit my response with updates.
Would this workaround be ok until we push a fix?
avg.put("samId", upc)