"PaymentMode": "Cash",
"Amount": 1000,
"PaymentReferenceNumber": "",
},
{
"PaymentMode": "CcAve",
"Amount": 500,
"PaymentReferenceNumber": "",
},
{
"PaymentMode": "cash",
"Amount": 0,
"PaymentReferenceNumber": "IN0001-113",
},
{
"PaymentMode": "Credited",
"Amount": 500,
"PaymentReferenceNumber": "IN0001-114",
}
This is how i get my json response. What i need to do is that, those 'amount' value whose corresponding payment reference number is empty or null needs to be added.This is what i have done
public int getTotalPayments() {
int total = 0;
for(OrderPayment payment : orderPayments) {
if(payment.getPaymentReferencenumber().isEmpty()||payment.getPaymentReferencenumber().equals("NULL")){
total += payment.getAmount();
}
}
return total;
}
But I am getting wrong. Can anyone help
Look at your logic, you say you're getting the sum of:
References that are empty
OR
References that are NOT "NULL"
And most of the stuff is not null.
To answer your question, just remove the !:
if(payment.getPaymentReferencenumber().isEmpty()||payment.getPaymentReferencenumber().equals("NULL")){
Which is
- References that are empty
OR
- References that are "NULL"
Your Condition is wrong . In am assuming you are checking for a blank Reffrence number here.
So it should be as :-
public int getTotalPayments() {
int total = 0;
for(OrderPayment payment : orderPayments) {
if (isEmpty(payment.getPaymentReferencenumber())) {
total += payment.getAmount();
}
}
return total;
}
private boolean isEmpty(String str) {
if (TextUtils.isEmpty(str))
return true;
return str.toLowerCase().equals("null");
}
Related
I am working on a cart system. I am trying to sum of the product price added into the list. When I update the product quantity it gives me following error.
I am using getx for this. But I don't think it is a getx error.
Unable to parse JSON message: The document is empty.
countTotalPrice() async {
totalPrice = 0.0;
for (var i = 0; i < cartProducts.length; i++) {
totalPrice += cartProducts[i]['total'] as double;
}
update();
}
addToCart(int index) async {
Map data = {
"product_name": productsList[index]['english_name'],
"price": productsList[index]['sale_price'],
"qty": 1,
"total": productsList[index]['sale_price'],
};
cartProducts.add(data);
countTotalPrice();
update();
}
updateQuantity(index, count) {
Map data = cartProducts[index];
data['qty'] = count;
data['total'] = double.parse(data['price']) * data['qty'];
countTotalPrice();
update();
}
try this
data['total'] = double.parse(data['price'].toString()) * double.parse(data['qty'].toString())).toString();
I have an Android project where I'm using some data from stored JSON. I'm using it in several places to get the values, but now, I would also need to get the name of the key instead of value. Is it possible somehow? I'm using 'org.json' library to parse the JSON.
My JSON:
{
"cookbook": {
"products": {
"factory1": {
"product": "product1",
"rate": 2,
},
"factory2": {
"product": "product2",
"rate": 14,
"requires": {
"money": 20,
"product3": 3,
"product4": 2
}
}
}
}
As I said, I have not a problem with retrieving the values, but now I have a name of a product in a variable, let's say 'product2' and I need to determine, which factory is producing this product. So I need to get return 'factory2'.
I have tried:
mainCookbookJson = new JSONObject(loadJSONFromAsset(activity, "cookbook.json"));
JSONObject cookbookJson = mainCookbookJson.getJSONObject("cookbook");
JSONObject productsJson = cookbookJson.getJSONObject("products");
for(Iterator<String> iter = productsJson.keys(); iter.hasNext();) {
String key = iter.next();
if (productsJson.getJSONObject(key).getString("product").equals(product)) {
return productsJson.getString(key);
//return productsJson.getJSONObject(key).toString(); // Also tried
}
}
but this is returning the whole object formatted as a String.
Thank you for any suggestions.
Try just returning the key.
for(Iterator<String> iter = productsJson.keys(); iter.hasNext();) {
String key = iter.next();
if (productsJson.getJSONObject(key).getString("product").equals(product)) {
return key;
}
}
I am using .zip operator to combine 2 API calls
What I want
I wanted to get filtered values from 2nd Observable based on some ids from 1st Observable
Eg
1st Observable returns data like (sample data)
"categories": [
{
"category": "1",
"category_name": "Wedding Venues",
"category_photo_url": "http://www.marriager.com/uploads/album/0463373001465466151-0463467001465466151.jpeg",
"category_type_id": "1",
2nd Observable returns data like :
"data": [
{
"cat_id": "1",
"category_name": "Wedding Venues",
"status": "1",
"order_id": "1",
"category_type_id": "1"
},
I wanted to filter my 2nd Observable data to only return values that matches category_type_id from 1st Observable
My Code
Observable obsService = retrofitService.loadService(getSharedPref().getVendorId());
Observable obsCategory = retrofitService.loadCategory();
Observable<ServiceAndCategory> obsCombined = Observable.zip(obsService.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()), obsCategory.observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()), new Func2<ServiceModel, CategoryModel, ServiceAndCategory>() {
#Override
public ServiceAndCategory call(ServiceModel serviceModel, CategoryModel categoryModel) {
return new ServiceAndCategory(serviceModel, categoryModel);
}
});
obsCombined.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io());
obsCombined.subscribe(new Subscriber<ServiceAndCategory>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
if (e instanceof UnknownHostException || e instanceof ConnectException) {
mPresenter.onNetworkError();
} else if (e instanceof SocketTimeoutException) {
mPresenter.onTimeOutError();
} else {
mPresenter.onServerError();
}
}
#Override
public void onNext(ServiceAndCategory model) {
mPresenter.onSuccess(model);
}
});
EDIT
basically I want to apppy the following logic
this.categoryList = combinedModel.categoryModel.getData();
serviceList = combinedModel.serviceModel.getData().getCategories();
for (int i = 0; i < serviceList.size(); i++) {
for (int j = 0; j < categoryList.size(); j++) {
if (!serviceList.get(i).getCategoryTypeId().equals(categoryList.get(j).getCategoryTypeId())) {
categoryList.remove(j);
}
}
}
You can apply this filtering with reactive approach using a map and a list, first collect all categories to a map, and all services to a list, zip them together, and then filter the services list according to categories map:
Observable<HashMap<Integer, CategoryData>> categoriesMapObservable =
obsCategory
.flatMapIterable(CategoryModel::getData)
.reduce(new HashMap<>(),
(map, categoryData) -> {
map.put(categoryData.getCategoryTypeId(), categoryData);
return map;
}
);
Observable<List<ServiceData>> serviceListObservable = obsService
.map(ServiceModel::getData);
Observable obsCombined =
Observable.zip(
categoriesMapObservable
.subscribeOn(Schedulers.io()),
serviceListObservable
.subscribeOn(Schedulers.io()),
Pair::new
)
.flatMap(hashMapListPair -> {
HashMap<Integer, CategoryData> categoriesMap = hashMapListPair.first;
return Observable.from(hashMapListPair.second)
.filter(serviceData -> categoriesMap.containsKey(serviceData.getCategoryTypeId()))
.toList();
}, (hashMapListPair, serviceDataList) -> new Pair<>(hashMapListPair.first.values(), serviceDataList));
the output result depends on you , here I apply at the end a selector of flatMap() that will create a Pair of Collection of CategoryData and a filtered list of ServiceData, you can of course create whatever custom Object you need for that.
I'm not sure you're gaining much from this, it's seems more efficient from complexity perspective, assuming HashMap is O(1), where categories are N, and services are M, you have here N + M (N constructing the map, M iterating the list and querying the map), while your naive implementation will be N x M.
as for code complexity, i'm not sure it worth it, you can apply your logic at the end of the zip for filtering, or use some library that might be doing filter more efficiently.
P.S the observerOn(AndroidSchedulers.mainThread() is unnecessary so I removed it.
I want to order my posts in the FirebaseRecyclerView by the String Votes. It contains a number as a String. If I write orderbychild("Votes") it shows up the smallest number first.
How can I turn that around? Cheers!
You don't necessarily turn it around.
Let's say your data looks like this:
{
"polls": {
"id1": { "name": "lorem", "votes": 4 }
"id2": { "name": "ipsum", "votes": 3 }
"id3": { "name": "dolor", "votes": 5 }
"id4": { "name": "sit", "votes": 2 }
"id5": { "name": "amot", "votes": 6 }
}
}
If for instance you need the top 4 you would do this:
.orderByChild("Votes").limitToFirst(4)
Would return:
{
"id4": { "name": "sit", "votes": 2 }
"id2": { "name": "ipsum", "votes": 3 }
"id1": { "name": "lorem", "votes": 4 }
"id3": { "name": "dolor", "votes": 5 }
}
If you want the other end, you would do this instead:
.orderByChild("Votes").limitToLast(4)
And the return would be:
{
"id2": { "name": "ipsum", "votes": 3 }
"id1": { "name": "lorem", "votes": 4 }
"id3": { "name": "dolor", "votes": 5 }
"id5": { "name": "amot", "votes": 6 }
}
If you need all of them, just order in the ui.
A quick and rather flexible way to do this on server side is to add an extra field and index your data both with Votes and negativeVotes, where negativeVotes=-Votes
Then for reverse order you do this:
orderbychild("negativeVotes")
And for regular order you do this:
orderbychild("Votes")
A way that I think better is ordering in client-side using reverse().
mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
the code below is how I fixed the issue. it uses an 3 integers - a max value the max value is equal to what ever you want with in the bounds of the datatype restrictions.
int round = 5;
int roundKills = 1000;
int points = 500;
round = round-99999;
roundKills = roundKills-999999;
points = points-99999999;
String oundkills = Integer.toString(roundKills);
String oints = Integer.toString(points);
String ound = Integer.toString(round);
LeaderBoardInput leaderBoardInput = new
LeaderBoardInput(user,"SM",oundkills,oints,ound);
the LeaderboardInput class is just getters and setters for values that are being passed to the database
reference.child(user+System.currentTimeMillis()).setValue(leaderBoardInput);
when you pull the value, you would do something like the following:
round = round+99999;
roundKills = roundKills+999999;
points = points+99999999;
for your example if you have 5 votes and a max vote of 9,999,999
the code would look like this
int votes = 5;
long invertVotes = votes - 9999999;
String dbVotes = Integer.toString(invertVotes);
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("scores");
reference.child("Votes"+System.currentTimeMillis()).setValue(dbVotes);
Query reference = FirebaseDatabase.getInstance()
.getReference().child("Votes").orderByChild("Votes");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//parse data to recycler view adapter and call //notifyDatasetChange()
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
for (DataSnapshot child : children) {
Votes voteValues = child.getValue(voteinput.class);
int value = votevalues.getvotes()+9999999;
scores.add(new Votes( value));
}
getdb = false;
}
});
with Votes be a getter setter class and the scores variable being a list of the Votes class instances
this will order votes 9999994 in db but print 5 to list
out put of multiple values will 5 4 3 2 1 instead of 1 2 3 4 5
I would like to add just one more thing to #Ari approch.
private Query getQuery() {
Query query;
if(last_value == -1) {
query = getPostViewCountRef()
.orderByChild("negativeViewsCount")
.limitToFirst(ITEMS_PER_PAGE);
}else {
query = getPostViewCountRef()
.orderByChild("negativeViewsCount")
.startAfter(last_value)
.limitToFirst(ITEMS_PER_PAGE);
}
return query;
}
as you can see we limitToFist instead of limitTolast
I have this bit of code that show me the text from the json file, but I would like to check the text if there's a specific word in it.
Here's my code :
if (currentLocation.distanceTo(myModel.getNearest()) < 500) {
if (said != true) {
String seriousWarning = (myModel.getNearest().getProvider());
tts.speak(seriousWarning, TextToSpeech.QUEUE_ADD, null);
said = true;
}
the myModel.getNearest()) is here :
public Location getNearest(){
nearest = cameras.get(0);
return nearest;
}
and JSON file :
{
"lng":0.18077 ,
"lat": 43.00854 ,
"name":"Orange Store",
"tribe":"1",
"id":"1",
"verified":"1"
},
I've tried this but didn't work :
if (currentLocation.distanceTo(myModel.getNearest()) < 500) {
if (said != true) {
String seriousWarning = (myModel.getNearest().getProvider());
tts.speak(seriousWarning, TextToSpeech.QUEUE_ADD, null);
said = true;
if (seriousWarning.equals("Orange"))
sign.setText("JAckbot");
}
any help is much appreciated.
Simply store text in any String variable like:
String s1 = [your text];
if(s1.contains([specific word]))
{
do something if text contains specific word
}else
{
do something is text do not contain word
}