Example usage for android.util Log getStackTraceString

List of usage examples for android.util Log getStackTraceString

Introduction

In this page you can find the example usage for android.util Log getStackTraceString.

Prototype

public static String getStackTraceString(Throwable tr) 

Source Link

Document

Handy function to get a loggable stack trace from a Throwable

Usage

From source file:org.alfresco.mobile.android.application.fragments.node.details.NodeDetailsFragment.java

@Subscribe
public void onLikeEvent(LikeNodeEvent event) {
    View progressView = viewById(R.id.like_progress);
    ImageView likeButton = (ImageView) viewById(R.id.action_like);
    if (likeButton == null) {
        return;/*w w w  .  j  av  a  2  s  .c om*/
    }

    if (progressView != null) {
        progressView.setVisibility(View.GONE);
    }
    if (event.data == null) {
        Log.e(TAG, Log.getStackTraceString(event.exception));
        AlfrescoNotificationManager.getInstance(getActivity()).showToast(R.string.error_retrieve_likes);
    } else if (event.data) {
        likeButton.setImageResource(R.drawable.ic_like);
        AccessibilityUtils.addContentDescription(likeButton, R.string.unlike);
    } else {
        likeButton.setImageResource(R.drawable.ic_unlike);
        AccessibilityUtils.addContentDescription(likeButton, R.string.like);
    }
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

private void uploadMedia(final QueuedMedia item) {
    item.readyStage = QueuedMedia.ReadyStage.UPLOADING;

    String mimeType = getContentResolver().getType(item.uri);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String fileExtension = map.getExtensionFromMimeType(mimeType);
    final String filename = String.format("%s_%s_%s.%s", getString(R.string.app_name),
            String.valueOf(new Date().getTime()), StringUtils.randomAlphanumericString(10), fileExtension);

    byte[] content = item.content;

    if (content == null) {
        InputStream stream;/*from w w w  .j  a  v  a 2 s  . c  o m*/

        try {
            stream = getContentResolver().openInputStream(item.uri);
        } catch (FileNotFoundException e) {
            Log.d(TAG, Log.getStackTraceString(e));
            return;
        }

        content = MediaUtils.inputStreamGetBytes(stream);
        IOUtils.closeQuietly(stream);

        if (content == null) {
            return;
        }
    }

    if (mimeType == null)
        mimeType = "multipart/form-data";

    item.preview.setProgress(0);

    ProgressRequestBody fileBody = new ProgressRequestBody(content, MediaType.parse(mimeType), false, // If request body logging is enabled, pass true
            new ProgressRequestBody.UploadCallback() { // may reference activity longer than I would like to
                int lastProgress = -1;

                @Override
                public void onProgressUpdate(final int percentage) {
                    if (percentage != lastProgress) {
                        runOnUiThread(() -> item.preview.setProgress(percentage));
                    }
                    lastProgress = percentage;
                }
            });

    MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, fileBody);

    item.uploadRequest = mastodonApi.uploadMedia(body);

    item.uploadRequest.enqueue(new Callback<Attachment>() {
        @Override
        public void onResponse(@NonNull Call<Attachment> call,
                @NonNull retrofit2.Response<Attachment> response) {
            if (response.isSuccessful()) {
                onUploadSuccess(item, response.body());
            } else {
                Log.d(TAG, "Upload request failed. " + response.message());
                onUploadFailure(item, call.isCanceled());
            }
        }

        @Override
        public void onFailure(@NonNull Call<Attachment> call, @NonNull Throwable t) {
            Log.d(TAG, "Upload request failed. " + t.getMessage());
            onUploadFailure(item, call.isCanceled());
        }
    });
}

From source file:org.alfresco.mobile.android.application.fragments.node.details.NodeDetailsFragment.java

@Subscribe
public void onIsFavoriteEvent(FavoritedNodeEvent event) {
    View progressView = viewById(R.id.favorite_progress);
    ImageView favoriteButton = (ImageView) viewById(R.id.action_favorite);
    if (favoriteButton == null) {
        return;//from   w w  w  .j av a2  s . c  o m
    }

    if (progressView != null) {
        progressView.setVisibility(View.GONE);
    }
    if (event.data == null) {
        Log.e(TAG, Log.getStackTraceString(event.exception));
        AlfrescoNotificationManager.getInstance(getActivity()).showToast(R.string.error_retrieve_favorite);
    } else if (event.data) {
        favoriteButton.setImageResource(R.drawable.ic_favorite_light);
        AccessibilityUtils.addContentDescription(favoriteButton, R.string.unfavorite);
    } else {
        favoriteButton.setImageResource(R.drawable.ic_unfavorite_dark);
        AccessibilityUtils.addContentDescription(favoriteButton, R.string.favorite);
    }
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

private void stopVPN(ParcelFileDescriptor pfd) {
    Log.i(TAG, "Stopping");
    try {//from w  w w  .  j  av  a 2  s .c  o m
        pfd.close();
    } catch (IOException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        Util.sendCrashReport(ex, this);
    }
}

From source file:org.alfresco.mobile.android.application.fragments.node.details.NodeDetailsFragment.java

@Subscribe
public void onFavoriteNodeEvent(FavoriteNodeEvent event) {
    View progressView = viewById(R.id.favorite_progress);
    ImageView favoriteButton = (ImageView) viewById(R.id.action_favorite);
    if (favoriteButton == null) {
        return;// w ww  . j  a v a  2  s. co m
    }

    if (progressView != null) {
        progressView.setVisibility(View.GONE);
    }
    if (event.data == null) {
        Log.e(TAG, Log.getStackTraceString(event.exception));
        AlfrescoNotificationManager.getInstance(getActivity()).showToast(R.string.error_retrieve_favorite);
    } else if (event.data) {
        favoriteButton.setImageResource(R.drawable.ic_favorite_light);
        AccessibilityUtils.addContentDescription(favoriteButton, R.string.unfavorite);
    } else {
        favoriteButton.setImageResource(R.drawable.ic_unfavorite_dark);
        AccessibilityUtils.addContentDescription(favoriteButton, R.string.favorite);
    }

    if (!DisplayUtils.hasCentralPane(getActivity()) && getFragment(DocumentFolderBrowserFragment.TAG) != null) {
        ((DocumentFolderBrowserFragment) getFragment(DocumentFolderBrowserFragment.TAG))
                .onFavoriteNodeEvent(event);
    }
}

From source file:org.alfresco.mobile.android.application.fragments.node.details.NodeDetailsFragment.java

@Subscribe
public void onSyncNodeEvent(SyncNodeEvent event) {
    ImageView syncButton = (ImageView) viewById(R.id.action_sync);
    if (syncButton == null) {
        return;/*from ww w.j  ava  2s  .co m*/
    }

    if (event.data == null) {
        Log.e(TAG, Log.getStackTraceString(event.exception));
        // AlfrescoNotificationManager.getInstance(getActivity()).showToast(R.string.error_retrieve_favorite);
    } else if (event.data) {
        this.isSynced = event.data;
        syncButton.setImageResource(R.drawable.ic_synced_dark);
        AccessibilityUtils.addContentDescription(syncButton, R.string.unsync);

    } else {
        this.isSynced = event.data;
        syncButton.setImageResource(R.drawable.ic_sync_light);
        AccessibilityUtils.addContentDescription(syncButton, R.string.sync);
    }

    if (!DisplayUtils.hasCentralPane(getActivity())) {
        if (SyncContentManager.getInstance(getActivity()).canSync(SessionUtils.getAccount(getActivity()))) {
            if (event.node != null) {
                SyncContentManager.getInstance(getActivity()).sync(SessionUtils.getAccount(getActivity()),
                        event.node.getIdentifier());
            } else {
                SyncContentManager.getInstance(getActivity()).sync(AnalyticsManager.LABEL_SYNC_ACTION,
                        SessionUtils.getAccount(getActivity()));
            }
        }
    }
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

private void stopNative(ParcelFileDescriptor vpn, boolean clear) {
    Log.i(TAG, "Stop native clear=" + clear);
    try {//from   ww w .j  a va 2 s  .c om
        jni_stop(vpn.getFd(), clear);
    } catch (Throwable ex) {
        // File descriptor might be closed
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        jni_stop(-1, clear);
    }
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

private Allowed isAddressAllowed(Packet packet) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    packet.allowed = false;/*from w  w  w  .j a  v  a  2  s . c om*/
    if (prefs.getBoolean("filter", false)) {
        // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
        if (packet.uid < 2000 && !last_connected && isSupported(packet.protocol)) {
            // Allow system applications in disconnected state
            packet.allowed = true;
            Log.w(TAG, "Allowing disconnected system " + packet);

        } else if (packet.uid < 2000 && !mapUidKnown.containsKey(packet.uid) && isSupported(packet.protocol)) {
            // Allow unknown system traffic
            packet.allowed = true;
            Log.w(TAG, "Allowing unknown system " + packet);

        } else {
            boolean filtered = false;
            // Only TCP (6) and UDP (17) have port numbers
            int dport = (packet.protocol == 6 || packet.protocol == 17 ? packet.dport : 0);
            long key = (packet.version << 40) | (packet.protocol << 32) | (dport << 16) | packet.uid;

            synchronized (mapUidIPFilters) {
                if (mapUidIPFilters.containsKey(key))
                    try {
                        InetAddress iaddr = InetAddress.getByName(packet.daddr);
                        Map<InetAddress, Boolean> map = mapUidIPFilters.get(key);
                        if (map != null && map.containsKey(iaddr)) {
                            filtered = true;
                            packet.allowed = !map.get(iaddr);
                            Log.i(TAG, "Filtering " + packet);
                        }
                    } catch (UnknownHostException ex) {
                        Log.w(TAG, "Allowed " + ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

                if (!filtered)
                    packet.allowed = (mapUidAllowed.containsKey(packet.uid) && mapUidAllowed.get(packet.uid));
            }
        }
    }

    Allowed allowed = null;
    if (packet.allowed) {
        if (mapForward.containsKey(packet.dport)) {
            Forward fwd = mapForward.get(packet.dport);
            if (fwd.ruid == packet.uid) {
                allowed = new Allowed();
            } else {
                allowed = new Allowed(fwd.raddr, fwd.rport);
                packet.data = "> " + fwd.raddr + "/" + fwd.rport;
            }
        } else
            allowed = new Allowed();
    }

    if (prefs.getBoolean("log", false) || prefs.getBoolean("log_app", false))
        logPacket(packet);

    return allowed;
}

From source file:com.phonegap.ContactAccessorSdk5.java

/**
 * Creates a new contact and stores it in the database
 * //from  w  ww . j ava 2 s .  c  o m
 * @param id the raw contact id which is required for linking items to the contact
 * @param contact the contact to be saved
 * @param account the account to be saved under
 */
private boolean modifyContact(String id, JSONObject contact, Account account) {
    // Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
    // But not needed to update existing values.
    int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();

    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    //Add contact type
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, account.name).build());

    // Modify name
    JSONObject name;
    try {
        String displayName = getJsonString(contact, "displayName");
        name = contact.getJSONObject("name");
        if (displayName != null || name != null) {
            ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { id,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });

            if (displayName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
            }

            String familyName = getJsonString(name, "familyName");
            if (familyName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
            }
            String middleName = getJsonString(name, "middleName");
            if (middleName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
            }
            String givenName = getJsonString(name, "givenName");
            if (givenName != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
            }
            String honorificPrefix = getJsonString(name, "honorificPrefix");
            if (honorificPrefix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
            }
            String honorificSuffix = getJsonString(name, "honorificSuffix");
            if (honorificSuffix != null) {
                builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
            }

            ops.add(builder.build());
        }
    } catch (JSONException e1) {
        Log.d(LOG_TAG, "Could not get name");
    }

    // Modify phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            for (int i = 0; i < phones.length(); i++) {
                JSONObject phone = (JSONObject) phones.get(i);
                String phoneId = getJsonString(phone, "id");
                // This is a new phone so do a DB insert
                if (phoneId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                            getJsonString(phone, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                            getPhoneType(getJsonString(phone, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing phone so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Phone._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    getJsonString(phone, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                    getPhoneType(getJsonString(phone, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }

    // Modify emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            for (int i = 0; i < emails.length(); i++) {
                JSONObject email = (JSONObject) emails.get(i);
                String emailId = getJsonString(email, "id");
                // This is a new email so do a DB insert
                if (emailId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Email.DATA,
                            getJsonString(email, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE,
                            getContactType(getJsonString(email, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing email so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Email._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Email.DATA,
                                    getJsonString(email, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                                    getContactType(getJsonString(email, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            for (int i = 0; i < addresses.length(); i++) {
                JSONObject address = (JSONObject) addresses.get(i);
                String addressId = getJsonString(address, "id");
                // This is a new address so do a DB insert
                if (addressId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                            getJsonString(address, "formatted"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                            getJsonString(address, "streetAddress"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                            getJsonString(address, "locality"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                            getJsonString(address, "region"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                            getJsonString(address, "postalCode"));
                    contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                            getJsonString(address, "country"));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing address so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { addressId,
                                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS,
                                    getJsonString(address, "formatted"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET,
                                    getJsonString(address, "streetAddress"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY,
                                    getJsonString(address, "locality"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION,
                                    getJsonString(address, "region"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE,
                                    getJsonString(address, "postalCode"))
                            .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY,
                                    getJsonString(address, "country"))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }

    // Modify organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            for (int i = 0; i < organizations.length(); i++) {
                JSONObject org = (JSONObject) organizations.get(i);
                String orgId = getJsonString(org, "id");
                ;
                // This is a new organization so do a DB insert
                if (orgId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                            getJsonString(org, "department"));
                    contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY,
                            getJsonString(org, "name"));
                    contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE,
                            getJsonString(org, "title"));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing organization so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(
                                    ContactsContract.CommonDataKinds.Organization._ID + "=? AND "
                                            + ContactsContract.Data.MIMETYPE + "=?",
                                    new String[] { orgId,
                                            ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT,
                                    getJsonString(org, "department"))
                            .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY,
                                    getJsonString(org, "name"))
                            .withValue(ContactsContract.CommonDataKinds.Organization.TITLE,
                                    getJsonString(org, "title"))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }

    // Modify IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            for (int i = 0; i < ims.length(); i++) {
                JSONObject im = (JSONObject) ims.get(i);
                String imId = getJsonString(im, "id");
                ;
                // This is a new IM so do a DB insert
                if (imId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE,
                            getContactType(getJsonString(im, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing IM so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Im._ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                    + "=?",
                            new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Im.TYPE,
                                    getContactType(getJsonString(im, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Modify note
    String note = getJsonString(contact, "note");
    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
            .withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                    new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE })
            .withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());

    // Modify nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE })
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }

    // Modify urls   
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("websites");
        if (websites != null) {
            for (int i = 0; i < websites.length(); i++) {
                JSONObject website = (JSONObject) websites.get(i);
                String websiteId = getJsonString(website, "id");
                ;
                // This is a new website so do a DB insert
                if (websiteId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.CommonDataKinds.Website.DATA,
                            getJsonString(website, "value"));
                    contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE,
                            getContactType(getJsonString(website, "type")));

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing website so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(
                                    ContactsContract.CommonDataKinds.Website._ID + "=? AND "
                                            + ContactsContract.Data.MIMETYPE + "=?",
                                    new String[] { websiteId,
                                            ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.CommonDataKinds.Website.DATA,
                                    getJsonString(website, "value"))
                            .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                                    getContactType(getJsonString(website, "type")))
                            .build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }

    // Modify birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                .withSelection(
                        ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
                                + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?",
                        new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
                                new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) })
                .withValue(ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
                .withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }

    // Modify photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            for (int i = 0; i < photos.length(); i++) {
                JSONObject photo = (JSONObject) photos.get(i);
                String photoId = getJsonString(photo, "id");
                byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
                // This is a new photo so do a DB insert
                if (photoId == null) {
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
                    contentValues.put(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
                    contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
                    contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);

                    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                            .withValues(contentValues).build());
                }
                // This is an existing photo so do a DB update
                else {
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(
                            ContactsContract.CommonDataKinds.Photo._ID + "=? AND "
                                    + ContactsContract.Data.MIMETYPE + "=?",
                            new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
                            .withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
                            .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
                }
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }

    boolean retVal = true;

    //Modify contact
    try {
        mApp.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.e(LOG_TAG, Log.getStackTraceString(e), e);
        retVal = false;
    }

    return retVal;
}

From source file:eu.faircode.netguard.ServiceSinkhole.java

private void prepareHostsBlocked() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ServiceSinkhole.this);
    boolean use_hosts = prefs.getBoolean("filter", false) && prefs.getBoolean("use_hosts", false);
    File hosts = new File(getFilesDir(), "hosts.txt");
    if (!use_hosts || !hosts.exists() || !hosts.canRead()) {
        Log.i(TAG, "Hosts file use=" + use_hosts + " exists=" + hosts.exists());
        lock.writeLock().lock();//from  w  ww .java 2s .  c  o  m
        mapHostsBlocked.clear();
        lock.writeLock().unlock();
        return;
    }

    boolean changed = (hosts.lastModified() != last_hosts_modified);
    if (!changed && mapHostsBlocked.size() > 0) {
        Log.i(TAG, "Hosts file unchanged");
        return;
    }
    last_hosts_modified = hosts.lastModified();

    lock.writeLock().lock();

    mapHostsBlocked.clear();

    int count = 0;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(hosts));
        String line;
        while ((line = br.readLine()) != null) {
            int hash = line.indexOf('#');
            if (hash >= 0)
                line = line.substring(0, hash);
            line = line.trim();
            if (line.length() > 0) {
                String[] words = line.split("\\s+");
                if (words.length == 2) {
                    count++;
                    mapHostsBlocked.put(words[1], true);
                } else
                    Log.i(TAG, "Invalid hosts file line: " + line);
            }
        }
        mapHostsBlocked.put("test.netguard.me", true);
        Log.i(TAG, count + " hosts read");
    } catch (IOException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (IOException exex) {
                Log.e(TAG, exex.toString() + "\n" + Log.getStackTraceString(exex));
            }
    }

    lock.writeLock().unlock();
}