How to get foreign DatabaseField automatically with query? - android

I'm using ORMLite (v4.48) with my Android app. I have the table "Contact" which can contain multiple "Email" (ForeignCollectionField) and one "Personal" (DatabaseField) object. When I get the Contact object from the database I would like to automatically get (or lazy load) the Personal object which has the same Contact ID.
It already automatically gets the Email objects which I can access. But for some reason the Personal object is always "null" even though there is an entry in the Personal table.
Here are my classes:
#DatabaseTable(tableName = "Contact", daoClass = ContactDao.class)
public class Contact {
#DatabaseField(generatedId = true, columnName = PersistentObject.ID)
int id;
#DatabaseField(index = true)
String contactName;
#ForeignCollectionField(eager = false)
ForeignCollection<Email> emails;
#DatabaseField(foreign = true)
public Personal personal;
public ForeignCollection<Email> getEmails() {
return emails;
}
public void setEmails(ForeignCollection<Email> emails) {
this.emails = emails;
}
public Personal getPersonal() {
return personal;
}
public void setPersonal(Personal personal) {
this.personal = personal;
}
...
}
And
#DatabaseTable(tableName = "Email", daoClass = EmailDao.class)
public class Email {
#DatabaseField(generatedId = true, columnName = PersistentObject.ID)
int id;
#DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = PersistentObject.CONTACT_ID_FIELD_NAME) // contact_id
Contact contact;
#DatabaseField
String emailType;
#DatabaseField(canBeNull = false)
String email;
public Email() {
}
public Email(int id, Contact Contact, String emailType, String email) {
this.id = id;
this.contact = contact;
this.emailType = emailType;
this.email = email;
}
public int getId() {
return id;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
...
}
and
#DatabaseTable(tableName = "Personal", daoClass = PersonalDao.class)
public class Personal {
#DatabaseField(generatedId = true, columnName = PersistentObject.ID)
int id;
#DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = PersistentObject.CONTACT_ID_FIELD_NAME)
Contact contact;
#DatabaseField
int age;
#DatabaseField
int weight; // in grams
#DatabaseField
int height; // in cm
public Personal() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
I'm getting the data from the database like this:
QueryBuilder<Contact, Integer> queryBuilder = mContactDao.queryBuilder();
queryBuilder.orderBy("lastViewed", false);
queryBuilder.limit(limit);
PreparedQuery<Contact> preparedQuery = queryBuilder.prepare();
List<Contact> contactList = mContactDao.query(preparedQuery);
that all works well so far.
Then further down the code I can access the Email objects like this:
ForeignCollection<Email> emails = contact.getEmails();
Iterator<Email> iter = emails.iterator();
while (iter.hasNext()) {
Email iAddress = iter.next();
Log.d(TAG, "EMAIL: " + iAddress.getEmail());
Log.d(TAG, "EMAIL TYPE: " + iAddress.getEmailType());
}
Which also works perfectly. Only if I want to access the Personal object I always get NULL.
Personal personal = contact.getPersonal(); // is always NULL
I can't figure out why that is. Do I manually need to add a JOIN in the query builder? I thought it would also lazily load the data once I access it with getPersonal() like it does with getEmails()?

You did not show how entity instances are created, but i assume Personal is created after Contact has been inserted. If that is a case, then after inserting Personal you should do contact.setPersonal(personal), and contactDao.update(contact) - that way personal_id will be stored in contact row

Related

android - How to invert delete objects in realm? [duplicate]

I can't find any solutions to read contacts from Android and save them in Realm. Anyone done that before?
I know that I will have to use Contacts Provider, but this is all I know. AFAIK, Realm doesn't support Cursor so...what else?
edit:
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Contact realmContact = new Contact();
String filter = "" + ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and "
+ ContactsContract.CommonDataKinds.Phone.TYPE +"="
+ ContactsContract.CommonDataKinds.Phone.TYPE_MAIN;
Cursor phones = getActivity()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, filter, null, null);
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
realmContact.setId(id);
realmContact.setName(name);
realmContact.setNumber(phoneNumber);
realmContact.setIsBeingSaved(true);
realm.insertOrUpdate(realmContact);
}
/** merge mechanism */
realm.where(Contact.class)
.equalTo("isBeingSaved", false)
.findAll()
.deleteAllFromRealm(); // delete all non-saved data
for(Contact contact : realm.where(Contact.class).findAll()) {
realmContact.setIsBeingSaved(false); // reset all save state
}
Contact.class
public class Contact extends RealmObject{
#PrimaryKey
private String id;
#Index
private String name;
#Index
private String number;
#Index
private boolean isBeingSaved;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public boolean getIsBeingSaved() {
return isBeingSaved;
}
public void setIsBeingSaved(boolean beingSaved) {
isBeingSaved = beingSaved;
}
}
Create RealmObject, read the data from content provider, save data to RealmObject, save data in Realm:
// background thread
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmContact realmContact = new RealmContact();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
realmContact.setName(name);
realmContact.setPhoneNumber(phoneNumber);
realm.insertOrUpdate(realmContact);
}
}
});
} finally {
if(realm != null) {
realm.close();
}
}
EDIT: okay, here's a trick to merging data and removing all data that's not in the list you've saving
public class RealmContract extends RealmObject {
#PrimaryKey
private long id;
#Index
private String name;
#Index
private String phoneNumber;
#Index
private boolean isBeingSaved;
//getters, setters
}
Then merge:
// background thread
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmContact realmContact = new RealmContact();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds._ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
realmContact.setId(id);
realmContact.setName(name);
realmContact.setPhoneNumber(phoneNumber);
realmContact.setIsBeingSaved(true);
realm.insertOrUpdate(realmContact);
}
realm.where(RealmContact.class)
.equalTo(RealmContactFields.IS_BEING_SAVED, false) // compile 'dk.ilios:realmfieldnameshelper:1.0.0'
.findAll()
.deleteAllFromRealm(); // delete all non-saved data
for(RealmContact realmContact : realm.where(RealmContact.class).findAll()) { // realm 0.89.0+
realmContact.setIsBeingSaved(false); // reset all save state
}
}
});
} finally {
if(realm != null) {
realm.close();
}
}
EDIT: Refer to OP's other question for reading contact data reliably (because there's something up with the Contact LOOKUP_ID and making sure the IDs are correct): Obtaining contacts from content provider without duplicates or invalid contacts, and save to Realm
You can create a Model Class to store desired data from contact
then using Cursor get data and set data in model class.
Save the cursor data in list of model object.
Then insert all model object in single transaction as per object transaction has overhead and slow our app

how can I add rows to DB on android only when DB is created? (using room)

I have category class:
#Entity(tableName = "Categories",indices = {#Index(value = {"id"},
unique = true)})
public class Category implements Serializable {
public Category(String name,int icon,int color)
{
_name= name;
_icon = icon;
_color = color;
}
#PrimaryKey(autoGenerate = true)
public int id;
#ColumnInfo(name = "name")
public String _name;
#ColumnInfo(name = "icon")
public int _icon;
#ColumnInfo(name = "color")
public int _color;
public String get_name() {return _name;}
public int getColor() {
return _color;
}
public int getIcon() {
return _icon;
}
}
and I would like to create constant rows only when DB is newly created and not each time the application is loading.
what I did till now is:
protected CategorySingletone() {
// Exists only to defeat instantiation.
AppDatabase db = AppDatabase.getAppDatabase(MainActivity.get().getApplicationContext());
if (db.categoryDao().countCategories()==0) {
_categoryList = new ArrayList<>();
_categoryList.add(new Category("Cars", R.drawable.couch, 3));
_categoryList.add(new Category("Tech", R.drawable.phone, 3));
_categoryList.add(new Category("Home", R.drawable.book_1, 3));
_categoryList.add(new Category("Leisure", R.drawable.book_1, 3));
_categoryList.add(new Category("Motors", R.drawable.book_4, 3));
_categoryList.add(new Category("Fashion", R.drawable.book_5, 3));
for (Iterator<Category> i = _categoryList.iterator(); i.hasNext();) {
Category item = i.next();
db.categoryDao().insertAll(item);
}
}
while I am checking if rows exists.
is there a better way?
A more efficient way would be to use the DatabaseUtils queryNumEntries method.
e.g.
if (DatabaseUtils.queryNumEntries(db,"Categories") == 0) {
.......
}

Cursor not working as expected

I'm trying to pass objects from a SQLite database to a fragment, but they're getting nulled somewhere along the way.
The Log.i line in DatabaseHelper outputs as expected, but the Log.i line in CollectionsFragment does not -- it returns the correct number of values, but all of them are null.
I feel like logging collectionsList in DatabaseHelper would be useful, but I'm not sure how to do that with an ArrayList.
Snippet from DatabaseHelper:
public List<Book> getAllCollections(int authorID) {
List<Book> collectionsList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT DISTINCT collection FROM " + BOOKS + " WHERE author_id = '" + authorID + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Book book = new Book();
book.setCollection(cursor.getString(0));
Log.i("stories", cursor.getString(0)); // returns with correct values
collectionsList.add(book);
} while (cursor.moveToNext());
}
return collectionsList;
// not sure how to log collectionsList here
}
Snippet from CollectionsFragment:
// link ListView object with XML ListView
collectionsListView = (ListView) view.findViewById(R.id.collections_list_view);
// create new instance of DatabaseHelper
DatabaseHelper db = new DatabaseHelper(getActivity());
// return view;
// create list of collections through getAllCollections method
List<Book> collectionsList = db.getAllCollections(authorID);
Log.i("testing", collectionsList.toString()); // returns [null, null]
// create new ArrayAdapter
ArrayAdapter<Book> arrayAdapter =
new ArrayAdapter<Book>(getActivity(), android.R.layout.simple_list_item_1, collectionsList);
// link ListView and ArrayAdapter
collectionsListView.setAdapter(arrayAdapter);
Book Class:
public class Book {
int id;
String title;
int author_id;
String collection;
String body;
#Override
public String toString() {
return title;
}
public Book() {
}
public Book(int id, String title, int author_id, String collection, String body) {
this.id = id;
this.title = title;
this.author_id = author_id;
this.collection = collection;
this.body = body;
}
// getters
public int getStoryID() {
return this.id;
}
public String getTitle() {
return this.title;
}
public int getAuthorID() {
return this.author_id;
}
public String getCollection() {
return this.collection;
}
public String getBody() {
return this.body;
}
// setters
public void setStoryID(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthorID(int author_id) {
this.author_id = author_id;
}
public void setCollection(String collection) {
this.collection = collection;
}
public void setBody(String body) {
this.body = body;
}
}

Android how to get clicked itemid from Listview and update another column value on this row

I am making small app. It has 2 listview on MainActivity.
DB is SQLLite and has tree cloumns id(int), person(text), status(text).
Firt listview will be show informations from DB with this query
select * from DB where status=B
And next ListView will show information where status=A.
lv1.status=b | lv2.status=a
Person 1 | Person 2
Person 3 | Person 4
When i click lv2 on item, value of clicked lv2 field 'status' must change to 'b'.
But I can not write right query for db.
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Thanks
Here is my code
lvB = (ListView)findViewById(R.id.lvB);
listClientB();
lvA = (ListView)findViewById(R.id.lvA);
listClientA();
lvA.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User)adapterView.getAdapter().getItem(i);
int id = user.get_id();
if (user.getStatus().contains("A")){
dbHelper.changeUser();
}
Toast.makeText(getApplicationContext(), id + "-NUMBER id", Toast.LENGTH_LONG).show();
Log.d(String.valueOf(user.get_id()), "-NUMBER id");
listClientA();
Log.d(user.getStatus(), "Pressed");
}
});
}
private void listClientA(){
list = dbHelper.allUsersA();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvA.setAdapter(klientStatusAdapter);
lvA.setTextFilterEnabled(true);
}
private void listClientB(){
list = dbHelper.allUsersB();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvB.setAdapter(klientStatusAdapter);
lvB.setTextFilterEnabled(true);
}
Here is from DB
public List<User> allUsersA(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'A'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public List<User> allUsersB(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'B'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Here is adapter
public class ClientStatusAdapter extends BaseAdapter{
LayoutInflater inflater;
Context context;
List<User> wordsList;
DbHelper dbHelper;
public ClientStatusAdapter(Context context1, List<User> wordsList) {
this.context = context1;
this.wordsList = wordsList;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dbHelper = new DbHelper(context);
}
#Override
public int getCount() {
return wordsList.size();
}
#Override
public Object getItem(int i) {
return wordsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.kliyent_status_adapter, null);
}
TextView txtIsmAdapter = (TextView)view.findViewById(R.id.txtIsmAdapter);
TextView txtOvqatAdapter = (TextView)view.findViewById(R.id.txtOvqatAdapter);
final User user = wordsList.get(i);
TextView txtCliyentNames = (TextView)view.findViewById(R.id.txtCliyentNames);
txtCliyentNames.setText(user.getClientName());
TextView txtCliyentOrderedFoood = (TextView)view.findViewById(R.id.txtCliyentOrderedFoood);
txtCliyentOrderedFoood.setText(user.getCleintOrderedFood());
TextView txtStatusAdapter = (TextView)view.findViewById(R.id.txtStatusAdapter);
txtStatusAdapter.setText(user.getStatus());
notifyDataSetChanged();
ImageView imgOn = (ImageView) view.findViewById(R.id.imgOn);
return view;
}
}
Here is entity User
public class User {
private int _id;
private String clientName;
private String cleintOrderedFood;
private String status = "A";
public User() {
}
public User(int _id, String clientName, String cleintOrderedFood) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
}
public User(int _id, String clientName, String cleintOrderedFood, String status) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
this.status = status;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCleintOrderedFood() {
return cleintOrderedFood;
}
public void setCleintOrderedFood(String cleintOrderedFood) {
this.cleintOrderedFood = cleintOrderedFood;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
If you look closely at the SQLiteDatabase.update() method, you will see it is declared as
int update (String table,
ContentValues values,
String whereClause,
String[] whereArgs)
Note the last two parameters. These are how you select which rows to update. For example, you can specify to only update rows with a given id:
public void changeUser(int userId){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
String whereClause = "_id = ?";
String where = new String[] {Integer.toString(userId)};
db.update(TABLE_ORDER, values, whereClause, where);
db.close();
}
Here I am assuming you use the conventional column name _id. Of course, you can change this to suit your needs if you have a different column name.
Note that you will now need to pass a parameter to changeUser(). However, you have not shown how nor where you currently call it, so I am unable to provide any advice how to change this.

How to read contacts in Android using Realm?

I can't find any solutions to read contacts from Android and save them in Realm. Anyone done that before?
I know that I will have to use Contacts Provider, but this is all I know. AFAIK, Realm doesn't support Cursor so...what else?
edit:
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Contact realmContact = new Contact();
String filter = "" + ContactsContract.Contacts.HAS_PHONE_NUMBER + " > 0 and "
+ ContactsContract.CommonDataKinds.Phone.TYPE +"="
+ ContactsContract.CommonDataKinds.Phone.TYPE_MAIN;
Cursor phones = getActivity()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, filter, null, null);
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
realmContact.setId(id);
realmContact.setName(name);
realmContact.setNumber(phoneNumber);
realmContact.setIsBeingSaved(true);
realm.insertOrUpdate(realmContact);
}
/** merge mechanism */
realm.where(Contact.class)
.equalTo("isBeingSaved", false)
.findAll()
.deleteAllFromRealm(); // delete all non-saved data
for(Contact contact : realm.where(Contact.class).findAll()) {
realmContact.setIsBeingSaved(false); // reset all save state
}
Contact.class
public class Contact extends RealmObject{
#PrimaryKey
private String id;
#Index
private String name;
#Index
private String number;
#Index
private boolean isBeingSaved;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public boolean getIsBeingSaved() {
return isBeingSaved;
}
public void setIsBeingSaved(boolean beingSaved) {
isBeingSaved = beingSaved;
}
}
Create RealmObject, read the data from content provider, save data to RealmObject, save data in Realm:
// background thread
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmContact realmContact = new RealmContact();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
realmContact.setName(name);
realmContact.setPhoneNumber(phoneNumber);
realm.insertOrUpdate(realmContact);
}
}
});
} finally {
if(realm != null) {
realm.close();
}
}
EDIT: okay, here's a trick to merging data and removing all data that's not in the list you've saving
public class RealmContract extends RealmObject {
#PrimaryKey
private long id;
#Index
private String name;
#Index
private String phoneNumber;
#Index
private boolean isBeingSaved;
//getters, setters
}
Then merge:
// background thread
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmContact realmContact = new RealmContact();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds._ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
realmContact.setId(id);
realmContact.setName(name);
realmContact.setPhoneNumber(phoneNumber);
realmContact.setIsBeingSaved(true);
realm.insertOrUpdate(realmContact);
}
realm.where(RealmContact.class)
.equalTo(RealmContactFields.IS_BEING_SAVED, false) // compile 'dk.ilios:realmfieldnameshelper:1.0.0'
.findAll()
.deleteAllFromRealm(); // delete all non-saved data
for(RealmContact realmContact : realm.where(RealmContact.class).findAll()) { // realm 0.89.0+
realmContact.setIsBeingSaved(false); // reset all save state
}
}
});
} finally {
if(realm != null) {
realm.close();
}
}
EDIT: Refer to OP's other question for reading contact data reliably (because there's something up with the Contact LOOKUP_ID and making sure the IDs are correct): Obtaining contacts from content provider without duplicates or invalid contacts, and save to Realm
You can create a Model Class to store desired data from contact
then using Cursor get data and set data in model class.
Save the cursor data in list of model object.
Then insert all model object in single transaction as per object transaction has overhead and slow our app

Categories

Resources