Android Greendao - group and order by - android

I'm using GreenDAO in my project.
I have a chats table which contains all the messages.
I want to group by the chat_id and order the messages in descending order by the timestamp of the message.
so what I'm trying to get is a list that contains the most recent message of each chat the user has.
this is the code I'm using:
Chats.queryBuilder()
.orderDesc(ChatsDAO.Properties.TimeStamp)
.where(ChatsDAO.Properties.UserId.eq(user_id))
.where(new WhereCondition.StringCondition("1 GROUP BY chat_id"))
.list();
but still, the code above gives me a list which contains the first message of each chat, instead of the recent message.
is there any way to make a raw query using greenDAO and select what I want?

You can make a raw query using GreenDAO as follow. Also, check the link
Query<User> query = userDao.queryBuilder().where(
new StringCondition("_ID IN " +
"(SELECT USER_ID FROM USER_MESSAGE WHERE READ_FLAG = 0)")
).build();

Related

Firebase Firestore OR query (Android Studio)

I've been trying to find a query for almost 2 days now
I want to search id (current user id) from the document 4 fields (customer1,customer2,customer3,customer4)
Here is the firestore document picture
tried this query
final Query userQuery = collectionReference
.whereEqualTo("customer1",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer2",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer3",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer4",firebaseAuth.getInstance().getCurrentUser().getUid());
but this only shows up if the current ID is present in all 4. Is there any easier way to do this.
You can do that by using a field that is an array containing the uids you want to test, and then applying array-contains on it. In your case:
In your case:
customer: [customer1, customer2, customer3, customer4]
collectionReference
.where("customer ", "array-contains", firebaseAuth.getInstance().getCurrentUser().getUid())
Firestore does not support logical OR queries among mulitple fields. So, what you're trying to do is not possible with a single query using the database structure you have now. You would have to perform multiple queries and merge the results in the client.
If you want to be able to use a single query, you will have to change your database. One option is to put all the customers into a single array field and use an array-contains query to find a customer in that field.

How to sort groups based upon recent message in firebase?

Goal: show the list of groups based upon the recent message and when a new message comes, update the chat group list.
Firebase Structure:
Left one structure represents user model: Basically under student key, there is a list of the student then its details along with group ids in which he/she participated.
Right one structure represents the group detail model: Under chat_group key, there is a list of groups with details and also recent message timing.
Solution Tried:
Fetch the group id from the student using the onChildAdded method of firebase DB one by one then fetch its group details using the addListenerForSingleValueEvent method, then store in the list and every time sort it using sort method of array list and then call notifyDataSetChanged method of recyclerview adapter.
Problem with this approach: Too time-consuming and as the number of groups increases processing time also increases.
I think the best solution is to add a new key to the group details model for the students signed up , like that
SignedStudents : "student1 , student2 , student3"
Then you will read data from chat_group directly orderedByChild("recent_message_timeStamp") , then you have to filter it locally to get the groups only related to the specific student to add it to your list like that
String students = model.getStudents();
if (students.contains("student1")) addGroupToYourList();

SQLite in Android - How to generate User IDs with date and sequential number per day

I currently have an app where I store user data in a SQLite database, and one of my fields is a User ID. I would like to add an option to auto-generate User IDs in an mmddyyXXX format, where XXX is a sequential number per user that resets every day.
Does anyone know how I would approach this? I looked at some of the other similar questions, but they don't seem to be helpful.
This is not complicated at all. If your'e similar with SQLite in android just take the date and the userId using a SELECT and generate that string yourself.
If the XXX is not the userId just save another table containing 'tokens' for users. every userId would have a 'token'.
Every new day just change the contents of this table.
I believe you could use a TRIGGER that will generate the userid when a row is inserted.
The following may suit :-
CREATE TRIGGER IF NOT EXISTS newuserid AFTER INSERT ON users
BEGIN
UPDATE users SET userid = strftime('%m%d',date('now'))||substr(strftime('%Y',date('now')),3)||
(
SELECT CAST(substr('000',1,3-length(count()+1)) AS TEXT)||CAST((count()+1) AS TEXT)
FROM USERS
WHERE substr(userid,1,6) = strftime('%m%d',date('now'))||substr(strftime('%Y',date('now')),3)
)
WHERE userid IS NULL;
END;
The trigger is named newuserid
userid is the column for the auto-generated id. The above relies upon it being NULL so it cannot be a PRIMARY INDEX.
There is no reliance upon other columns.
Testing
Starting with an empty table :-
Inserting 4 rows using INSERT INTO users VALUES(null,'This is a new user'); results in :-
To check for another date the rows are adjusted from 041018??? to 040918??? as per :-
4 more rows are inserted using INSERT INTO users VALUES(null,'This is a new user');, resulting in :-
Note this answer isn't intended to be fail-safe but rather the basis of the concept for the answer.

Android Back4App(Parse) get data from multiple classes

I am building an Android app using Back4App(Parse) database.
I have two classes Post and Post_likes. I want to fetch all posts listing from Post table with individual post likes from post_likes table in the same query.
In Post table, I have post details like post_id, user_id and other details.
In Post_likes table, I have user_id who liked the particular post corresponding to post_id.
Post table with post details
Post_likes table with Post_id and user_id
Now, I want to get total post likes of corresponding post and users who like the particular post along with post listing.
I want to fetch total likes of particular post and then show in home screen post listing.
So, how to write the query to combine the two tables.
Any help will be deeply appreciated.
To define a Pointer Column in the DB, From the Back4App's dashboard you can click on "Edit" button for one Class and add a new Column. Select the type "Pointer" and select the Class name you want to point to in the combo list.
In your code simple add the pointer in the corresponding field
(Something like:
ParseObject PostLikes aPostLike;
ParseObject Post thepost
aPostLike.put("pointedPost", thepost);
(See documentation for accurate syntax).
When you query List of PostLike you can add a "where clause" directly on the pointer Field "pointedPost".
You can also include the content of the Post while query all PostLikes with the key words "include":
(see doc here :
http://parseplatform.org/docs/android/guide/#relational-queries ) :
ParseQuery<ParseObject> query = ParseQuery.getQuery("PostLikes");
// Include the post data with each comment
query.include("post");

Filter Realtime Database Android

I want to create an application that any user can add an advert (announce) with something that he wants to sell.
This is the structure of the Real-time Database in Firebase:
- advert
- category
- {uid}
- title
- price
- description
- location
I want to let the user to filter the adverts by category, title, and price.
Currently, I can filter the adverts only by title like this:
FirebaseDatabase.getInstance().getReference()
.child("adverts")
.orderByChild("title")
.startAt("tv")
.limitToFirst(20)
I have 3 questions:
How can i add more "and clauses"? Or how should i structure the nodes to filter more values?
How should I sort the values that i receive from the server in ascending order or descending order depending on uid?
Seems that the method startAt("abc") is not fetching only the children that has contains in the title "tv". Am i doing something wrong? How should I fetch only the children that contains the string "tv"?
On firebase, there is no way to add "AND clauses". You must structure your data in a way that matches your filtering needs.
I believe firebase already sorts the data by uid.
If you want to fetch only the children that contains the string "tv", you should use this query:
FirebaseDatabase.getInstance().getReference().child("adverts").orderByChild("title").startAt("tv").endAt("tv").limitToFirst(20);
I suggest that you watch the Firebase Database for SQL Developers Series. It has the answers for the 3 of your questions

Categories

Resources