How to find the last element in the realm database - android

In realm we have the option to find the first element in the database using findFirst(). But I want to do the reverse of it. I want to last element based on the some condition which I provide.
To find out the first element in the realm database:
GamesDetail learnGameDetail = realm.where(GamesDetail.class).equalTo("gameType", getResources().getString(R.string.learn_row)).notEqualTo("currentBadge",0).findFirst();
In the above query all the rows will have currentBadge as zero. But the last updated row will have currentBadge with some value. I need to find the last updated row with currentBadge not equal to zero.

Instead of
GamesDetail learnGameDetail = realm.where(GamesDetail.class)
.equalTo("gameType", getResources().getString(R.string.learn_row))
.notEqualTo("currentBadge",0)
.findFirst();
You can do
GamesDetail learnGameDetail = realm.where(GamesDetail.class)
.equalTo("gameType", getResources().getString(R.string.learn_row))
.notEqualTo("currentBadge",0)
.findAll()
.last(null);
Please note that insertion order is not kept after deletion. Using findAllSorted() is generally advised.

Related

Realm Android index of objects

How can I change the order or index of Realm object in the android studio??
I want to change the order of the objects, I cleared the class and tried to insert a new one, Is that the solution. Please help me
Instead of using findAll() method you can use findAllSorted() and you can also give ASCENDING or DESCENDING order.
From Realm documentation:
findAllSorted(java.lang.String[] fieldNames, Sort[] sortOrders)
Finds all objects that fulfill the query conditions and sorted by
specific field names.
Parameters:
fieldNames - an array of field names to sort by.
sortOrders - how to sort the field names.
Returns: a RealmResults containing objects. If no objects match the
condition, a list with zero objects is returned.
I just inserted a column sort_order and updated that each time.
Works perfectly. Thanks

How to query Firebase database and not show values based of a boolean value

I am using FirebaseListAdapter in Android to display a list of Orders based off a certain date:
Query orderQuery = ordersRef.orderByChild("dateCreated").startAt(d1.getTime());
My Orders have a completed boolean property
-KsRHO1sLcVxKtVMec3o
completed: false
dateCreated: 1503713136950
I would like to only show not completed items in my list adapter.
the current query above retrieves all orders.
The issue is I don’t know how to query the database correctly to get this to work.
The only idea I have is in the populateView method of the FirebaseListAdapter to check if(!model.isCompleted()){ } and not fill in the textViews associated with the list item.
What way could I achieve my desired result?
in firebase there is not Multi Select or "Multi Query"
so you can orderByChild creating time Or compeleted
So you have to use the Method You mention in your Question
The only idea I have is in the populateView method of the
FirebaseListAdapter to check
if(!model.isCompleted()){ } and not fill in the textViews associated with the list item.
or you have to edit your database Structure
-completed
-KsRHO1sLcVxKtVMec3o
dateCreated: 1503713136950
and
-Notcompleted
-KsRHO1sLcVxKtVMec3o
dateCreated: 1503713136950
like when it`s completed .. remove it from notcompleted Node and
add it in completed node
You can try to use different references for completed and incomplete orders.
Initially when order is placed it will be in the incomplete state and when your order is updated then move the order with key in the complete reference.
Step 1:
Initially when order is getting placed, store the order in a "incomplete" reference like:
-incomplete:{
-anyRandomKeyGeneratedByFirebase:{
"orderTitle":"My First Order"... your order detail goes here
"orderKey":"anyRandomKeyGeneratedByFirebase"
},
.
.
.
}
Above structure will be for incomplete order.
When you know that your order status is completed then you will have to move order into the complete child reference like:
-complete:{
-anyRandomKeyGeneratedByFirebase:{
"orderTitle":"My First Order"... your order detail goes here
"orderKey":"anyRandomKeyGeneratedByFirebase"
},
.
.
.
}
So in this it will solve your problem. Rather than fetching all orders fetch only completed orders from complete reference.
-orders:{
-incompleteOrders:{
},
-completeOrders:{
}
}

Purpose of findFirst() in Realm - Android

What is the use of findFirst() method in Realm for Android? Also, how to retrieve the last inserted record from a table using Realm?
findFirst() would be used when you only expect one result from your query, or just don't care about the whole list, and only want to sample one record.
If you want the very last element you could try findAll(), get the size of that list, and get the last element.

Android Realm find first N element

How I can select first N element from Realm database.
Now,I use this code to select N elements:
Realm.getDefaultInstance()
.where(MyObject.class)
.findAllSorted("myField", Sort.DESCENDING)
But this select operation is too long. I need to SQL 'LIMIT' operation analog.
You can have a look at this
https://github.com/realm/realm-java/issues/544
seems realm results are lazy loaded so you dun need "limit" when using realm
Simple
int N=10; // whatever value you want
Realm mRealm=Realm.getDefaultInstance();
RealmResults<Example> list= mRealm.where(Example.class).findAll();
list.subList(0,N);
I did that using limit method, You should use latest version classpath "io.realm:realm-gradle-plugin:5.8.0"
RealmResults<YourPOJOClass> realmResults = mRealm.where(YourPOJOClass.class).sort("createdTime").limit(10).findAll();
//here this record will be sorted by ascending order using schema name "createdTime"
//this will return the 10 rows only.
`
Possible duplicate Since I already posted the solution here : Limit Realm results
I figured out the solution to achieve this after so many days using "between" query as found in the official docs https://realm.io/docs/java/latest
If you want to fetch first N elements, Simply pass the count from and to with field name as below
realm.where(clazz).between("count",0,1000).findAll();
Where,
"count" = Field name (i.e variable name in your pojo)
"0" = Range From
"1000" = Range to
For example: The above query will fetch first 0 to 1000 as RealmResults.
Note: The above solution works only if you have some unique id with row count. In my case I manually inserted count value before inserting the values into Realm.

Validate for empty row in Android

I have a table in which 5 rows are there. But I have to feed the value of row in the database in which values are filled. It can be 2nd, 3rd or all. So how would I find out and validate the same. The rows are not generating dynamically. The rows are already in layout with some ids. I know it's weird but requirement is this only. Please suggest me how can I do this.
For that you have some alternative,
I think you should insert default record into the field so that will be easy instead of validating, if you think that is good.
When get the result from the DB just put the single condition
String name = Db.get_name().toString();
if(name!=null)
{
Row_TextView.setText(name);
}
else
{
Row_TextView.setText("-"); // or what ever you want to set
}
- Here is database example
Try it i hope it works for you
What you need is a Cursor to read data from the db
Then loop through the fetched data (if 'getCount()>0' then while(!cursor.isAfterLast))
For each row check if the data is present in specific columns in your db and if not then do insert it in the db

Categories

Resources