How to retrieve the sum of a column using Parse/Parse Cloud? - android

I've created an Android application that helps my dad with his daily income/outcome management (for business).
I need an option menu item that when clicked, queries the particular Parse Class for the sum of a certain column (of String type, but data is in numbers only). I had done this using SQLite and it was a piece of cake, but this NoSQL system lacks such basic functions.
I understand we have to use Parse Cloud Code to accomplish this, but I'm not sure on the how-tos as there isn't much documentation on how to use Cloud Code.
Respective Code can be shared on request, as I'm not sure of what block to share. Please help, thank you very much :)

How about after receiving a list from ParseQuery just sum all the rows with for each loop? No need for ParseCloud to my taste.
Also, You could already make a column of Number type, not String, but let's go with this:
int sum; //or double or float, whatever needed
done(List<ParseObject> list, ParseException e){
for (ParseObject p : list){
sum += Integer.valueOf(p.getString("yourColumnName"));
}
}
Should work like that.

Related

Flutter-Dart Firebase Get a Summe from Docs

I wanna get a Summe from Firebase with Flutter-Dart, i can with Stream Builder all Datas receiving but i wanna get a Summe-Total from Orders. For Example how much money did i earn for this month ? or How much money i have to Pay to my Owner ? My Firebase Database look like this,
[Firebase Struktur][1]
[1]: https://i.stack.imgur.com/E5zsM.png
I wanna get the Grand Total for all "betrag", i tried this like it , but its coming a null, how can i all Documents as List with choosed Feld with For Loop Grand total Calculating and show in the Text ?
var rechnungider = 0;
firestoreInstance.collection("rechnungen").doc().get().then((value) {
for (int i = value.data()!.length; i > value.data()!.length; i++) {
print(value.data());
rechnungider += int.parse(value.data()!["betrag"]);
}
box.write("rechnunggider", rechnungider.toString());
print("Rechnunggider Yenilendi:${box.read("rechnunggider")}");
//print(value.data.toString());
});
}
I wanna show without Document name, i mean all betrag data from all Documents.Total Value, Summe.
Thanks
Please do not calculate the sum of collections on the frontend. I can't warn you enough!
I would recommend to create a cloud function that saves the sum on another place in your database. It is the recommended approach for getting the sum for a value from a collection.
Let me know if you need an example for the functions to write.

A list in a list?

I have some troubles with a issue in my Android App. Hope someone can help me to solve this.
I have two lists. One list with Skills and one list with employees.
What I want is a list per Skill with all employees who have that skill.
I thought about this:
List SkillsWithEmployees
Skill 1 -> (Employee1, Employee2 and Employee3)
Skill 2 -> (Employee2 and Employee3)
Skill 3 -> (Employee1, Employee4 and Employee5)
Have someone an solution for me how I can do this? Or maybe other ideas to do something like this?
My result have to be that I can ask "I want all employees with Skill 2"
To expand on Kkba's answer, a HashMap is probably your best way of organising your data, if you are grouping subsections of employees by skill. As each skill is unique, it can be used as the key part of the HashMap like so:
HashMap<Skill, Employee> skillMap = new HashMap();
skillMap.put(firstSkill, Arrays.asList(employee1, employee3);
skillMap.put(secondSkill, Arrays.asList(employee2, employee3);
skillMap.put(thirdSkill, Arrays.asList(employee1, employee2, employee4);
And the list of employees using a certain skill can be accessed with:
skillMap.get(firstSkill); // Returns employee1 and employee3
But keep in mind that get() returns null if the key does not exist. You may want to use
skillmap.getOrDefault(emptySkill, Collections.emptyList());
instead to ensure a List is always returned regardless of if the skill exists.
Further reading: Arrays.asList(), HashMap.getOrDefault()
I would approach this in a couple ways. Using a Map<Skill, List<Employee>> is perfectly fine so long as you don't intend to modify your collection. If you do however, then it can quickly become a pain to add new keys and values.
With that in mind, if you want to have a mutable collection type, then I would use some form of MultiMap. The standard Java SDK doesn't include an implementation, but you can find one easily enough online (a proto-implementation is present in the Java Documentation), or supplied via a library (i.e. Guava's Multimap)
Alternatively, create a class that pairs Skills to Employees, and filter a collection of them based on a predicate. For example:
class SkilledEmployee {
private final Skill skill;
private final Employee employee;
SkilledEmployee(Skill skill, Employee employee) {
this.skill = skill;
this.employee = employee;
}
Skill skill() {
return skill;
}
Employee employee() {
return employee;
}
}
// To find employees by skill, using Java 8...
listOfSkilledEmployees.stream()
.filter(se -> se.skill().equals(SKILL_ONE)) //Filter out employees with Skill1
.map(SkilledEmployee::employee)
.forEach(employeeWithSkillOne -> { /*Do something */});
HashMap<String, ArrayList<String>>
"Skill1", ArrayList<"Employee1", "Employee2", "Employee3">
"Skill2", ArrayList<"Employee2", "Employee3">
"Skill3", ArrayList<"Employee1", "Employee4", "Employee5">

How to search in Firestore using multiple fields of documents for android?

I'm using a Firebase Firestore for android to store data. I tried to search data from documents.
My Firestore structure is:
Collection (Products) - Document (Auto Generated ID) - Field (NumberOfPeople,OfferStartDate,OfferEndDate,OfferPrice,Location)
I wrote query for search data on those fields.
CollectionReference collectionOfProducts = db.collection("Products");
collectionOfProducts
.whereEqualTo("Location", location)
.whereGreaterThanOrEqualTo("OfferPrice", offerPrice)
.whereLessThanOrEqualTo("OfferPrice", offerPrice)
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
.get()
I want search result like this: An offer which is between start date and end date, where offer price is greater than equal or less than equal on give price range. This query is not working in android studio.
How to do this in firestore firebase?
According to the official documentation regarding Cloud Firestore queries, please note that there some query limitations:
In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons must all filter on the same field.
So a Query object that contains a call to both methods:
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
Is actually not possible, as "OfferStartDate" and "OfferEndDate" are different properties.
The best solution I can think of is to use only one of these method calls and do the other filtering on the client.
Another possible solution might be to use denormalization and duplicate the data
in certain intervals. In this way, you'll always know the time periods and you'll be able to create the corresponding queries.
To the best of my knowledge, Firestore only lets you use where<Greater/Less>ThanOrEqualTo() and where<Greater/Less>Than() a single field and all other filter operations on other fields can only be whereEqualTo().
Some workarounds for your specific case include -
1) Modifying your query to
collectionOfProducts
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereEqualTo("Location", location)
.get()
And then performing the subsequent filtering on the result in your app code.
Alternately, you can perform your filter on "OfferPrice" and "Location" in your query and the remaining filters can be applied to the query result.
2) You can use firebase functions or other server code to write logic that performs customized filtering and fetch the result that way.
i was having same issue with this, but i found a work around that takes sometime to write.
lets say you want to search for a particular keyword(in this case the value of a field inside a document), and you want firebase to search multiple field instead of just looking for 1 particular field.
this is what you want to do.
const searchTerm = document.createElement('input')
db.collection('collection').where('field1', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === '0'){
db.collection('collection').where('field2', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === 0) {
db.collection......and repeat
}
})
}
})
in summary, the above code is basically telling js to search for the term again with a different field if the result of the previous query is 0. I know this solution might not be able to work if we have a large quantity of fields. But for folks out there that are working with small number fields, this solution might be able to help.
I really do hope firestore one day would allow such feature, but here is the code it worked fine for me.
the problem I have now is to allow search input to be able to search without have me to complete the word. I do currently have an idea how this would be, but just need some time to put together.

output text line by line

I write app for Android such gets data from server in JSON format. Now I get this value in string, but in my application it must look like:
Route:
1)first point
2)secon point
3).....
n) n point
I read that in Android in textView I can do it if string will be with html tags but I think it is not the best variant. After Android I must do it in iPhone now I don't know how to do that there. Send Routes as Array is not good variant too. Can you say what is the best way to decide this problem?
Have a look here you will have to find the good pattern .
Hence you have separated strings just use a list View with an ArrayAdapter.
I am not so good with regex but i think it should like : [1-9][0-9]) [[a-f][0-9]]+
I couldn't comment b/c of rep, sorry. Could you provide an example of returned JSON string. I think JSON format can be parsed with ease.
If this the case you can parse it in a loop (or another way. I'm not that good at it)
String[] parseIt (String JSON){
String[] list=JSON.split("\\d\\)");
String[] rlist=new String[list.length-1];
for(int i=0;i<list.length-1;i++){
rlist[i]=list[i+1].trim();
}
return rlist;
}
This might do trick. But you should edit result. I didn't test yet
Edit: I edited code. It simply return the address now with leading whitespace. You can get rid off them using. String trim() method like;
list[1].trim();
Do it in loop and don't care about first element (index 0).
Edit 2: Now it should work

Android TextViews. Is parametrization possible? Is binding to model possible?

I am new to both Android and Stack Overflow. I have started developing and Android App and I am wondering two things:
1) Is it possible to parametrize a TextView? Lets say I want to render a text message which states something like: "The user age is 38". Lets suppose that the user age is the result of an algorithm. Using some typical i18n framework I would write in my i18n file something like "The user age is {0}". Then at run time I would populate parameters accordingly. I haven't been able to figure out how to do this or similar approach in Android.
2) Let's suppose I have a complex object with many fields. Eg: PersonModel which has id, name, age, country, favorite video game, whatever. If I want to render all this information into a single layout in one of my activities the only way I have found is getting all needed TextViews by id and then populate them one by one through code.
I was wondering if there is some mapping / binding mechanism in which I can execute something like: render(myPerson, myView) and that automatically through reflection each of the model properties get mapped into each of the TextViews.
If someone has ever worked with SpringMVC, Im looking for something similar to their mechanism to map domain objects / models to views (e.g. spring:forms).
Thanks a lot in advanced for your help. Hope this is useful for somebody else =)
bye!
In answer to #1: You want String.format(). It'll let you do something like:
int age = 38;
String ageMessage = "The user age is %d";
myTextView.setText(String.format(ageMessage, age));
The two you'll use the most are %d for numbers and %s for strings. It uses printf format if you know it, if you don't there's a quicky tutorial in the Formatter docs.
For #2 I think you're doing it the best way there is (grab view hooks and fill them in manually). If you come across anything else I'd love to see it.

Categories

Resources