I have this function which is called when there is any change in Contacts in Phone, Now the problem here is that this code works fine on HTC Desire 620 (KitKat) but crashes on Moto G (Lollipop) and other devices.
Error : java.lang.IllegalStateException: Illegal State: object is no longer valid to operate on. Was it deleted?
Also: It works fine with Moto G2 if contacts are less like < 500 but if more it crashes!
Logcat details:
E/AndroidRuntime: Process: com.advisualinc.echo:SwitchService, PID: 16972
E/AndroidRuntime: java.lang.IllegalStateException: Illegal State: Object is no longer valid to operate on. Was it deleted by another thread?
E/AndroidRuntime: at io.realm.internal.UncheckedRow.nativeGetString(Native Method)
E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
My service class:
public class ContactsSyncService extends Service {
public static int count = 0;
int k = 0;
Realm realmFresh;
public static boolean contactUpdated = false;
ContentObserver mObserver;
public Context contextService = ContactsSyncService.this;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
k++;
// Toast.makeText(ApplicationController.getInstance(), "Starting Change: " , Toast.LENGTH_SHORT).show();
if (!contactUpdated) {
contactUpdated = true;
Logger.debug("Contact Update to start -->");
// Toast.makeText(ApplicationController.getInstance(), "Changing: " , Toast.LENGTH_SHORT).show();
FetchLocalContacts.refreshingContactsDB(contextService);
// Toast.makeText(ApplicationController.getInstance(), "Changed: " , Toast.LENGTH_SHORT).show();
}
}
};
getContentResolver().registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, mObserver);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
getContentResolver().unregisterContentObserver(mObserver);
}
}
The Function called by Service is refreshingContactsDB():
public static void parseContactstoContactsDB()
{
Thread background = new Thread(new Runnable()
{
public void run()
{
Realm realmFetchFirstTime = Realm.getInstance(ApplicationController.getInstance());
ContentResolver cr = ApplicationController.getInstance()
.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION,null,null, null);
String duplicateName = "";
String duplicatePhone = "";
if( phones.getCount() >0)
{
final int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
String name = phones.getString(nameIndex);
String phoneNo = phones.getString(numberIndex);
if(phoneNo!=null&&!phoneNo.isEmpty())
{
phoneNo = phoneNo.replace(" ", "");
phoneNo = phoneNo.replace("(", "");
phoneNo = phoneNo.replace(")", "");
phoneNo = phoneNo.replace("-", "");
phoneNo = phoneNo.replace("\u00a0", "");
phoneNo = phoneNo.replace("\u202c", "");
phoneNo = phoneNo.replace("\u2011", "");
phoneNo = phoneNo.replace("\u202a", "");
phoneNo = phoneNo.replace("*", "");
phoneNo = phoneNo.replace("#", "");
if (phoneNo.length() >= 5)
{
if(name.equalsIgnoreCase(duplicateName)&&phoneNo.equalsIgnoreCase(duplicatePhone))
{
continue;
}
duplicateName = name;
duplicatePhone = phoneNo;
String formattedPhoneNumber;
formattedPhoneNumber = parseNumber(phoneNo);
realmFetchFirstTime.beginTransaction();
R_LocalContactDB rContacts = realmFetchFirstTime.createObject(R_LocalContactDB.class);
rContacts.setName(name);
rContacts.setPhone(formattedPhoneNumber);
realmFetchFirstTime.commitTransaction();
Logger.debug("Formatted Contacts --> Name: "
+ name
+ " -- Phone No: "
+ formattedPhoneNumber);
}
}
}
phones.close();
}
realmFetchFirstTime.close();
// getNumbersFromDBAndUpdate();
}
});
background.start();
}
public static void getNumbersFromDBAndUpdate()
{
Realm realmServer = Realm.getInstance(ApplicationController.getInstance());
RealmResults<R_LocalContactDB> query = realmServer.where(R_LocalContactDB.class).findAll();
Logger.debug("Contact Update updating to server -->");
for (int i = 0; i < query.size(); i++)
{
phoneNumberJsonArray.put(query.get(i).getPhone());
}
try
{
uploadContactJsonBody.put("phone_numbers", phoneNumberJsonArray);
Logger.debug("LocalContacts RequestJson ---> "
+ uploadContactJsonBody.toString());
AppPreferenceManager.getInstance().setContactPref(1);
UploadLocalContactsToServerAsynTask test = new UploadLocalContactsToServerAsynTask(
uploadContactJsonBody.toString(),
new LocalContactsSyncCallBack()
{
#Override
public void didFinishProfileSync(boolean bool,
String result) {
Logger.debug("Is ContactUpdated FetchContacts --> "
+ bool);
setMatchedStatusToFalse();
AppPreferenceManager.getInstance().setContactUpdate(bool);
Intent roomIntent = new Intent();
roomIntent
.setAction("com.advisualinc.echo.fetch.local_contacts");
ApplicationController.getInstance().sendBroadcast(roomIntent);
}
});
test.execute();
}
catch (JSONException e)
{
e.printStackTrace();
}
realmServer.close();
}
public static void refreshingContactsDB()
{
Thread background = new Thread(new Runnable()
{
public void run()
{
realmFresh = Realm.getInstance(ApplicationController.getInstance());
createCountryDetailsArrayModel();
R_LocalContactDB rCont;
TelephonyManager tm = (TelephonyManager) ApplicationController.getInstance()
.getSystemService(Context.TELEPHONY_SERVICE);
String simCountryISO = tm.getSimCountryIso();
for (int i = 0; i < countryDetailsList.size(); i++)
{
if (simCountryISO.equalsIgnoreCase(countryDetailsList.get(i)
.getCode()))
{
dialCodePrefix = countryDetailsList.get(i).getDial_code();
}
}
AppPreferenceManager.getInstance().setContactUpdate(false);
Logger.debug("Contact Update Refreshing Contact Started -->");
ContentResolver cr = ApplicationController.getInstance()
.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
String duplicateName = "";
String duplicatePhone = "";
if (phones.getCount() > 0)
{
final int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
String name = phones.getString(nameIndex);
String phoneNo = phones.getString(numberIndex);
if (phoneNo != null && !phoneNo.isEmpty())
{
phoneNo = phoneNo.replace(" ", "");
phoneNo = phoneNo.replace("(", "");
phoneNo = phoneNo.replace(")", "");
phoneNo = phoneNo.replace("-", "");
phoneNo = phoneNo.replace("\u00a0", "");
phoneNo = phoneNo.replace("\u202c", "");
phoneNo = phoneNo.replace("\u2011", "");
phoneNo = phoneNo.replace("\u202a", "");
phoneNo = phoneNo.replace("*", "");
phoneNo = phoneNo.replace("#", "");
if (phoneNo.length() >= 5)
{
if (name.equalsIgnoreCase(duplicateName) && phoneNo.equalsIgnoreCase(duplicatePhone)) {
continue;
}
duplicateName = name;
duplicatePhone = phoneNo;
String formattedPhoneNumber;
formattedPhoneNumber = parseNumber(phoneNo);
R_LocalContactDB realmResults = realmFresh.where(R_LocalContactDB.class).equalTo("phone", formattedPhoneNumber).findFirst();
Logger.debug("Size: " + realmResults);
R_LocalContactDB rContacts = new R_LocalContactDB(null, null, false, 0);
if (realmResults == null)
{
i++;
realmFresh.beginTransaction();
rCont = realmFresh.copyToRealm(rContacts);
rCont.setName(name);
rCont.setPhone(formattedPhoneNumber);
rCont.setStatus(0);
rCont.setMatchedWithRecent(true);
// Logger.debug("New Size: " + query.size());
realmFresh.commitTransaction();
}
else if( realmResults.isValid())
{
realmFresh.beginTransaction();
if (!name.equalsIgnoreCase(realmResults.getName()))
{
realmResults.setName(name);
}
realmResults.setMatchedWithRecent(true);
// Logger.debug("New Size Else Condition: " + query.size());
realmFresh.commitTransaction();
}
}
}
}
ContactsSyncService.contactUpdated = false;
}
realmFresh.close();
deleteExtraContacts();
getNumbersFromDBAndUpdate();
}
});
background.start();
}
Related
I am working with an Android application which shows the list of contacts in the phone like Whats-app. I am successful with getting the contacts to the Application database. When I try to update my DB when a contact is newly added/edited/deleted using Content Observer, I mainly face two problems
1. When Calls ,
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
I am getting wrong name. eg:- I edited Samuel's Contact no but checking the above code getting David's name.
when I try to get contact number by using the code,
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
I am getting error
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 402 rows, 41 columns.
03-01 17:16:56.546 3660-3660/com.xxxxxxxxx.xxxxx W/System.err: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Please Anybody help me to find the solution.
Here is my Code
public class ContactObserver extends ContentObserver {
Intent i;
private static final String TAG = "ObserverReceiver";
private Context context;
BaseActivity mBaseActivity;
public ContactObserver(Handler handler, BaseActivity context) {
super(handler);
this.mBaseActivity = context;
this.context = context;
}
public ContactObserver() {
super(null);
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
if (!selfChange) {
try {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
Log.d(TAG, "Observer has been started..");
// Contacts Cursor
final Cursor cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
// Check which contact is added or updated
if (cur != null) {
while (cur.moveToNext()) {
// Get contact added/updated timestamp but CONTACT_LAST_UPDATED_TIMESTAMP
// Get new/updated contact detail here
final String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
final String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String contactNumber = null;
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
} catch (Exception e) {
e.printStackTrace();
}
}
String finalContactNumber = contactNumber;
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
List<Contacts> sContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getBySystemid(id);
Log.i("Contacts1+", new Gson().toJson(sContacts));
if (sContacts.size() > 0) {
for (Contacts mContacts : sContacts) {
String phone = finalContactNumber;
if (phone == null) {
phone = mContacts.getPhone();
}
Log.i("Contacts1+", contactName + " : " + phone);
if (phone != null && phone.length() > 0) {
phone = phone.replace(" ", "");
}
while (String.valueOf(phone.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < phone.length(); i++) {
num = num + phone.charAt(i);
}
phone = num;
}
if (phone.length() == 10) {
phone = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + phone;
}
if ((mContacts.getName() != contactName || mContacts.getPhone() != phone)) {
mContacts.setName(contactName);
if (!mContacts.getPhone().equalsIgnoreCase(phone)) {
mContacts.setPhone(phone);
mContacts.setIslisted("false");
}
if (mContacts.getPhone().equalsIgnoreCase(phone) || mContacts.getName().equalsIgnoreCase(contactName)) {
ContactDatabase.getDatabase(context)
.contactsDao()
.update(mContacts);
cur.close();
}
}
}
} else {
Contacts mContacts = new Contacts();
String contactNumber = null;
try {
contactNumber = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactNumber != null && contactNumber.length() > 0) {
contactNumber = contactNumber.replace(" ", "");
contactNumber = contactNumber.replace("-", "");
}
while (String.valueOf(contactNumber.charAt(0)).equals("0")) {
String num = "";
for (int i = 1; i < contactNumber.length(); i++) {
num = num + contactNumber.charAt(i);
}
contactNumber = num;
}
if (contactNumber.length() == 10) {
contactNumber = getSharedPreference(AppConstants.SharedKey.COUNTRY_CODE) + contactNumber;
}
String contactName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
mContacts.setPhone(contactNumber);
mContacts.setName(contactName);
mContacts.setSystemid(id);
mContacts.setIslisted("false");
List<Contacts> cContacts = ContactDatabase
.getDatabase(context)
.contactsDao()
.getbyPhone(contactNumber);
if (cContacts.size() == 0) {
ContactDatabase.getDatabase(context)
.contactsDao()
.insert(mContacts);
}
} catch (Exception e) {
e.printStackTrace();
}
}
i = new Intent(context, ContactSynchService.class);
context.startService(i);
cur.close();
}
});
thread.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String getSharedPreference(String key) {
SharedPreferences prefs = mBaseActivity.getSharedPreferences(AppConstants.SHARED_KEY, MODE_PRIVATE);
return prefs.getString(key, "DEFAULT");
}
}
I tried these links, but none of them could give a solution.
ContentObserver for contact update manually
ContentObserver not working in android
Android: ContentObserver not working in android 4.3
Any help will be appreciated. Thanks in Advance
i call MyTask().execute(); in onCreate() of MainAcivity Class in my application. it Busy or Hang my application for long time. please help me why? i want my work in background so that it can't disturb my app. Why my app become busy and unresponsive?
Class code is below:
private class MyTask extends AsyncTask<String, Integer, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
super.onPreExecute();
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
checkUser();
return "";
}
// This is called from background thread but runs in UI
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// Do things like update the progress bar
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Do things like hide the progress bar or change a TextView
}
}
checkUser() method code is below
private void checkUser(){
// now here we convert this list array into json string
final String server_url="http://www.xxxx.com/TruCaller/check_user.php"; // url of server check this 100 times it must be working
// volley
StringRequest stringRequest=new StringRequest(Request.Method.POST, server_url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
final String result=response.toString().trim();
if(result.equals("not found")){
//Toast.makeText(MainActivity.this,"Wait...",Toast.LENGTH_LONG).show();
// Log.d("responsedd", "result not found fffffffff: "+result);
getContacts2();
}else{
}
// Log.d("responsedd", "result : "+result); //when response come i will log it
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
error.getMessage(); // when error come i will log it
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("identifier", UIDD);
Log.d("responsedd", "result not found ggggggggggg: "+ UIDD);
return params;
}
};
Vconnection.getnInstance(this).addRequestQue(stringRequest); // vConnection i claas which used to connect volley
}
getContacts2() method code is below:
public void getContacts2() {
if (!mayRequestContacts()) {
return;
}
// contactList = new ArrayList<String>();
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output;
ContentResolver contentResolver = getContentResolver();
cursor = contentResolver.query(CONTENT_URI, null, null, null, null);
// Iterate every contact in the phone
if (cursor.getCount() > 0) {
counter = 0;
while (cursor.moveToNext()) {
output = new StringBuffer();
String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));
String phoneC = "", adressC = "", emailC = "",country_code="";
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));
Bitmap bitmap = null;
String image = "";
if (hasPhoneNumber > 0) {
////////////////////Phone numbers with this name..... 2 Testing ....////////////////
String phoneNumber2 = "";
final String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.TYPE,};
final Cursor phone = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, ContactsContract.Data.CONTACT_ID + "=?", new String[]{String.valueOf(contact_id)}, null);
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA);
phoneC = "";
while (!phone.isAfterLast()) {
////////////////////////////////////////////
String x = phone.getString(contactNumberColumnIndex);
bitmap = retrieveContactPhoto(MainActivity.this, x);
String countryCode = countryCode(phone.getString(contactNumberColumnIndex));
country_code = countryCode;
// String swissNumberStr = "03348633664";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.createInstance(getApplicationContext());
Phonenumber.PhoneNumber pNumberProto;
String phoneVerfid="";
try {
pNumberProto = phoneUtil.parse(phone.getString(contactNumberColumnIndex), countryCode);
// System.err.println("NumberParseException was thrown:>>>>>>>>>>>> " + pNumberProto);
boolean isValid = phoneUtil.isValidNumber(pNumberProto);
if(isValid){
System.out.println(phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL));
phoneVerfid = phoneUtil.format(pNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
}
} catch (NumberParseException e) {
// System.err.println("NumberParseException was thrown: " + e.toString() +" ???" +phone.getString(contactNumberColumnIndex) + countryCode);
}
///////////////////////////////
phoneNumber2 = phoneVerfid + "_";
// output.append("\n Phone number:" + phoneNumber2);
phoneC = phoneC + phoneNumber2;
// System.out.println("Country = "+countryCode(phoneNumber2) + " p= " +phoneNumber2);
phone.moveToNext();
}
}
phone.close();
/////////////////////////////////////////////////////////////
// Read every email id associated with the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);
emailC = "";
email = "";
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA)) + "%";
if (!emailC.contains(email)) {
emailC = emailC + email;
// output.append("\n Email:" + email);
}
}
emailCursor.close();
//////////// Adresss//////
String postalData = "";
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{String.valueOf(contact_id), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, addrWhere, addrWhereParams, null);
if (addrCur.moveToFirst()) {
postalData = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS));
//output.append("\n Address:" + postalData);
adressC = adressC + " " + postalData;
}
addrCur.close();
}
if (phoneC != "") {
if (bitmap != null) {
Bitmap bitmap1 = getResizedBitmap(bitmap,210);
image = getStringImage(bitmap1);
if(bitmap1!=null) {
bitmap1.recycle();
}
// System.out.println("KKKKKKKKKKKKKKKKKKK >>>>>>>>> "+image);
}
Contact_Details dt = new Contact_Details(name, phoneC, UIDD, country_code, image, emailC, adressC);
dataArray.add(dt);
if(bitmap!=null){ bitmap.recycle();}
image = "";
}
}
submit1User2Contacs();
}
}
MainAcivity onCreate Method :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new MyTask().execute();}
Looks like you haven't called close method for cursor object.
Calling cursor.close() will solve your problem
i try below code instead of new MyTask().execute() class. and the below code work for me. i also try below code with xxx.run(); method instead of start();. run() method also not work. only thread with xxx.start(); worked. so the correct code is below one. Thanks every one.
new Thread(new Runnable(){
#Override
public void run() {
//my method
checkUser();
}
}).start();
this is my service Interface
public interface ContactService {
void postPhoneContacts(#NonNull ContactServiceListener serviceListener, int id, List<UserProfileInfo> userInfo);
}
This is mybackground service from where i want to make a network call
How to intsantiate Contact Service Interface here? I am getting Null Pointer Exception. From Fragment I am starting this service. Please help me this out
public class UploadContactBgService extends Service {
private ContactService contactService;
private int userId;
#Override
public void onCreate() {
super.onCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
List<UserProfileInfo> contactList = getContactsFromPhone();
EventBus.getDefault().post(new PostContactEvent(contactList));
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
userId = prefs.getInt(LoginPresenter.PREF_USER_ID, 0);
if (userId != 0) {
postPhoneBookContactList(userId, contactList);
}*/
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
private List<UserProfileInfo> getContactsFromPhone() {
//Read Column names of ContactsContract table to get contact info from phone book
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
Uri DATA_CONTENT_URI = ContactsContract.Data.CONTENT_URI;
String ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String PHONE_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
String EMAIL_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
String DATA_CONTACT_ID = ContactsContract.Data.CONTACT_ID;
String ADDRESS_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE;
String ORG_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE;
String DATA_MIME_TYPE = ContactsContract.Data.MIMETYPE;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
String EVENT_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE;
String EVENT_START_DATE = ContactsContract.CommonDataKinds.Event.START_DATE;
String NOTE_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE;
String WEB_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE;
String RELATION_CONTENT_ITEM_TYPE = ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE;
int CONTACT_TYPE_MOBILE = 1;
int CONTACT_TYPE_WORK = 2;
int CONTACT_TYPE_HOME = 3;
int CONTACT_TYPE_WORK_FAX = 4;
int CONTACT_TYPE_HOME_FAX = 5;
int CONTACT_TYPE_PAGER = 6;
int CONTACT_TYPE_OTHER = 7;
int USER_PROFILE_TYPE = 2;
ContentResolver cr = this.getContentResolver();
Cursor cursor = cr.query(CONTENT_URI, null, null, null,
DISPLAY_NAME + " ASC ");
List<UserProfileInfo> userInfoList = new ArrayList<>();
if (cursor.moveToNext()) {
do {
String contactId = cursor.getString(cursor.getColumnIndex(ID));
UserProfileInfo userInfo = new UserProfileInfo();
UserProfile profile = new UserProfile();
UserType userType = new UserType();
/**
* Querying the table ContactsContract.Data to retrieve individual items like
home phone, mobile phone, work email etc corresponding to each contact
*/
Cursor dataCursor = cr.query(DATA_CONTENT_URI, null,
DATA_CONTACT_ID + "=" + contactId,
null, null);
if (dataCursor.moveToFirst()) {
/**
* checking if respective contactId has contact number or not
* If yes..then only add that user to list
* otherwise read next user
*/
int hasContactNumber = Integer.parseInt(dataCursor.getString(
dataCursor.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasContactNumber == 0) {
continue;
}
// Getting Display Name
String displayName = dataCursor.getString(dataCursor.getColumnIndex(DISPLAY_NAME));
profile.setName(displayName);
do {
// Getting Phone numbers
List<Contact> phones = new ArrayList<>();
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(PHONE_CONTENT_ITEM_TYPE)) {
Contact contactNum = new Contact();
ContactTypeDm contactTypeDm = new ContactTypeDm();
switch (dataCursor.getInt(dataCursor.getColumnIndex("data2"))) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
String homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(homePhone);
contactNum.setContactNumber(homePhone);
contactTypeDm.setContactTypeId(CONTACT_TYPE_HOME);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
String mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(mobilePhone);
contactNum.setContactNumber(mobilePhone);
contactTypeDm.setContactTypeId(CONTACT_TYPE_MOBILE);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
String workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(workPhone);
contactNum.setContactNumber(workPhone);
contactTypeDm.setContactTypeId(CONTACT_TYPE_WORK);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
String other = dataCursor.getString(dataCursor.getColumnIndex("data1"));
userInfo.setUserName(other);
contactNum.setContactNumber(other);
contactTypeDm.setContactTypeId(CONTACT_TYPE_OTHER);
contactNum.setContactTypeDm(contactTypeDm);
phones.add(contactNum);
break;
}
userInfo.setContacts(phones);
}
// Getting EMails
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(EMAIL_CONTENT_ITEM_TYPE)) {
switch (dataCursor.getInt(dataCursor.getColumnIndex("data2"))) {
case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
String homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setEmail(homeEmail);
break;
case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
String workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setEmail(workEmail);
break;
}
}
// Getting Organization details
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(ORG_CONTENT_ITEM_TYPE)) {
String companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
String title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
profile.setOrgName(companyName);
profile.setTitle(title);
}
// Getting BDay
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(EVENT_CONTENT_ITEM_TYPE)) {
int indexEvent = dataCursor.getColumnIndex(EVENT_START_DATE);
String dobStr = dataCursor.getString(indexEvent);
profile.setBDay(dobStr);
}
//Getting Note
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(NOTE_CONTENT_ITEM_TYPE)) {
String note = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setNotes(note);
}
//Getting Postal Address Details...
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(ADDRESS_CONTENT_ITEM_TYPE)) {
String street = dataCursor.getString(dataCursor.getColumnIndex("data4"));
String city = dataCursor.getString(dataCursor.getColumnIndex("data7"));
String state = dataCursor.getString(dataCursor.getColumnIndex("data8"));
String postalCode = dataCursor.getString(dataCursor.getColumnIndex("data9"));
Address addressInfo = new Address();
addressInfo.setStreet(street);
addressInfo.setCity(city);
addressInfo.setZip(postalCode);
addressInfo.setState(state);
userInfo.setAddress(addressInfo);
}
//Getting Website
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(WEB_CONTENT_ITEM_TYPE)) {
String webUrl = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setWebsite(webUrl);
}
//Getting Relation
if (dataCursor.getString(dataCursor.getColumnIndex(DATA_MIME_TYPE)).equals(RELATION_CONTENT_ITEM_TYPE)) {
String relationship = dataCursor.getString(dataCursor.getColumnIndex("data1"));
profile.setRelationShip(relationship);
}
}
while (dataCursor.moveToNext());
}
userType.setUserTypeId(USER_PROFILE_TYPE);
profile.setUserType(userType);
userInfo.setUserProfile(profile);
userInfoList.add(userInfo);
} while (cursor.moveToNext());
}
return userInfoList;
}
public void postPhoneBookContactList(int id, List<UserProfileInfo> userInfoList) {
contactService.postPhoneContacts(new ContactServiceListener() {
#Override
public void onSuccess(UserProfileInfo responseBody) {
EventBus.getDefault().post(new GetSyncedContactListEvent(responseBody));
}
#Override
public void onError(String error) {
}
}, id, userInfoList);
}
}
Here i am fetching the name,email,phone number from the mobile and trying to upload to server..Here if the contacts contains name,email and phone number the values will be inserted successfully..but if any of the field is empty it is throwing NULL pointer exception.How to avoid this one..i mean if the contact does not contain email it should atleast send name and phone number.
here is my code.
public class DisplayContact1 extends Activity {
private static String TAG = WorkDetails1.class.getSimpleName();
Button select;
private String vault;
List<AddressBookContact> list;
public static final String kvault = "vault_no";
public static final String kname = "name";
public static final String kphone = "phone";
public static final String kemail = "email";
public static final String kcontacts = "contacts";
public static final String SHARED_PREF_NAME = "myloginapp";
public static final String UPLOAD_URL = "http://oursite.com/contacts_1.php";
private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
Cursor cursor;
LongSparseArray<AddressBookContact> array;
long start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.display);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
getAllContacts(this.getContentResolver());
}
public void getAllContacts(ContentResolver cr) {
int result = ContextCompat.checkSelfPermission(DisplayContact1.this, Manifest.permission.READ_CONTACTS);
if (result == PackageManager.PERMISSION_GRANTED){
//fetches contacts from the phone contact list and displays in ascending order
list = new LinkedList<AddressBookContact>();
array = new LongSparseArray<AddressBookContact>();
start = System.currentTimeMillis();
String[] projection = {
ContactsContract.Data.MIMETYPE,
ContactsContract.Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Contactables.DATA,
ContactsContract.CommonDataKinds.Contactables.TYPE,
};
String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
String[] selectionArgs = {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
};
String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;
Uri uri = ContactsContract.Data.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;
cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
contactsdisplay();
} else {
requestForLocationPermission();
}
}
private void requestForLocationPermission()
{
if (ActivityCompat.shouldShowRequestPermissionRationale(DisplayContact1.this, Manifest.permission.READ_CONTACTS))
{
}
else {
ActivityCompat.requestPermissions(DisplayContact1.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
{
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
getAllContacts(DisplayContact1.this.getContentResolver());
contactsdisplay();
}
break;
}
}
public void contactsdisplay() {
//Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);
while (cursor.moveToNext()) {
long id = cursor.getLong(idIdx);
AddressBookContact addressBookContact = array.get(id);
if (addressBookContact == null) {
addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
array.put(id, addressBookContact);
list.add(addressBookContact);
}
int type = cursor.getInt(typeIdx);
String data = cursor.getString(dataIdx);
String mimeType = cursor.getString(mimeTypeIdx);
if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
// mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
addressBookContact.addEmail(type, data);
} else {
// mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
addressBookContact.addPhone(type, data);
}
}
long ms = System.currentTimeMillis() - start;
cursor.close();
// done!!! show the results...
int i = 1;
for (AddressBookContact addressBookContact : list) {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
}
final String cOn = "<b><font color='#ff9900'>";
final String cOff = "</font></b>";
Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");
Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
Log.d(TAG, "║ " + l1);
Log.d(TAG, "║ " + l2);
Log.d(TAG, "╚════════════════════════════════════" );
SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);
ListView lv= (ListView) findViewById(R.id.lv);
lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
uploadImage();
}
});
}
public void uploadImage(){
SharedPreferences sharedPreferences = getSharedPreferences(DisplayContact.SHARED_PREF_NAME, MODE_PRIVATE);
final String vault_no = vault;
class UploadImage extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DisplayContact1.this,"Please wait...","uploading",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("Successfully Saved")){
//Intent intent = new Intent(CollegeDetails.this,Work.class);
Toast.makeText(DisplayContact1.this, s, Toast.LENGTH_SHORT).show();
// startActivity(intent);
}else{
Toast.makeText(DisplayContact1.this,s,Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
//RegisterUserClass rh = new RegisterUserClass();
HashMap<String,String> param = new HashMap<String,String>();
JSONArray contacts = new JSONArray();
int i = 1;
for (AddressBookContact addressBookContact : list) {
try {
Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
JSONObject contact = new JSONObject();
contact.put(kname, addressBookContact.name.toString());
contact.put(kvault, vault_no);
contact.put(kphone, addressBookContact.phone.toString());
if(addressBookContact.email.toString()!=null)
contact.put(kemail, addressBookContact.email.toString());
contacts.put(contact);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
param.put(kcontacts, contacts.toString());
System.out.println("param value.." + i++ +":"+ contacts.toString());
}
return rh.sendPostRequest(UPLOAD_URL, param);
}
}
UploadImage u = new UploadImage();
u.execute();
}
}
here is the AddressBookContact.class
public class AddressBookContact {
private long id;
private Resources res;
String name;
LongSparseArray<String> email;
LongSparseArray<String> phone;
AddressBookContact(long id, String name, Resources res) {
this.id = id;
this.name = name;
this.res = res;
}
#Override
public String toString() {
return toString(false);
}
public String toString(boolean rich) {
SpannableStringBuilder builder = new SpannableStringBuilder();
if (rich) {
builder.append("id: ").append(Long.toString(id))
.append(", name: ").append(name);
} else {
builder.append("name: ").append(name);
}
if (phone != null) {
builder.append("\nphone: ");
for (int i = 0; i < phone.size(); i++) {
int type = (int) phone.keyAt(i);
builder.append(phone.valueAt(i));
if (i + 1 < phone.size()) {
builder.append(", ");
}
}
}
if (email != null) {
builder.append("\nemail: ");
for (int i = 0; i < email.size(); i++) {
int type = (int) email.keyAt(i);
builder.append(email.valueAt(i));
if (i + 1 < email.size()) {
builder.append(", ");
}
}
}
return builder.toString();
}
public void addEmail(int type, String address) {
if (email == null) {
email = new LongSparseArray<String>();
}
email.put(type, address);
}
public void addPhone(int type, String number) {
if (phone == null) {
phone = new LongSparseArray<String>();
}
phone.put(type, number);
}
}
if email field is empty, i am getting null pointer exception at this line..
contact.put(kemail, addressBookContact.email.toString());..so i have added if loop to check the null condition..but then also i am getting exception.
Here
if (addressBookContact.email.toString() != null)
you try to get String from 'email' variable that is null.
Correct comparing is:
if (addressBookContact.email != null)
Add two conditions as below your string might not be null but can be
empty ""
if(addressBookContact.email.toString() != null && !addressBookContact.email.toString().equalsIgnoreCase(""))
contact.put(kemail, addressBookContact.email.toString());
Use TextUtils.
if(!TextUtils.isEmpty(addressBookContact.email.toString())){
contact.put(kemail, addressBookContact.email.toString());
}
And if kemail is compulsory field then in else condition just pass "" empty value.
This is the function which throws me ArrayIndexOutOfBoundsException: rowIndex > available rows:. At line if (!name.equalsIgnoreCase(realmResults.get(0).getName()) || !phoneNo.equalsIgnoreCase(realmResults.get(0).getPhone()) )
The code runs fine on HTC 620g but crashes on Moto G2 and other devices.
public static void refreshingContactsDB(final Context context)
{
Thread background = new Thread(new Runnable()
{
public void run()
{
realmFresh = Realm.getInstance(context);
createCountryDetailsArrayModel();
TelephonyManager tm = (TelephonyManager) ApplicationController.getInstance()
.getSystemService(Context.TELEPHONY_SERVICE);
String simCountryISO = tm.getSimCountryIso();
for (int i = 0; i < countryDetailsList.size(); i++) {
if (simCountryISO.equalsIgnoreCase(countryDetailsList.get(i)
.getCode())) {
dialCodePrefix = countryDetailsList.get(i).getDial_code();
}
}
AppPreferenceManager.getInstance().setContactUpdate(false);
Logger.debug("Contact Update Refreshing Contact Started -->");
ContentResolver cr = ApplicationController.getInstance()
.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
String duplicateName = "";
String duplicatePhone = "";
if (phones.getCount() > 0) {
final int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext()) {
String name = phones.getString(nameIndex);
String phoneNo = phones.getString(numberIndex);
if (phoneNo != null && !phoneNo.isEmpty())
{
phoneNo = phoneNo.replace(" ", "");
phoneNo = phoneNo.replace("(", "");
phoneNo = phoneNo.replace(")", "");
phoneNo = phoneNo.replace("-", "");
phoneNo = phoneNo.replace("\u00a0", "");
phoneNo = phoneNo.replace("\u202c", "");
phoneNo = phoneNo.replace("\u2011", "");
phoneNo = phoneNo.replace("\u202a", "");
phoneNo = phoneNo.replace("*", "");
phoneNo = phoneNo.replace("#", "");
if (phoneNo.length() >= 5) {
if (name.equalsIgnoreCase(duplicateName) && phoneNo.equalsIgnoreCase(duplicatePhone)) {
continue;
}
duplicateName = name;
duplicatePhone = phoneNo;
String formattedPhoneNumber;
formattedPhoneNumber = parseNumber(phoneNo);
RealmResults<R_LocalContactDB> realmResults = realmFresh.where(R_LocalContactDB.class).equalTo("phone", formattedPhoneNumber).findAll();
Logger.debug("Size: " + realmResults);
RealmResults<R_LocalContactDB> query = realmFresh.where(R_LocalContactDB.class).findAll();
R_LocalContactDB rContacts = new R_LocalContactDB(null, null, false, 0);
if (realmResults.size() == 0)
{
i++;
realmFresh.beginTransaction();
R_LocalContactDB rCont = realmFresh.copyToRealm(rContacts);
rCont.setName(name);
rCont.setPhone(formattedPhoneNumber);
rCont.setStatus(0);
rCont.setMatchedWithRecent(true);
Logger.debug("New Size: " + query.size());
realmFresh.commitTransaction();
Logger.debug("Sending To Server: " + i);
Logger.debug("Contact Update " + name
+ " saved");
}
else
{
realmFresh.beginTransaction();
if (!name.equalsIgnoreCase(realmResults.get(0).getName()) || !phoneNo.equalsIgnoreCase(realmResults.get(0).getPhone()) )
{
realmResults.get(0).setName(name);
realmResults.get(0).setPhone(phoneNo);
}
realmResults.get(0).setMatchedWithRecent(true);
realmResults.get(0);
Logger.debug("New Size Else Condition: " + query.size());
realmFresh.commitTransaction();
}
}
}
}
ContactsSyncService.contactUpdated = false;
phones.close();
}
realmFresh.close();
getNumbersFromDBAndUpdate();
deleteExtraContacts();
}
});
background.start();
}
RealmResults auto-update, so when you edit the data the the query will be refreshed. In your case it looks like you are doing:
RealmResults<R_LocalContactDB> realmResults = realmFresh.where(R_LocalContactDB.class).equalTo("phone", formattedPhoneNumber).findAll();
if (!name.equalsIgnoreCase(realmResults.get(0).getName()) || !phoneNo.equalsIgnoreCase(realmResults.get(0).getPhone()) ) {
realmResults.get(0).setName(name);
realmResults.get(0).setPhone(phoneNo); // This will make get(0) no longer part of the resultSet
}
realmResults.get(0).setMatchedWithRecent(true);
Instead of using .get(0) everywhere just cache it:
R_LocalContactDB item = realmResults.get(0);
//...
item.setMatchedWithRecent(true);