I'm a beginner in Realm.
I have a table with 3 columns which named Id, Name, Email,Address.
To get the data of Name column, we use a query like 'SELECT Name from table_name' for SQLite.
If we using Realm in Android, then which method do we have to use for fetching the data of only one column?
I searched alot on Google & documentation but to no avail.
Could anyone help me?
Update:
What I am tried:
RealmResults<User> results = query.findAll();
ArrayList<String> name = new Arraylist();
for(i=0; i<results.size; i++){
name.add(result.get(i).getName();
}
My problem:
results.size() > 10k. So I want to avoid 10k iteration
for(i=0; i<results.size; i++){
}
Look at queries section at the documentation:
All fetches (including queries) are lazy in Realm, and the data is never copied.
This mean, that data of particular column (property) will be fetched when you call getMyProperty() method. Not after call of finadAll() method of RealmQuery object
If we using Realm in Android, then which method do we have to use for fetching the data of only one column?
You can't, because Realm is an object store, it doesn't have concept of "columns".
My problem:
results.size() > 10k. So I want to avoid 10k iteration
for(i = 0; i < results.size(); i++){
}
Solution: don't iterate?
RealmResults<User> results = query.findAll();
//List<String> name = new ArrayList<>();
//for(i = 0; i < results.size(); i++){
// name.add(result.get(i).getName();
//}
return results;
// ...
String name = results.get(position).getName();
Related
How to get multiple documents from a Collection in firebase if we want to filter using not_in operator with a uniqueId list of documents.
I have a arrayList like this:
ArrayList<String> idList = new ArrayList();
idList.addAll(uniqueIdList);
// now idList have more than 500 uniqueId
Query query = db.collection("my_collection")
.whereEqualTo("status", "DONE")
.whereNotIn("uniqueId", idList)
.orderBy("uniqueId", Query.Direction.DESCENDING)
.orderBy("createdOn", Query.Direction.DESCENDING);
/* FIREBASE DOCUMENTATION SAYS
------------------------------
Use the in operator to combine up to 10 equality (==)
clauses on the same field with a logical OR */
If the idList object have more than 10 items. It crashes the android application due to FirestoreException.
So, should we not use where_not_in operator? But I have specific demand of this for the query.
So, if you want to query using where_not_in operator in Firebase then, you have to do some part from client side also. The query has a serious limitation. So here is a solution.
// Assume idList contains the uniqueId of documents that you don't want
// Assume status can be DONE or PENDING
// Assume list_objects is the ArrayList you have to pass to Recycler view or list view in your app
if (idList.size() > 0 && idList.size() <= 10) {
query = db.collection("my_collection")
.whereEqualTo("status", "DONE")
.whereNotIn("uniqueId", idList)
.orderBy("uniqueId", Query.Direction.DESCENDING)
.orderBy("createdOn", Query.Direction.DESCENDING);
// your on success code here
} else {
query = db.collection("my_collection")
.whereEqualTo("status", "DONE")
.orderBy("createdOn", Query.Direction.DESCENDING);
// here we are fetching all data where status is done
query.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
List<Object> list_toRemove = new ArrayList<>();
list_objects = task.getResult().toObjects(ClassName.class);
for (int i = 0; i < list_objects.size(); i++) {
Object item = list_objects.get(i);
if (idList.contains(item.getUniqueId())) {
list_toRemove.add(list_objects.get(i));
}
}
list_objects.removeAll(list_toRemove);
}
}
// remove the data manually here and we are now good. There is no other way for now.
}
So this is a limitation in firebase, but if we look at the advantages of using firebase firestore DB then it's a trade off.
The rule is that if you cannot filter data using query then fetch with applying filters that are possible then again filter using the Collection Framework (if you are using Java). All things are possible in this DB.
How to check if table is empty using parse , I'm having a problem with the code below :
private String[] getMaxDateMessage() throws ParseException {
final String[] msgData = new String[3];
ParseObject ob = null;
String[] userIds = {currentUserId, recipientId};
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseMessage");
query.whereContainedIn("senderId", Arrays.asList(userIds));
query.whereContainedIn("recipientId", Arrays.asList(userIds));
query.orderByDescending("createdAt");
if(query.hasCachedResult())
{
ob = query.getFirst();
if (ob.isDataAvailable()) {
//for (int i = 0; i < 1; i++) {
//createdDate[0] = messageList.get(i).get("createdAt").toString();
msgData[0] = ob.getCreatedAt().toString();
msgData[1] = ob.get("senderId").toString();
msgData[2] = ob.get("recipientId").toString();
// }
}
}
The thing is that the table is empty , so the query should return null , but no exception is been throwed , it just crashes the app .
So how can I check if the table is empty before trying to fetch any data ?
Update : The solution that I have found is to use query.count().
If the count returns a value that is not 0 then the table is not empty .
Using query.count() to determine if the table is empty is not an optimal solution. While this is perfectly fine when actually run against an empty table, using query.count() will almost always result in a sub-optimal query when there's more than one object in the table. The reason for this is quite clear: you only care about the first object matched by this query, yet a query.count() will scan the whole table in order to return the total of objects that match your query.
Therefore, the ideal solution is to simply use query.getFirst() and check if you get any results. You should be able to handle the case where ob is not a ParseObject, e.g. the collection is either empty or no objects match your query.
I have a List<String> ids and I want all the FooRealmObjects that have the ID field included in the ids list.
I could iterate through the ids list and query objects by ID, but I was hoping there is a one-liner for this, like :
realm.where(Foo.class).in("id", ids).findAll();
Any ideas?
Now realm already support the feature you want.
Added in Realm Java 1.2.0. (https://github.com/realm/realm-java/issues/841)
Now you can do exactly what you want:
realm.where(Foo.class).in("id", ids).findAll();
As Jeremy mentioned, querying with a list of parameters is not possible (for now), but his answer does not work at all.
This is the workaround I used:
List<String> ids = ...;
Realm realm = Realm.getInstance(mContext);
RealmQuery<Foo> query = realm.where(Foo.class);
for (int i = 0; i < ids.size() - 1; i++) {
query = query.equalTo("id", ids.get(i)).or();
}
query = query.equalTo("id", ids.get(ids.size() - 1));
RealmResults<Foo> foos = query.findAll();
I don't believe there is a method according to the documentation to query like this. You could do something like the following:
RealmQuery query = realm.where(Foo.class);
for (String id : ids) {
query.equalTo("id", id).or();
}
query.findAll();
Might have to iterate through it using ;;; to remove the last .or() but I'm not sure.
I receive data from a server using JSON and I want to order them alphabetically with alphabet indexed section and store them in a ListView.
Maybe something that will happen in :
for(int i=0;i<jArray.length();i++){
// here
}
I read that you can order elements like that only using a cursor. In my case would be very inefficient to store the elements from the server in the database and read them again. Waste of time and memory.
So, I am asking you if there could be any solution for my problem : order alphabetically with alphabet indexed section string received from JSON .
EDIT: I want my listview to look like this http://eshyu.wordpress.com/2010/08/15/cursoradapter-with-alphabet-indexed-section-headers/ . I mean with those sections . All tutorials I found said that you need to fetch information with a cursor. My question was if I could't do this wihout a cursor, because it would be a waste of memory to store them in the local database too.
You may need to parse the JSON Array :
List<Project> list = new ArrayList<Project>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = (JSONObject) jArray.get(i);
project = new Project();
project.setId( Long.parseLong(obj.get("id").toString()));
project.setKey(obj.get("key").toString());
project.setName(obj.get("name").toString());
list.add(project);
}
You can use the comparator class like this to sort them :
Collections.sort(list), new Comparator<Project>() {
public int compare(Project p1, Project p2) {
return p1.getKey().compareToIgnoreCase(p2.getKey());
}
});
You can also have Project class and implements Comparable:
public class Project implements Comparable<Project> {
private long id;
private String key;
private String name;
public int compareTo(Project p) {
if (this.key > p.key)
return -1;
else if (this.key < p.key)
return 1;
return 0;
}
}
And then sort the list by Collections.sort(list);
My suggestion is try to sort the data in the Server-side, because the memory of the phone is limited and it may make you application time consuming to show the data, but you do not have memory limitation problem in the Server-side.
use a comparator to sort the arraylist as described here . And then use an ArrayAdapter to show the items in Listview
I have a extremely minor issue that I can't seem to figure out. I'm trying to extract data based on a type of value from an ArrayList> and place it into another ArrayList. The issue is that the for-loop only runs once, which in this case i need it to traverse the entire array and then place the data into the unSuppressedData arraylist.
Below is the for-loop:
for (int x = 0; x < suppressedStatus.length; x++) {
for (int i = 0; i < availData.size(); i++) {
Hashtable<String,String> checkAvail = availData.get(i);
String itemStatus = checkAvail.get("loanStatus");
if (unSuppressedData.contains(checkAvail) == false) {
if (!(itemStatus.equals(suppressedStatus[x]))) {
Log.d("Item Status", itemStatus);
Log.d("Suppressed Status", suppressedStatus[x]);
unSuppressedData.add(checkAvail);
//break;
}
}
}
}
suppressedStatus is a String array
availData is the arraylist i want to extract data from
unSuppressedData is the arraylist i want to place the data in
I believe that it only runs once is due to this line of code:
if (unSuppressedData.contains(checkAvail) == false) {
But i need to this line to check whether my unSuppressdData has the data, if no then will add the data from availData arraylist into unSuppressedData arraylist.
Could it be that i'm writing this piece of code wrongly? Appreciate any insights shed on this.
A good collection type for this sort of thing is the LinkedHashSet. Because it's a set, each element can only be added once. Being a hash, the contains test is quick. Being 'linked' the resulting set is iterated in insertion order.