Example usage for android.content ContentValues clear

List of usage examples for android.content ContentValues clear

Introduction

In this page you can find the example usage for android.content ContentValues clear.

Prototype

public void clear() 

Source Link

Document

Removes all values.

Usage

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {/*from   www .ja v a2  s  .  c  om*/
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncServiceTesting.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat_testing", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:com.tct.emailcommon.utility.AttachmentUtilities.java

/**
 * Save the attachment to its final resting place (cache or sd card)
 *///from  w  ww. j  a v  a  2s .  co  m
public static long saveAttachment(Context context, InputStream in, Attachment attachment) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    String realUri = null; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD
    long size = 0;

    try {
        ContentResolver resolver = context.getContentResolver();
        if (attachment.mUiDestination == UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_CACHE) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment when attachment destination is cache",
                    "attachment.size:" + attachment.mSize);
            Uri attUri = getAttachmentUri(accountId, attachmentId);
            size = copyFile(in, resolver.openOutputStream(attUri));
            contentUri = attUri.toString();
        } else if (Utility.isExternalStorageMounted()) {
            LogUtils.i(LogUtils.TAG, "AttachmentUtilities saveAttachment to storage",
                    "attachment.size:" + attachment.mSize);
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
            String exchange = "com.tct.exchange";
            if (exchange.equals(context.getPackageName()) && !PermissionUtil
                    .checkPermissionAndLaunchExplain(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                throw new IOException("Can't save an attachment due to no Storage permission");
            }
            //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
            File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            size = copyFile(in, new FileOutputStream(file));
            String absolutePath = file.getAbsolutePath();
            realUri = "file://" + absolutePath; //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD

            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);

            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;

            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }

        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.CONTENT_URI, contentUri);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_S
        if (realUri != null) {
            cv.put(AttachmentColumns.REAL_URI, realUri);
        }
        //TS: zheng.zou 2016-1-22 EMAIL BUGFIX-1431088 ADD_E
    } catch (IOException e) {
        LogUtils.e(Logging.LOG_TAG, e, "Fail to save attachment to storage!");
        // Handle failures here...
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_FAILED);
    }
    context.getContentResolver().update(uri, cv, null, null);
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    // If this is an inline attachment, update the body
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_S
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_S
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-01 EXCHANGE BUGFIX_962560 MOD_E
            //TS: zhaotianyong 2015-03-23 EXCHANGE BUGFIX_899799 MOD_E
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
    return size;
}

From source file:com.zhihuigu.sosoOffice.LoginActivity.java

/***
 * author by Ring //  www .j  a  va 2s.c  om
 */

public void dealReponse() {
    if (StringUtils.CheckReponse(reponse)) {
        ContentValues values = new ContentValues();
        Gson gson = new Gson();// Gson
        SoSoUserInfo sosouserinfo = null;
        List<Map<String, Object>> selectresult = null;
        try {
            sosouserinfo = gson.fromJson(reponse, SoSoUserInfo.class);//json
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sosouserinfo != null && sosouserinfo.getUserName() != null && sosouserinfo.getUserID() != null) {
            values.put("soso_userid", sosouserinfo.getUserID());
            values.put("soso_username", sosouserinfo.getUserName());
            values.put("soso_password", passwordEt.getText().toString());
            values.put("soso_realname", sosouserinfo.getRealName());
            values.put("soso_registerdate", sosouserinfo.getRegisterDate());
            values.put("soso_userimageurl", sosouserinfo.getHeadImage());
            values.put("soso_logindate", sosouserinfo.getLoginDate());
            values.put("soso_sex", sosouserinfo.getSex());
            values.put("soso_roleid", sosouserinfo.getRoleID());
            values.put("soso_rolemc", sosouserinfo.getRoleMC());
            values.put("soso_region", sosouserinfo.getRegion());
            values.put("soso_birthday", sosouserinfo.getBirthday());
            values.put("soso_email", sosouserinfo.getEmail());
            values.put("soso_telephone", sosouserinfo.getTelephone());
            values.put("soso_bigintegral", sosouserinfo.getBigintegral());
            values.put("soso_credibility", sosouserinfo.getCredibility());
            values.put("soso_customerstate", sosouserinfo.getCustomerState());
            values.put("soso_ownerphone", sosouserinfo.getZJTele());
            values.put("soso_legalperson", sosouserinfo.getZJMC());
            values.put("soso_owneraddress", sosouserinfo.getZJAddress());
            values.put("soso_businesslicenseurl", sosouserinfo.getJobsImage());
            values.put("autologin", checkBox.isChecked() ? 1 : 0);
            values.put("loginlast", 1);

            DBHelper.getInstance(LoginActivity.this)
                    .execSql("update soso_userinfo set autologin = 0 ,loginlast = 0");
            selectresult = DBHelper.getInstance(LoginActivity.this).selectRow(
                    "select * from soso_userinfo where soso_userid = '" + sosouserinfo.getUserID() + "'", null);
            //            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //            String time = StringUtils.formatCalendar1(sdf.format(new Date()),MyApplication.error_value);
            if (selectresult != null) {
                if (selectresult.size() <= 0) {
                    values.put("soso_lastlogindate", "1900-01-01 12:00:00");
                    DBHelper.getInstance(LoginActivity.this).insert("soso_userinfo", values);
                    sosouserinfo.setLastLoginDate("1900-01-01 12:00:00");
                } else {
                    if (selectresult.get(selectresult.size() - 1).get("soso_userimageurl") != null
                            && !sosouserinfo.equals(selectresult.get(selectresult.size() - 1)
                                    .get("soso_userimageurl").toString())) {
                        DBHelper.getInstance(this)
                                .execSql("update soso_userinfo set soso_userimagesd = '' where soso_userid ='"
                                        + sosouserinfo.getUserID() + "'");
                    }
                    try {
                        values.put("soso_lastlogindate",
                                selectresult.get(selectresult.size() - 1).get("soso_logindate").toString());
                    } catch (Exception e) {
                        values.put("soso_lastlogindate", "1900-01-01 12:00:00");
                    }
                    DBHelper.getInstance(LoginActivity.this).update("soso_userinfo", values, "soso_userid = ?",
                            new String[] { sosouserinfo.getUserID() });
                    try {
                        sosouserinfo.setLastLoginDate(
                                selectresult.get(selectresult.size() - 1).get("soso_lastlogindate").toString());
                    } catch (Exception e) {
                        sosouserinfo.setLastLoginDate("1900-01-01 12:00:00");
                    }
                }
            }
            sosouserinfo.setPassWord(passwordEt.getText().toString());
            MyApplication.getInstance(LoginActivity.this).setSosouserinfo(sosouserinfo);
            MyApplication.getInstance(LoginActivity.this).setRoleid(sosouserinfo.getRoleID());
        }
        if (values != null) {
            values.clear();
            values = null;
        }
        DBHelper.getInstance(LoginActivity.this).close();
    }
}

From source file:com.zhihuigu.sosoOffice.LoadActivity.java

/***
 * author by Ring /*from w  w  w . j av a  2  s. c o  m*/
 */

public void dealReponse() {
    if (StringUtils.CheckReponse(reponse)) {
        ContentValues values = new ContentValues();
        Gson gson = new Gson();// Gson
        SoSoUserInfo sosouserinfo = null;
        try {
            sosouserinfo = gson.fromJson(reponse, SoSoUserInfo.class);// json
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sosouserinfo != null && sosouserinfo.getUserName() != null && sosouserinfo.getUserID() != null) {
            values.put("soso_userid", sosouserinfo.getUserID());
            values.put("soso_username", sosouserinfo.getUserName());
            values.put("soso_realname", sosouserinfo.getRealName());
            values.put("soso_registerdate", sosouserinfo.getRegisterDate());
            values.put("soso_userimageurl", sosouserinfo.getHeadImage());
            values.put("soso_logindate", sosouserinfo.getLoginDate());
            values.put("soso_sex", sosouserinfo.getSex());
            values.put("soso_roleid", sosouserinfo.getRoleID());
            values.put("soso_rolemc", sosouserinfo.getRoleMC());
            values.put("soso_region", sosouserinfo.getRegion());
            values.put("soso_birthday", sosouserinfo.getBirthday());
            values.put("soso_email", sosouserinfo.getEmail());
            values.put("soso_telephone", sosouserinfo.getTelephone());
            values.put("soso_bigintegral", sosouserinfo.getBigintegral());
            values.put("soso_credibility", sosouserinfo.getCredibility());
            // "soso_ownerphone text,"+//
            // "soso_legalperson text,"+//
            // "soso_owneraddress text,"+//
            // "soso_businesslicenseurl text,"+//url
            values.put("soso_customerstate", sosouserinfo.getCustomerState());
            values.put("soso_ownerphone", sosouserinfo.getZJTele());
            values.put("soso_legalperson", sosouserinfo.getZJMC());
            values.put("soso_owneraddress", sosouserinfo.getZJAddress());
            values.put("soso_businesslicenseurl", sosouserinfo.getJobsImage());
            values.put("loginlast", 1);
            List<Map<String, Object>> selectresult = DBHelper.getInstance(LoadActivity.this).selectRow(
                    "select * from soso_userinfo where soso_userid = '" + sosouserinfo.getUserID() + "'", null);
            if (selectresult != null) {
                if (selectresult.size() <= 0) {
                    values.put("soso_lastlogindate", "1900-01-01 12:00:00");
                    DBHelper.getInstance(LoadActivity.this).insert("soso_userinfo", values);
                    sosouserinfo.setLastLoginDate("1900-01-01 12:00:00");
                } else {
                    if (selectresult.get(selectresult.size() - 1).get("soso_userimageurl") != null
                            && !sosouserinfo.equals(selectresult.get(selectresult.size() - 1)
                                    .get("soso_userimageurl").toString())) {
                        DBHelper.getInstance(this)
                                .execSql("update soso_userinfo set soso_userimagesd = '' where soso_userid ='"
                                        + sosouserinfo.getUserID() + "'");
                    }
                    try {
                        values.put("soso_lastlogindate",
                                selectresult.get(selectresult.size() - 1).get("soso_logindate").toString());
                    } catch (Exception e) {
                        values.put("soso_lastlogindate", "1900-01-01 12:00:00");
                    }
                    DBHelper.getInstance(LoadActivity.this).update("soso_userinfo", values, "soso_userid = ?",
                            new String[] { sosouserinfo.getUserID() });
                }
                sosouserinfo.setUserID(selectresult.get(selectresult.size() - 1).get("soso_userid").toString());
                sosouserinfo
                        .setUserName(selectresult.get(selectresult.size() - 1).get("soso_username").toString());
                sosouserinfo
                        .setPassWord(selectresult.get(selectresult.size() - 1).get("soso_password").toString());
                try {
                    sosouserinfo.setLastLoginDate(
                            selectresult.get(selectresult.size() - 1).get("soso_lastlogindate").toString());
                } catch (Exception e) {
                    sosouserinfo.setLastLoginDate("1900-01-01 12:00:00");
                }
            }
            MyApplication.getInstance(LoadActivity.this).setSosouserinfo(sosouserinfo);
            MyApplication.getInstance(LoadActivity.this).setRoleid(sosouserinfo.getRoleID());
        }
        if (values != null) {
            values.clear();
            values = null;
        }
        DBHelper.getInstance(LoadActivity.this).close();
    }
}

From source file:com.tct.emailcommon.utility.AttachmentUtilities.java

public static void saveAttachmentToExternal(Context context, Attachment attachment, String path) {
    final Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachment.mId);
    final ContentValues cv = new ContentValues();
    final long attachmentId = attachment.mId;
    final long accountId = attachment.mAccountKey;
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    String contentUri = null;//from w ww  . ja va2 s .  c  o m
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    final long size;
    InputStream in = null;
    OutputStream out = null;
    try {
        ContentResolver resolver = context.getContentResolver();
        if (Utility.isExternalStorageMounted()) {
            if (TextUtils.isEmpty(attachment.mFileName)) {
                // TODO: This will prevent a crash but does not surface the underlying problem
                // to the user correctly.
                LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment with no name: %d", attachmentId);
                throw new IOException("Can't save an attachment with no name");
            }
            // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_S
            try {
                String cachedFileUri = attachment.getCachedFileUri();
                if (TextUtils.isEmpty(cachedFileUri)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(cachedFileUri));
            } catch (IOException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
                //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_S
            } catch (IllegalArgumentException e) {
                String contentUriForOpen = attachment.getContentUri();
                if (TextUtils.isEmpty(contentUriForOpen)) {
                    throw new IOException();
                }
                in = resolver.openInputStream(Uri.parse(contentUriForOpen));
            }
            //TS: junwei-xu 2016-03-31 EMAIL BUGFIX-1886442 ADD_E
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_S
            //Note: we support save attachment at user designated location.
            File downloads;
            if (path != null) {
                downloads = new File(path);
            } else {
                downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            }
            //TS: jian.xu 2016-01-20 EMAIL FEATURE-1477377 MOD_E
            downloads.mkdirs();
            File file = Utility.createUniqueFile(downloads, attachment.mFileName);
            out = new FileOutputStream(file);
            size = copyFile(in, out);
            String absolutePath = file.getAbsolutePath();
            // Although the download manager can scan media files, scanning only happens
            // after the user clicks on the item in the Downloads app. So, we run the
            // attachment through the media scanner ourselves so it gets added to
            // gallery / music immediately.
            MediaScannerConnection.scanFile(context, new String[] { absolutePath }, null, null);
            final String mimeType = TextUtils.isEmpty(attachment.mMimeType) ? "application/octet-stream"
                    : attachment.mMimeType;
            try {
                DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_S
                //Note: should use media scanner, it will allow update the
                //media provider uri column in download manager's database.
                long id = dm.addCompletedDownload(attachment.mFileName, attachment.mFileName,
                        true /* use media scanner */, mimeType, absolutePath, size,
                        true /* show notification */);
                //TS: junwei-xu 2016-02-04 EMAIL BUGFIX-1531245 MOD_E
                contentUri = dm.getUriForDownloadedFile(id).toString();
            } catch (final IllegalArgumentException e) {
                LogUtils.d(LogUtils.TAG, e, "IAE from DownloadManager while saving attachment");
                throw new IOException(e);
            }
        } else {
            LogUtils.w(Logging.LOG_TAG, "Trying to save an attachment without external storage?");
            throw new IOException();
        }
        // Update the attachment
        cv.put(AttachmentColumns.SIZE, size);
        cv.put(AttachmentColumns.UI_STATE, UIProvider.UIPROVIDER_ATTACHMENTSTATE_SAVED);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_S
        //Note:we have saved the attachment to sd card,so should update the attachment destination external
        cv.put(AttachmentColumns.UI_DESTINATION, UIProvider.UIPROVIDER_ATTACHMENTDESTINATION_EXTERNAL);
        // TS: Gantao 2015-06-30 EMAIL BUGFIX-1031608 ADD_E
    } catch (IOException e) {
        // Handle failures here...
        LogUtils.e(Logging.LOG_TAG, "IOException while save an attachment to external storage");
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            LogUtils.e(Logging.LOG_TAG, "ioexception while close the stream");
        }
    }
    // TS: Gantao 2015-07-29 EMAIL BUGFIX-1055568 MOD_E
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_S
    //        context.getContentResolver().update(uri, cv, null, null);
    if (cv.size() > 0) {
        context.getContentResolver().update(uri, cv, null, null);
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_871936 MOD_E
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_S
    if (contentUri != null && attachment.mContentId != null && attachment.mContentId.length() > 0) {
        Body body = Body.restoreBodyWithMessageId(context, attachment.mMessageKey);
        if (body != null && body.mHtmlContent != null) {
            cv.clear();
            String html = body.mHtmlContent;
            String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + attachment.mContentId + "\\E\"";
            String srcContentUri = " src=\"" + contentUri + "\"";
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
            try {
                html = html.replaceAll(contentIdRe, srcContentUri);
            } catch (PatternSyntaxException e) {
                LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
            }
            //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
            cv.put(BodyColumns.HTML_CONTENT, html);
            Body.updateBodyWithMessageId(context, attachment.mMessageKey, cv);
            Body.restoreBodyHtmlWithMessageId(context, attachment.mMessageKey);
        }
    }
    //TS: wenggangjin 2014-12-11 EMAIL BUGFIX_868520 MOD_E
}

From source file:me.ububble.speakall.fragment.ConversationGroupFragment.java

public void showDialogAddContact(final String contacto) {
    final boolean[] agregar = { false };
    try {/*from   ww  w .  j  a v  a 2s  .  c  o  m*/
        final ContentResolver contentResolver = activity.getContentResolver();
        final JSONObject contact = new JSONObject(contacto);
        String name = null;
        String phone = null;

        String selectionArgs = ContactsContract.Contacts.DISPLAY_NAME + " = ? AND "
                + ContactsContract.CommonDataKinds.Phone.TYPE + "= "
                + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

        Cursor c = contentResolver.query(ContactsContract.Data.CONTENT_URI,
                new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, selectionArgs,
                new String[] { contact.getString("nombre") }, null);

        if (c.getCount() > 0) {
            if (c.moveToFirst()) {
                phone = c.getString(0);
            }
            if (phone.equals(contact.getString("telefono"))) {
                Toast.makeText(activity, "Ya tienes este contacto", Toast.LENGTH_SHORT).show();
            } else {
                LayoutInflater dialogInflater = (LayoutInflater) activity
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                        .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                        .setNegativeButton(R.string.add_contact_no, null);
                finderDialog = dialogBuilder.show();
                finderDialog.setCanceledOnTouchOutside(true);
                finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    finderDialog.dismiss();
                                    agregar[0] = true;
                                    if (agregar[0]) {
                                        ContentValues values = new ContentValues();
                                        values.put(ContactsContract.Data.DISPLAY_NAME,
                                                contact.getString("nombre"));
                                        Uri rawContactUri = contentResolver
                                                .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                        long rawContactId = ContentUris.parseId(rawContactUri);
                                        long contactId = ContentUris.parseId(rawContactUri);

                                        values.clear();
                                        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                                contact.getString("telefono"));
                                        values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                        values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finderDialog.dismiss();
                                agregar[0] = false;
                            }
                        });
            }
        } else {
            LayoutInflater dialogInflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                    .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                    .setNegativeButton(R.string.add_contact_no, null);
            finderDialog = dialogBuilder.show();
            finderDialog.setCanceledOnTouchOutside(true);
            finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                finderDialog.dismiss();
                                agregar[0] = true;
                                if (agregar[0]) {
                                    ContentValues values = new ContentValues();
                                    values.put(ContactsContract.Data.DISPLAY_NAME, contact.getString("nombre"));
                                    Uri rawContactUri = contentResolver
                                            .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                    long rawContactId = ContentUris.parseId(rawContactUri);

                                    values.clear();
                                    values.put(android.provider.ContactsContract.Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                            contact.getString("telefono"));
                                    values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                            ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                    values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(ContactsContract.Contacts.Data.MIMETYPE,
                                            ContactsContract.Data.CONTENT_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(ContactsContract.Contacts.Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finderDialog.dismiss();
                            agregar[0] = false;
                        }
                    });
        }
        c.close();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

public void showDialogAddContact(final String contacto) {
    final boolean[] agregar = { false };
    try {//from w w w  . ja v  a  2s.co m
        final ContentResolver contentResolver = activity.getContentResolver();
        final JSONObject contact = new JSONObject(contacto);
        String name = null;
        String phone = null;

        String selectionArgs = ContactsContract.Contacts.DISPLAY_NAME + " = ? AND "
                + ContactsContract.CommonDataKinds.Phone.TYPE + "= "
                + ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;

        Cursor c = contentResolver.query(ContactsContract.Data.CONTENT_URI,
                new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, selectionArgs,
                new String[] { contact.getString("nombre") }, null);

        if (c.getCount() > 0) {
            if (c.moveToFirst()) {
                phone = c.getString(0);
            }
            if (phone.equals(contact.getString("telefono"))) {
                Toast.makeText(activity, "Ya tienes este contacto", Toast.LENGTH_SHORT).show();
            } else {
                LayoutInflater dialogInflater = (LayoutInflater) activity
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                        .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                        .setNegativeButton(R.string.add_contact_no, null);
                finderDialog = dialogBuilder.show();
                finderDialog.setCanceledOnTouchOutside(true);
                finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                try {
                                    finderDialog.dismiss();
                                    agregar[0] = true;
                                    if (agregar[0]) {
                                        ContentValues values = new ContentValues();
                                        values.put(ContactsContract.Data.DISPLAY_NAME,
                                                contact.getString("nombre"));
                                        Uri rawContactUri = contentResolver
                                                .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                        long rawContactId = ContentUris.parseId(rawContactUri);
                                        long contactId = ContentUris.parseId(rawContactUri);

                                        values.clear();
                                        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                                contact.getString("telefono"));
                                        values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                                ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                        values.put(Data.RAW_CONTACT_ID, rawContactId);
                                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                        .setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                finderDialog.dismiss();
                                agregar[0] = false;
                            }
                        });
            }
        } else {
            LayoutInflater dialogInflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            dialogView = dialogInflater.inflate(R.layout.add_contact_message, null);
            final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                    .setCancelable(true).setPositiveButton(R.string.add_contact_yes, null)
                    .setNegativeButton(R.string.add_contact_no, null);
            finderDialog = dialogBuilder.show();
            finderDialog.setCanceledOnTouchOutside(true);
            finderDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                finderDialog.dismiss();
                                agregar[0] = true;
                                if (agregar[0]) {
                                    ContentValues values = new ContentValues();
                                    values.put(ContactsContract.Data.DISPLAY_NAME, contact.getString("nombre"));
                                    Uri rawContactUri = contentResolver
                                            .insert(ContactsContract.RawContacts.CONTENT_URI, values);

                                    long rawContactId = ContentUris.parseId(rawContactUri);

                                    values.clear();
                                    values.put(android.provider.ContactsContract.Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,
                                            contact.getString("telefono"));
                                    values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
                                            ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                                    values.put(Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(Data.MIMETYPE, ContactsContract.Data.CONTENT_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                    values.clear();
                                    values.put(Data.MIMETYPE,
                                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                                    values.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                                            contact.getString("nombre"));
                                    values.put(Data.RAW_CONTACT_ID, rawContactId);
                                    contentResolver.insert(ContactsContract.Data.CONTENT_URI, values);

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
            finderDialog.getButton(DialogInterface.BUTTON_NEGATIVE)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finderDialog.dismiss();
                            agregar[0] = false;
                        }
                    });
        }
        c.close();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

protected boolean Sync(String service, String scope, String params) {
    final Date start = new Date();
    boolean hasError = false;
    if (params == null)
        params = "";
    final SQLiteDatabase db = mDB.getWritableDatabase();
    final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>();

    final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params);
    final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params);
    final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob);
    String serverBlob = null;/*w  w w  .ja va  2  s .  c  om*/
    Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?",
            new String[] { scopeServerBlob }, null, null, null);
    final String originalBlob;
    if (cur.moveToFirst()) {
        originalBlob = serverBlob = cur.getString(0);
    } else {
        originalBlob = null;
    }
    cur.close();
    db.beginTransaction();
    try {
        boolean nochanges = false;
        if (serverBlob != null) {
            nochanges = !contentHelper.hasDirtTable(db, scope);
        }
        boolean resolve = false;
        final Metadata meta = new Metadata();
        final HashMap<String, Object> vals = new HashMap<String, Object>();
        final ContentValues cv = new ContentValues(2);
        JsonFactory jsonFactory = new JsonFactory();
        JsonToken current = null;
        String name = null;
        boolean moreChanges = false;
        boolean forceMoreChanges = false;
        do {
            final int requestMethod;
            final String serviceRequestUrl;
            final ContentProducer contentProducer;

            if (serverBlob != null) {
                requestMethod = HTTP_POST;
                if (nochanges) {
                    serviceRequestUrl = download;
                } else {
                    serviceRequestUrl = upload;
                    forceMoreChanges = true;
                }
                contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges,
                        notifyTableInfo, contentHelper);
                nochanges = true;
            } else {
                requestMethod = HTTP_GET;
                serviceRequestUrl = download;
                contentProducer = null;

            }
            if (moreChanges) {
                db.beginTransaction();
            }

            Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer);
            if (result.getStatus() == HttpStatus.SC_OK) {
                final JsonParser jp = jsonFactory.createParser(result.getInputStream());

                jp.nextToken(); // skip ("START_OBJECT(d) expected");
                jp.nextToken(); // skip ("FIELD_NAME(d) expected");
                if (jp.nextToken() != JsonToken.START_OBJECT)
                    throw new Exception("START_OBJECT(d - object) expected");
                while (jp.nextToken() != JsonToken.END_OBJECT) {
                    name = jp.getCurrentName();
                    if (_.__sync.equals(name)) {
                        current = jp.nextToken();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            name = jp.getCurrentName();
                            current = jp.nextToken();
                            if (_.serverBlob.equals(name)) {
                                serverBlob = jp.getText();
                            } else if (_.moreChangesAvailable.equals(name)) {
                                moreChanges = jp.getBooleanValue() || forceMoreChanges;
                                forceMoreChanges = false;
                            } else if (_.resolveConflicts.equals(name)) {
                                resolve = jp.getBooleanValue();
                            }
                        }
                    } else if (_.results.equals(name)) {
                        if (jp.nextToken() != JsonToken.START_ARRAY)
                            throw new Exception("START_ARRAY(results) expected");
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            meta.isDeleted = false;
                            meta.tempId = null;
                            vals.clear();
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                name = jp.getCurrentName();
                                current = jp.nextToken();
                                if (current == JsonToken.VALUE_STRING) {
                                    vals.put(name, jp.getText());
                                } else if (current == JsonToken.VALUE_NUMBER_INT) {
                                    vals.put(name, jp.getLongValue());
                                } else if (current == JsonToken.VALUE_NUMBER_FLOAT) {
                                    vals.put(name, jp.getDoubleValue());
                                } else if (current == JsonToken.VALUE_FALSE) {
                                    vals.put(name, 0L);
                                } else if (current == JsonToken.VALUE_TRUE) {
                                    vals.put(name, 1L);
                                } else if (current == JsonToken.VALUE_NULL) {
                                    vals.put(name, null);
                                } else {
                                    if (current == JsonToken.START_OBJECT) {
                                        if (_.__metadata.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.uri.equals(name)) {
                                                    meta.uri = jp.getText();
                                                } else if (_.type.equals(name)) {
                                                    meta.type = jp.getText();
                                                } else if (_.isDeleted.equals(name)) {
                                                    meta.isDeleted = jp.getBooleanValue();
                                                } else if (_.tempId.equals(name)) {
                                                    meta.tempId = jp.getText();
                                                }
                                            }
                                        } else if (_.__syncConflict.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.isResolved.equals(name)) {
                                                } else if (_.conflictResolution.equals(name)) {
                                                } else if (_.conflictingChange.equals(name)) {
                                                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                        name = jp.getCurrentName();
                                                        current = jp.nextToken();
                                                        if (current == JsonToken.START_OBJECT) {
                                                            if (_.__metadata.equals(name)) {
                                                                while (jp.nextToken() != JsonToken.END_OBJECT) {

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // resolve conf

                                        } else if (_.__syncError.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                            TableInfo tab = contentHelper.getTableFromType(meta.type);
                            if (meta.isDeleted) {
                                tab.DeleteWithUri(meta.uri, db);
                            } else {
                                tab.SyncJSON(vals, meta, db);
                            }
                            if (!notifyTableInfo.contains(tab))
                                notifyTableInfo.add(tab);
                        }
                    }
                }
                jp.close();
                if (!hasError) {
                    cv.clear();
                    cv.put(BlobsTable.C_NAME, scopeServerBlob);
                    cv.put(BlobsTable.C_VALUE, serverBlob);
                    cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
                    cv.put(BlobsTable.C_STATE, 0);
                    db.replace(BlobsTable.NAME, null, cv);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    if (DEBUG) {
                        Log.d(TAG, "CP-Sync: commit changes");
                    }
                    final ContentResolver cr = getContext().getContentResolver();
                    for (TableInfo t : notifyTableInfo) {
                        final Uri nu = contentHelper.getDirUri(t.name, false);
                        cr.notifyChange(nu, null, false);
                        // false - do not force sync cause we are in sync
                        if (DEBUG) {
                            Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu);
                        }

                        for (String n : t.notifyUris) {
                            cr.notifyChange(Uri.parse(n), null, false);
                            if (DEBUG) {
                                Log.d(TAG, "+uri: " + n);
                            }
                        }
                    }
                    notifyTableInfo.clear();
                }
            } else {
                if (DEBUG) {
                    Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus());
                }
                hasError = true;
                break;
            }
        } while (moreChanges);
    } catch (final ConnectTimeoutException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ConnectTimeoutException", e);
        }
    } catch (final IOException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } catch (final ParseException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    } catch (final Exception e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    }
    if (hasError) {
        db.endTransaction();
        ContentValues cv = new ContentValues();
        cv.put(BlobsTable.C_NAME, scopeServerBlob);
        cv.put(BlobsTable.C_VALUE, originalBlob);
        cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
        cv.put(BlobsTable.C_STATE, -1);
        db.replace(BlobsTable.NAME, null, cv);
    }
    /*-if (!hasError) {
    final ContentValues cv = new ContentValues(2);
     cv.put(BlobsTable.C_NAME, scopeServerBlob);
     cv.put(BlobsTable.C_VALUE, serverBlob);
     db.replace(BlobsTable.NAME, null, cv);
     db.setTransactionSuccessful();
    }
    db.endTransaction();
    if (!hasError) {
     for (String t : notifyTableInfo) {
    getContext().getContentResolver().notifyChange(getDirUri(t),
          null);
     }
    }*/
    if (DEBUG) {
        Helpers.LogInfo(start);
    }
    return !hasError;
}

From source file:com.piusvelte.sonet.core.SonetService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else//from  w  ww . java  2 s.co  m
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(SonetService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(SonetService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(SonetService.this), values,
                                        Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(SonetService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Sonet.default_message_bg_color;
                                int profile_bg_color = Sonet.default_message_bg_color;
                                int friend_bg_color = Sonet.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Sonet.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(SonetService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(SonetService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(SonetService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Sonet.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(SonetService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Sonet.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(SonetService.this, widget,
                                                    Sonet.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(SonetService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(SonetService.this), values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(SonetService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(SonetService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(SonetService.this, 0, (Sonet
                                            .getPackageIntent(SonetService.this, SonetNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleService.java

private void start(Intent intent) {
    if (intent != null) {
        String action = intent.getAction();
        Log.d(TAG, "action:" + action);
        if (ACTION_REFRESH.equals(action)) {
            if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS))
                putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1);
            else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 1);
            else if (intent.getData() != null)
                putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1);
            else/*www .j  a  v a 2s . co m*/
                putValidatedUpdates(null, 0);
        } else if (LauncherIntent.Action.ACTION_READY.equals(action)) {
            if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION)
                    && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1);
                int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                // check if the scrollable needs to be built
                Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this),
                        new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?",
                        new String[] { Integer.toString(appWidgetId) }, null);
                if (widget.moveToFirst()) {
                    if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) {
                        ContentValues values = new ContentValues();
                        values.put(Widgets.SCROLLABLE, scrollableVersion);
                        // set the scrollable version
                        this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                                Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                    } else
                        putValidatedUpdates(new int[] { appWidgetId }, 1);
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Widgets.SCROLLABLE, scrollableVersion);
                    // set the scrollable version
                    this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values,
                            Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) });
                    putValidatedUpdates(new int[] { appWidgetId }, 1);
                }
                widget.close();
            } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
                // requery
                putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID) }, 0);
            }
        } else if (SMS_RECEIVED.equals(action)) {
            // parse the sms, and notify any widgets which have sms enabled
            Bundle bundle = intent.getExtras();
            Object[] pdus = (Object[]) bundle.get("pdus");
            for (int i = 0; i < pdus.length; i++) {
                SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
                AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() {

                    @Override
                    protected int[] doInBackground(SmsMessage... msg) {
                        // check if SMS is enabled anywhere
                        Cursor widgets = getContentResolver().query(
                                Widget_accounts_view.getContentUri(MyfeedleService.this),
                                new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET,
                                        Widget_accounts_view.ACCOUNT },
                                Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) },
                                null);
                        int[] appWidgetIds = new int[widgets.getCount()];
                        if (widgets.moveToFirst()) {
                            // insert this message to the statuses db and requery scrollable/rebuild widget
                            // check if this is a contact
                            String phone = msg[0].getOriginatingAddress();
                            String friend = phone;
                            byte[] profile = null;
                            Uri content_uri = null;
                            // unknown numbers crash here in the emulator
                            Cursor phones = getContentResolver().query(
                                    Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                                            Uri.encode(phone)),
                                    new String[] { ContactsContract.PhoneLookup._ID }, null, null, null);
                            if (phones.moveToFirst())
                                content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
                                        phones.getLong(0));
                            else {
                                Cursor emails = getContentResolver().query(
                                        Uri.withAppendedPath(
                                                ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI,
                                                Uri.encode(phone)),
                                        new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null,
                                        null);
                                if (emails.moveToFirst())
                                    content_uri = ContentUris.withAppendedId(
                                            ContactsContract.Contacts.CONTENT_URI, emails.getLong(0));
                                emails.close();
                            }
                            phones.close();
                            if (content_uri != null) {
                                // load contact
                                Cursor contacts = getContentResolver().query(content_uri,
                                        new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null,
                                        null);
                                if (contacts.moveToFirst())
                                    friend = contacts.getString(0);
                                contacts.close();
                                profile = getBlob(ContactsContract.Contacts
                                        .openContactPhotoInputStream(getContentResolver(), content_uri));
                            }
                            long accountId = widgets.getLong(2);
                            long id;
                            ContentValues values = new ContentValues();
                            values.put(Entities.ESID, phone);
                            values.put(Entities.FRIEND, friend);
                            values.put(Entities.PROFILE, profile);
                            values.put(Entities.ACCOUNT, accountId);
                            Cursor entity = getContentResolver().query(
                                    Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID },
                                    Entities.ACCOUNT + "=? and " + Entities.ESID + "=?",
                                    new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) },
                                    null);
                            if (entity.moveToFirst()) {
                                id = entity.getLong(0);
                                getContentResolver().update(Entities.getContentUri(MyfeedleService.this),
                                        values, Entities._ID + "=?", new String[] { Long.toString(id) });
                            } else
                                id = Long.parseLong(getContentResolver()
                                        .insert(Entities.getContentUri(MyfeedleService.this), values)
                                        .getLastPathSegment());
                            entity.close();
                            values.clear();
                            Long created = msg[0].getTimestampMillis();
                            values.put(Statuses.CREATED, created);
                            values.put(Statuses.ENTITY, id);
                            values.put(Statuses.MESSAGE, msg[0].getMessageBody());
                            values.put(Statuses.SERVICE, SMS);
                            while (!widgets.isAfterLast()) {
                                int widget = widgets.getInt(1);
                                appWidgetIds[widgets.getPosition()] = widget;
                                // get settings
                                boolean time24hr = true;
                                int status_bg_color = Myfeedle.default_message_bg_color;
                                int profile_bg_color = Myfeedle.default_message_bg_color;
                                int friend_bg_color = Myfeedle.default_friend_bg_color;
                                boolean icon = true;
                                int status_count = Myfeedle.default_statuses_per_account;
                                int notifications = 0;
                                Cursor c = getContentResolver().query(
                                        Widgets_settings.getContentUri(MyfeedleService.this),
                                        new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                Widgets.FRIEND_BG_COLOR },
                                        Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        null);
                                if (!c.moveToFirst()) {
                                    c.close();
                                    c = getContentResolver().query(
                                            Widgets_settings.getContentUri(MyfeedleService.this),
                                            new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                    Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND,
                                                    Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR,
                                                    Widgets.FRIEND_BG_COLOR },
                                            Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                            new String[] { Integer.toString(widget),
                                                    Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                            null);
                                    if (!c.moveToFirst()) {
                                        c.close();
                                        c = getContentResolver().query(
                                                Widgets_settings.getContentUri(MyfeedleService.this),
                                                new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR,
                                                        Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT,
                                                        Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS,
                                                        Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR },
                                                Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?",
                                                new String[] {
                                                        Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID),
                                                        Long.toString(Myfeedle.INVALID_ACCOUNT_ID) },
                                                null);
                                        if (!c.moveToFirst())
                                            initAccountSettings(MyfeedleService.this,
                                                    AppWidgetManager.INVALID_APPWIDGET_ID,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                        if (widget != AppWidgetManager.INVALID_APPWIDGET_ID)
                                            initAccountSettings(MyfeedleService.this, widget,
                                                    Myfeedle.INVALID_ACCOUNT_ID);
                                    }
                                    initAccountSettings(MyfeedleService.this, widget, accountId);
                                }
                                if (c.moveToFirst()) {
                                    time24hr = c.getInt(0) == 1;
                                    status_bg_color = c.getInt(1);
                                    icon = c.getInt(2) == 1;
                                    status_count = c.getInt(3);
                                    if (c.getInt(4) == 1)
                                        notifications |= Notification.DEFAULT_SOUND;
                                    if (c.getInt(5) == 1)
                                        notifications |= Notification.DEFAULT_VIBRATE;
                                    if (c.getInt(6) == 1)
                                        notifications |= Notification.DEFAULT_LIGHTS;
                                    profile_bg_color = c.getInt(7);
                                    friend_bg_color = c.getInt(8);
                                }
                                c.close();
                                values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr));
                                // update the bg and icon
                                // create the status_bg
                                values.put(Statuses.STATUS_BG, createBackground(status_bg_color));
                                // friend_bg
                                values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color));
                                // profile_bg
                                values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color));
                                values.put(Statuses.ICON,
                                        icon ? getBlob(getResources(), map_icons[SMS]) : null);
                                // insert the message
                                values.put(Statuses.WIDGET, widget);
                                values.put(Statuses.ACCOUNT, accountId);
                                getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this),
                                        values);
                                // check the status count, removing old sms
                                Cursor statuses = getContentResolver().query(
                                        Statuses.getContentUri(MyfeedleService.this),
                                        new String[] { Statuses._ID },
                                        Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?",
                                        new String[] { Integer.toString(widget), Long.toString(accountId) },
                                        Statuses.CREATED + " desc");
                                if (statuses.moveToFirst()) {
                                    while (!statuses.isAfterLast()) {
                                        if (statuses.getPosition() >= status_count) {
                                            getContentResolver().delete(
                                                    Statuses.getContentUri(MyfeedleService.this),
                                                    Statuses._ID + "=?", new String[] { Long.toString(statuses
                                                            .getLong(statuses.getColumnIndex(Statuses._ID))) });
                                        }
                                        statuses.moveToNext();
                                    }
                                }
                                statuses.close();
                                if (notifications != 0)
                                    publishProgress(Integer.toString(notifications),
                                            friend + " sent a message");
                                widgets.moveToNext();
                            }
                        }
                        widgets.close();
                        return appWidgetIds;
                    }

                    @Override
                    protected void onProgressUpdate(String... updates) {
                        int notifications = Integer.parseInt(updates[0]);
                        if (notifications != 0) {
                            Notification notification = new Notification(R.drawable.notification, updates[1],
                                    System.currentTimeMillis());
                            notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1],
                                    PendingIntent.getActivity(MyfeedleService.this, 0,
                                            (Myfeedle.getPackageIntent(MyfeedleService.this,
                                                    MyfeedleNotifications.class)),
                                            0));
                            notification.defaults |= notifications;
                            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                    .notify(NOTIFY_ID, notification);
                        }
                    }

                    @Override
                    protected void onPostExecute(int[] appWidgetIds) {
                        // remove self from thread list
                        if (!mSMSLoaders.isEmpty())
                            mSMSLoaders.remove(this);
                        putValidatedUpdates(appWidgetIds, 0);
                    }

                };
                mSMSLoaders.add(smsLoader);
                smsLoader.execute(msg);
            }
        } else if (ACTION_PAGE_DOWN.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_DOWN, 0));
        else if (ACTION_PAGE_UP.equals(action))
            (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()),
                    intent.getIntExtra(ACTION_PAGE_UP, 0));
        else {
            // this might be a widget update from the widget refresh button
            int appWidgetId;
            try {
                appWidgetId = Integer.parseInt(action);
                putValidatedUpdates(new int[] { appWidgetId }, 1);
            } catch (NumberFormatException e) {
                Log.d(TAG, "unknown action:" + action);
            }
        }
    }
}