对象无法访问,是否被另一个线程删除?

时间:2015-11-04 13:23:16

标签: android realm

我有这个功能,当电话中的联系人有任何变化时调用,现在问题是这个代码在HTC Desire 620(KitKat)上工作正常但在Moto G(Lollipop)和其他设备上崩溃。 / p>

错误: java.lang.IllegalStateException:非法状态:对象不再有效进行操作。它被删除了吗?

另外:如果联系人不像< 500 ,但如果它更多崩溃!

Logcat详细信息:

  1. E / AndroidRuntime:进程:com.advisualinc.echo:SwitchService,PID:16972
  2. E / AndroidRuntime:java.lang.IllegalStateException:非法状态:对象不再有效进行操作。它被另一个线程删除了吗?
  3. E / AndroidRuntime:at io.realm.internal.UncheckedRow.nativeGetString(Native Method)
  4. E / AndroidRuntime:at java.lang.Thread.run(Thread.java:818)<< li>

    我的服务类:

    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);
        }
    }
    

    服务调用的函数是 refreshContactsDB()

    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();
    
    }
    

0 个答案:

没有答案