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.sensapp.android.sensappdroid.fragments.ManageGraphSensorFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final String graphName = getArguments().getString(GRAPH_NAME);
    final Long graphID = getArguments().getLong(GRAPH_ID);
    cursor = getActivity().getContentResolver().query(SensAppContract.Sensor.CONTENT_URI, null, null, null,
            SensAppContract.Sensor.NAME + " ASC");
    Cursor cursorGraphSensor = getActivity().getContentResolver().query(
            Uri.parse(SensAppContract.GraphSensor.CONTENT_URI + "/graph/" + graphID), null, null, null,
            SensAppContract.GraphSensor.SENSOR + " ASC");
    String[] sensorNames = new String[cursor.getCount()];
    boolean[] sensorStatus = new boolean[cursor.getCount()];
    cursorGraphSensor.moveToFirst();//  ww w . j  a  v  a  2s.c  om
    int columnIDSensorName = cursor.getColumnIndexOrThrow(SensAppContract.Sensor.NAME);
    int columnIDGraphSensor = cursorGraphSensor.getColumnIndexOrThrow(SensAppContract.GraphSensor.SENSOR);
    for (int i = 0; cursor.moveToNext(); i++) {
        //Init sensorNames and put sensorStatus to true if the sensor is in the graph
        sensorNames[i] = cursor.getString(columnIDSensorName);
        if (!cursorGraphSensor.isAfterLast() && cursor.getString(columnIDSensorName)
                .equals(cursorGraphSensor.getString(columnIDGraphSensor))) {
            sensorStatus[i] = true;
        } else
            sensorStatus[i] = false;
        if (sensorStatus[i])
            cursorGraphSensor.moveToNext();

    }
    //Make and display the Dialog
    return new AlertDialog.Builder(getActivity()).setTitle("Add sensors to the graph " + graphName)
            .setMultiChoiceItems(sensorNames, sensorStatus, new DialogInterface.OnMultiChoiceClickListener() {
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    cursor.moveToPosition(which);
                    String sensorName = cursor
                            .getString(cursor.getColumnIndexOrThrow(SensAppContract.Sensor.NAME));
                    if (isChecked) {
                        sensorsRemoved.remove(sensorName);
                        sensorsAdded.add(sensorName);
                    } else {
                        sensorsAdded.remove(sensorName);
                        sensorsRemoved.add(sensorName);
                    }
                }
            }).setPositiveButton("Done", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    ContentValues values = new ContentValues();
                    for (String name : sensorsAdded) {
                        values.put(SensAppContract.GraphSensor.TITLE, name);
                        values.put(SensAppContract.GraphSensor.STYLE, GraphBaseView.LINECHART);
                        values.put(SensAppContract.GraphSensor.COLOR, Color.BLUE);
                        values.put(SensAppContract.GraphSensor.MAX, Integer.MAX_VALUE);
                        values.put(SensAppContract.GraphSensor.MIN, Integer.MIN_VALUE);
                        values.put(SensAppContract.GraphSensor.GRAPH, graphID);
                        values.put(SensAppContract.GraphSensor.SENSOR, name);
                        getActivity().getContentResolver().insert(SensAppContract.GraphSensor.CONTENT_URI,
                                values);
                        values.clear();
                    }
                    for (String name : sensorsRemoved) {
                        String where = SensAppContract.GraphSensor.SENSOR + " = \"" + name + "\" AND "
                                + SensAppContract.GraphSensor.GRAPH + " = " + graphID;
                        getActivity().getContentResolver().delete(SensAppContract.GraphSensor.CONTENT_URI,
                                where, null);
                    }
                    cursor.close();
                }
            }).create();
}

From source file:li.barter.http.HttpResponseParser.java

/**
 * Reads the location details from the Location response json into a content
 * values object//w w w  . j  a v  a 2  s  . c  o  m
 *
 * @param locationObject The Json representation of a location
 * @param values         The values instance to read into
 * @param clearBeforeAdd Whether the values should be emptied before adding
 * @return The location Id that was parsed
 * @throws JSONException If the Json is invalid
 */
private String readLocationDetailsIntoContentValues(final JSONObject locationObject, final ContentValues values,
        final boolean clearBeforeAdd) throws JSONException {

    if (clearBeforeAdd) {
        values.clear();
    }

    final String locationId = JsonUtils.readString(locationObject, HttpConstants.ID_LOCATION, true, true);
    values.put(DatabaseColumns.LOCATION_ID, locationId);
    values.put(DatabaseColumns.NAME, JsonUtils.readString(locationObject, HttpConstants.NAME, true, true));
    values.put(DatabaseColumns.ADDRESS,
            JsonUtils.readString(locationObject, HttpConstants.ADDRESS, true, true));
    values.put(DatabaseColumns.LATITUDE,
            JsonUtils.readDouble(locationObject, HttpConstants.LATITUDE, true, true));
    values.put(DatabaseColumns.LONGITUDE,
            JsonUtils.readDouble(locationObject, HttpConstants.LONGITUDE, true, true));

    mEndLatitude = JsonUtils.readDouble(locationObject, HttpConstants.LATITUDE, true, true);

    mEndLongitude = JsonUtils.readDouble(locationObject, HttpConstants.LONGITUDE, true, true);

    return locationId;
}

From source file:li.barter.http.HttpResponseParser.java

/**
 * Reads the book details from the Book response json into a content values
 * object/*from w  w  w . j  av  a  2s .  c  o  m*/
 *
 * @param bookObject     The Json representation of a book search result
 * @param values         The values instance to read into
 * @param clearBeforeAdd Whether the values should be emptied before adding
 * @param autoNotify     <code>true</code> to automatically notify any connected
 *                       loaders
 * @return The book Id that was parsed
 * @throws JSONException If the Json is invalid
 */
private String readUserDetailsIntoContentValues(final JSONObject bookObject, final ContentValues values,
        final boolean clearBeforeAdd, final boolean autoNotify) throws JSONException {

    if (clearBeforeAdd) {
        values.clear();
    }

    final String userId = JsonUtils.readString(bookObject, HttpConstants.ID_USER, true, true);

    values.put(DatabaseColumns.USER_ID, JsonUtils.readString(bookObject, HttpConstants.ID_USER, false, false));
    values.put(DatabaseColumns.FIRST_NAME,
            JsonUtils.readString(bookObject, HttpConstants.FIRST_NAME, false, false));
    values.put(DatabaseColumns.LAST_NAME,
            JsonUtils.readString(bookObject, HttpConstants.LAST_NAME, false, false));
    values.put(DatabaseColumns.PROFILE_PICTURE,
            JsonUtils.readString(bookObject, HttpConstants.IMAGE_URL, false, false));

    values.put(DatabaseColumns.DESCRIPTION,
            JsonUtils.readString(bookObject, HttpConstants.DESCRIPTION, false, false));

    final JSONObject locationObject = JsonUtils.readJSONObject(bookObject, HttpConstants.LOCATION, false,
            false);

    if (locationObject != null) {
        values.put(DatabaseColumns.LOCATION_ID, parseAndStoreLocation(locationObject, autoNotify));
    }

    return userId;
}

From source file:li.barter.http.HttpResponseParser.java

/**
 * Reads the book details from the Book response json into a content values
 * object//from ww w.  j  a  v  a 2  s  . c  om
 *
 * @param bookObject     The Json representation of a book search result
 * @param values         The values instance to read into
 * @param clearBeforeAdd Whether the values should be emptied before adding
 * @param autoNotify     <code>true</code> to automatically notify any connected
 *                       loaders
 * @return The book Id that was parsed
 * @throws JSONException If the Json is invalid
 */
private String readBookDetailsIntoContentValues(final JSONObject bookObject, final ContentValues values,
        final boolean clearBeforeAdd, final boolean autoNotify) throws JSONException {

    if (clearBeforeAdd) {
        values.clear();
    }

    final String bookId = JsonUtils.readString(bookObject, HttpConstants.ID_BOOK, false, false);

    final int id = JsonUtils.readInt(bookObject, HttpConstants.ID, true, true);
    Logger.d(TAG, "ID : " + id);
    values.put(DatabaseColumns.ID, id + "");
    values.put(DatabaseColumns.ISBN_10, JsonUtils.readString(bookObject, HttpConstants.ISBN_10, false, false));
    values.put(DatabaseColumns.ISBN_13, JsonUtils.readString(bookObject, HttpConstants.ISBN_13, false, false));
    values.put(DatabaseColumns.AUTHOR, JsonUtils.readString(bookObject, HttpConstants.AUTHOR, false, false));
    values.put(DatabaseColumns.USER_ID, JsonUtils.readString(bookObject, HttpConstants.ID_USER, false, false));
    values.put(DatabaseColumns.TITLE, JsonUtils.readString(bookObject, HttpConstants.TITLE, false, false));
    values.put(DatabaseColumns.DESCRIPTION,
            JsonUtils.readString(bookObject, HttpConstants.DESCRIPTION, false, false));

    final String imagePresent = JsonUtils.readString(bookObject, HttpConstants.IMAGE_PRESENT, false, false);
    if (imagePresent != null && imagePresent.equals("false")) {
        values.put(DatabaseColumns.IMAGE_URL,
                JsonUtils.readString(bookObject, HttpConstants.IMAGE_PRESENT, false, false));
    } else {
        values.put(DatabaseColumns.IMAGE_URL,
                JsonUtils.readString(bookObject, HttpConstants.IMAGE_URL, false, false));
    }
    values.put(DatabaseColumns.PUBLICATION_YEAR,
            JsonUtils.readString(bookObject, HttpConstants.PUBLICATION_YEAR, false, false));
    values.put(DatabaseColumns.PUBLICATION_MONTH,
            JsonUtils.readString(bookObject, HttpConstants.PUBLICATION_MONTH, false, false));
    values.put(DatabaseColumns.VALUE, JsonUtils.readString(bookObject, HttpConstants.VALUE, false, false));
    values.put(DatabaseColumns.BOOK_OWNER,
            JsonUtils.readString(bookObject, HttpConstants.OWNER_NAME, false, false));
    values.put(DatabaseColumns.BOOK_OWNER_IMAGE_URL,
            JsonUtils.readString(bookObject, HttpConstants.OWNER_IMAGE_URL, false, false));

    final JSONObject locationObject = JsonUtils.readJSONObject(bookObject, HttpConstants.LOCATION, false,
            false);

    if (locationObject != null) {
        values.put(DatabaseColumns.LOCATION_ID, parseAndStoreLocation(locationObject, autoNotify));
    }

    final JSONArray tagsArray = JsonUtils.readJSONArray(bookObject, HttpConstants.TAGS, true, true);

    if (tagsArray.length() > 0) {
        final String[] tags = new String[tagsArray.length()];

        for (int i = 0; i < tagsArray.length(); i++) {
            tags[i] = JsonUtils.readString(tagsArray, i, true, true);
        }

        values.put(DatabaseColumns.BARTER_TYPE, TextUtils.join(AppConstants.BARTER_TYPE_SEPARATOR, tags));
    }
    return id + "";
}

From source file:org.alfresco.mobile.android.application.fragments.sync.ResolveConflictSyncDialogFragment.java

private void move(Cursor c) {
    ContentValues cValues = new ContentValues();
    cValues.put(OperationSchema.COLUMN_STATUS, Operation.STATUS_RUNNING);
    getActivity().getContentResolver().update(SyncContentManager.getUri(syncId), cValues, null, null);

    // Current File
    Uri localFileUri = Uri.parse(c.getString(SyncContentSchema.COLUMN_LOCAL_URI_ID));
    File localFile = new File(localFileUri.getPath());
    String nodeIdentifier = c.getString(SyncContentSchema.COLUMN_NODE_ID_ID);

    // New File/*from  w w w .j  a  v a 2 s.  c  o m*/
    File parentFolder = AlfrescoStorageManager.getInstance(getActivity())
            .getDownloadFolder(SessionUtils.getAccount(getActivity()));
    File newLocalFile = new File(parentFolder, c.getString(SyncContentSchema.COLUMN_TITLE_ID));
    newLocalFile = IOUtils.createFile(newLocalFile);

    // Move to "Download"
    cValues.clear();
    if (localFile.renameTo(newLocalFile)) {
        getActivity().getContentResolver().delete(SyncContentManager.getUri(syncId), null, null);
    } else {
        cValues.put(OperationSchema.COLUMN_STATUS, SyncContentStatus.STATUS_FAILED);
        getActivity().getContentResolver().update(SyncContentManager.getUri(syncId), cValues, null, null);
    }

    SyncContentManager.getInstance(getActivity()).sync(SessionUtils.getAccount(getActivity()), nodeIdentifier);

    // Encrypt file if necessary
    AlfrescoStorageManager.getInstance(getActivity()).manageFile(newLocalFile);
    refreshSyncFragment();

    c.close();
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

protected static void updateProviderWithContactEntry(String account, Long syncLocalId, ContactEntry entry,
        ContentProvider provider) throws ParseException {
    final String name = entry.getTitle();
    final String notes = entry.getContent();
    final String yomiName = entry.getYomiName();
    final String personSyncId = lastItemFromUri(entry.getId());
    final String personSyncVersion = lastItemFromUri(entry.getEditUri());

    // Store the info about the person
    ContentValues values = new ContentValues();
    values.put(People.NAME, name);/*from  w  ww  .  ja va  2  s.co m*/
    values.put(People.NOTES, notes);
    values.put(People.PHONETIC_NAME, yomiName);
    values.put(SyncConstValue._SYNC_ACCOUNT, account);
    values.put(SyncConstValue._SYNC_ID, personSyncId);
    values.put(SyncConstValue._SYNC_DIRTY, "0");
    values.put(SyncConstValue._SYNC_LOCAL_ID, syncLocalId);
    values.put(SyncConstValue._SYNC_TIME, personSyncVersion);
    values.put(SyncConstValue._SYNC_VERSION, personSyncVersion);
    Uri personUri = provider.insert(People.CONTENT_URI, values);

    // Store the photo information
    final boolean photoExistsOnServer = !TextUtils.isEmpty(entry.getLinkPhotoHref());
    final String photoVersion = lastItemFromUri(entry.getLinkEditPhotoHref());
    values.clear();
    values.put(Photos.PERSON_ID, ContentUris.parseId(personUri));
    values.put(Photos.EXISTS_ON_SERVER, photoExistsOnServer ? 1 : 0);
    values.put(SyncConstValue._SYNC_ACCOUNT, account);
    values.put(SyncConstValue._SYNC_ID, personSyncId);
    values.put(SyncConstValue._SYNC_DIRTY, 0);
    values.put(SyncConstValue._SYNC_LOCAL_ID, syncLocalId);
    values.put(SyncConstValue._SYNC_TIME, photoVersion);
    values.put(SyncConstValue._SYNC_VERSION, photoVersion);
    if (provider.insert(Photos.CONTENT_URI, values) == null) {
        Log.e(TAG, "error inserting photo row, " + values);
    }

    // Store each email address
    for (Object object : entry.getEmailAddresses()) {
        EmailAddress email = (EmailAddress) object;
        values.clear();
        contactsElementToValues(values, email, ENTRY_TYPE_TO_PROVIDER_EMAIL);
        values.put(ContactMethods.DATA, email.getAddress());
        values.put(ContactMethods.KIND, Contacts.KIND_EMAIL);
        Uri uri = Uri.withAppendedPath(personUri, People.ContactMethods.CONTENT_DIRECTORY);
        provider.insert(uri, values);
    }

    // Store each postal address
    for (Object object : entry.getPostalAddresses()) {
        PostalAddress address = (PostalAddress) object;
        values.clear();
        contactsElementToValues(values, address, ENTRY_TYPE_TO_PROVIDER_POSTAL);
        values.put(ContactMethods.DATA, address.getValue());
        values.put(ContactMethods.KIND, Contacts.KIND_POSTAL);
        Uri uri = Uri.withAppendedPath(personUri, People.ContactMethods.CONTENT_DIRECTORY);
        provider.insert(uri, values);
    }

    // Store each im address
    for (Object object : entry.getImAddresses()) {
        ImAddress address = (ImAddress) object;
        values.clear();
        contactsElementToValues(values, address, ENTRY_TYPE_TO_PROVIDER_IM);
        values.put(ContactMethods.DATA, address.getAddress());
        values.put(ContactMethods.KIND, Contacts.KIND_IM);
        final byte protocolType = address.getProtocolPredefined();
        if (protocolType == ImAddress.PROTOCOL_NONE) {
            // don't add anything
        } else if (protocolType == ImAddress.PROTOCOL_CUSTOM) {
            values.put(ContactMethods.AUX_DATA,
                    ContactMethods.encodeCustomImProtocol(address.getProtocolCustom()));
        } else {
            Integer providerProtocolType = ENTRY_IM_PROTOCOL_TO_PROVIDER_PROTOCOL.get(protocolType);
            if (providerProtocolType == null) {
                throw new IllegalArgumentException("unknown protocol type, " + protocolType);
            }
            values.put(ContactMethods.AUX_DATA,
                    ContactMethods.encodePredefinedImProtocol(providerProtocolType));
        }
        Uri uri = Uri.withAppendedPath(personUri, People.ContactMethods.CONTENT_DIRECTORY);
        provider.insert(uri, values);
    }

    // Store each organization
    for (Object object : entry.getOrganizations()) {
        Organization organization = (Organization) object;
        values.clear();
        contactsElementToValues(values, organization, ENTRY_TYPE_TO_PROVIDER_ORGANIZATION);
        values.put(Organizations.COMPANY, organization.getName());
        values.put(Organizations.TITLE, organization.getTitle());
        values.put(Organizations.COMPANY, organization.getName());
        Uri uri = Uri.withAppendedPath(personUri, Organizations.CONTENT_DIRECTORY);
        provider.insert(uri, values);
    }

    // Store each group
    for (Object object : entry.getGroups()) {
        GroupMembershipInfo groupMembershipInfo = (GroupMembershipInfo) object;
        if (groupMembershipInfo.isDeleted()) {
            continue;
        }
        values.clear();
        values.put(GroupMembership.GROUP_SYNC_ACCOUNT, account);
        values.put(GroupMembership.GROUP_SYNC_ID, lastItemFromUri(groupMembershipInfo.getGroup()));
        Uri uri = Uri.withAppendedPath(personUri, GroupMembership.CONTENT_DIRECTORY);
        provider.insert(uri, values);
    }

    // Store each phone number
    for (Object object : entry.getPhoneNumbers()) {
        PhoneNumber phone = (PhoneNumber) object;
        values.clear();
        contactsElementToValues(values, phone, ENTRY_TYPE_TO_PROVIDER_PHONE);
        values.put(People.Phones.NUMBER, phone.getPhoneNumber());
        values.put(People.Phones.LABEL, phone.getLabel());
        Uri uri = Uri.withAppendedPath(personUri, People.Phones.CONTENT_DIRECTORY);
        provider.insert(uri, values);
    }

    // Store the extended properties
    for (Object object : entry.getExtendedProperties()) {
        ExtendedProperty extendedProperty = (ExtendedProperty) object;
        if (!"android".equals(extendedProperty.getName())) {
            continue;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(extendedProperty.getXmlBlob());
        } catch (JSONException e) {
            Log.w(TAG, "error parsing the android extended property, dropping, entry is " + entry.toString());
            continue;
        }
        Iterator jsonIterator = jsonObject.keys();
        while (jsonIterator.hasNext()) {
            String key = (String) jsonIterator.next();
            values.clear();
            values.put(Extensions.NAME, key);
            try {
                values.put(Extensions.VALUE, jsonObject.getString(key));
            } catch (JSONException e) {
                // this should never happen, since we just got the key from the iterator
            }
            Uri uri = Uri.withAppendedPath(personUri, People.Extensions.CONTENT_DIRECTORY);
            if (null == provider.insert(uri, values)) {
                Log.e(TAG, "Error inserting extension into provider, uri " + uri + ", values " + values);
            }
        }
        break;
    }
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * ?//from w  ww .j  av a 2s  .  c  o  m
 *
 * @param msg
 * @return
 */
public static int updateIMessageDownload(ECMessage msg) {
    if (msg == null || TextUtils.isEmpty(msg.getMsgId())) {
        return -1;
    }
    int row = -1;
    ContentValues values = new ContentValues();
    try {
        String where = IMessageColumn.MESSAGE_ID + " = '" + msg.getMsgId() + "'";
        ECFileMessageBody msgBody = (ECFileMessageBody) msg.getBody();
        values.put(IMessageColumn.FILE_PATH, msgBody.getLocalUrl());
        values.put(IMessageColumn.USER_DATA, msg.getUserData());
        if (msg.getType() == ECMessage.Type.VOICE) {
            int voiceTime = DemoUtils.calculateVoiceTime(msgBody.getLocalUrl());
            values.put(IMessageColumn.DURATION, voiceTime);
        }
        row = getInstance().sqliteDB().update(DatabaseHelper.TABLES_NAME_IM_MESSAGE, values, where, null);
        // notifyChanged(msgId);
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
        e.getStackTrace();
    } finally {
        if (values != null) {
            values.clear();
            values = null;
        }
    }
    return row;
}

From source file:com.pagenews.zhihudaily.homepage.ZhihuDailyPresenter.java

@Override
public void loadPosts(long date, final boolean clearing) {

    if (clearing) {
        view.showLoading();/* w w  w  . j av  a 2s . c  o m*/
    }

    if (NetworkState.networkConnected(context)) {

        model.load(Api.ZHIHU_HISTORY + formatter.ZhihuDailyDateFormat(date), new OnStringListener() {
            @Override
            public void onSuccess(String result) {

                try {
                    ZhihuDailyNews post = gson.fromJson(result, ZhihuDailyNews.class);
                    ContentValues values = new ContentValues();

                    if (clearing) {
                        list.clear();
                    }

                    for (ZhihuDailyNews.Question item : post.getStories()) {
                        list.add(item);
                        if (!queryIfIDExists(item.getId())) {
                            db.beginTransaction();
                            try {
                                DateFormat format = new SimpleDateFormat("yyyyMMdd");
                                Date date = format.parse(post.getDate());
                                values.put("zhihu_id", item.getId());
                                values.put("zhihu_news", gson.toJson(item));
                                values.put("zhihu_content", "");
                                values.put("zhihu_time", date.getTime() / 1000);
                                db.insert("Zhihu", null, values);
                                values.clear();
                                db.setTransactionSuccessful();
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                db.endTransaction();
                            }

                        }
                        Intent intent = new Intent("com.marktony.zhihudaily.LOCAL_BROADCAST");
                        intent.putExtra("type", CacheService.TYPE_ZHIHU);
                        intent.putExtra("id", item.getId());
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

                    }
                    view.showResults(list);
                } catch (JsonSyntaxException e) {
                    view.showError();
                }

                view.stopLoading();
            }

            @Override
            public void onError(VolleyError error) {
                view.stopLoading();
                view.showError();
            }
        });
    } else {

        if (clearing) {

            list.clear();

            Cursor cursor = db.query("Zhihu", null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    ZhihuDailyNews.Question question = gson.fromJson(
                            cursor.getString(cursor.getColumnIndex("zhihu_news")),
                            ZhihuDailyNews.Question.class);
                    list.add(question);
                } while (cursor.moveToNext());
            }
            cursor.close();
            view.stopLoading();
            view.showResults(list);

        } else {
            view.showError();
        }

    }
}

From source file:com.money.manager.ex.common.AllDataListFragment.java

private Money getTotalFromCursor(Cursor cursor) {
    Money total = MoneyFactory.fromString("0");
    int originalPosition = cursor.getPosition();
    AllDataAdapter adapter = getAllDataAdapter();
    CurrencyService currencyService = new CurrencyService(getContext());
    int baseCurrencyId = currencyService.getBaseCurrencyId();
    ContentValues values = new ContentValues();

    int currencyId;
    Money amount;/*from   ww  w  .j  a v  a2  s .co  m*/
    Money converted;
    String transType;
    TransactionTypes transactionType;

    cursor.moveToPosition(Constants.NOT_SET);

    while (cursor.moveToNext()) {
        values.clear();

        // Read needed data.
        DatabaseUtils.cursorStringToContentValues(cursor, adapter.TRANSACTIONTYPE, values);
        DatabaseUtils.cursorIntToContentValues(cursor, adapter.CURRENCYID, values);
        DatabaseUtils.cursorIntToContentValues(cursor, adapter.TOCURRENCYID, values);
        DatabaseUtils.cursorDoubleToCursorValues(cursor, adapter.AMOUNT, values);
        DatabaseUtils.cursorDoubleToCursorValues(cursor, adapter.TOAMOUNT, values);

        transType = values.getAsString(adapter.TRANSACTIONTYPE);
        transactionType = TransactionTypes.valueOf(transType);

        if (transactionType.equals(TransactionTypes.Transfer)) {
            currencyId = values.getAsInteger(adapter.TOCURRENCYID);
            amount = MoneyFactory.fromString(values.getAsString(adapter.TOAMOUNT));
        } else {
            currencyId = values.getAsInteger(adapter.CURRENCYID);
            amount = MoneyFactory.fromString(values.getAsString(adapter.AMOUNT));
        }

        converted = currencyService.doCurrencyExchange(baseCurrencyId, amount, currencyId);
        total = total.add(converted);
    }

    cursor.moveToPosition(originalPosition);

    return total;
}

From source file:com.pagenews.zhihudaily.homepage.DoubanMomentPresenter.java

@Override
public void loadPosts(long date, final boolean clearing) {

    if (clearing) {
        view.startLoading();/*from w  w  w.j av  a2  s . c o  m*/
    }

    if (NetworkState.networkConnected(context)) {

        model.load(Api.DOUBAN_MOMENT + new DateFormatter().DoubanDateFormat(date), new OnStringListener() {
            @Override
            public void onSuccess(String result) {

                try {
                    DoubanMomentNews post = gson.fromJson(result, DoubanMomentNews.class);
                    ContentValues values = new ContentValues();

                    if (clearing) {
                        list.clear();
                    }

                    for (DoubanMomentNews.posts item : post.getPosts()) {

                        list.add(item);

                        if (!queryIfIDExists(item.getId())) {
                            db.beginTransaction();
                            try {
                                values.put("douban_id", item.getId());
                                values.put("douban_news", gson.toJson(item));
                                DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                Date date = format.parse(item.getPublished_time());
                                values.put("douban_time", date.getTime() / 1000);
                                values.put("douban_content", "");
                                db.insert("Douban", null, values);
                                values.clear();
                                db.setTransactionSuccessful();
                            } catch (Exception e) {
                                e.printStackTrace();
                            } finally {
                                db.endTransaction();
                            }
                        }
                        Intent intent = new Intent("com.marktony.zhihudaily.LOCAL_BROADCAST");
                        intent.putExtra("type", CacheService.TYPE_DOUBAN);
                        intent.putExtra("id", item.getId());
                        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
                    }
                    view.showResults(list);
                } catch (JsonSyntaxException e) {
                    view.showLoadingError();
                }

                view.stopLoading();

            }

            @Override
            public void onError(VolleyError error) {
                view.stopLoading();
                view.showLoadingError();
            }
        });
    } else {

        if (clearing) {

            list.clear();

            Cursor cursor = db.query("Douban", null, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                do {
                    DoubanMomentNews.posts post = gson.fromJson(
                            cursor.getString(cursor.getColumnIndex("douban_news")),
                            DoubanMomentNews.posts.class);
                    list.add(post);
                } while (cursor.moveToNext());
            }
            cursor.close();
            view.stopLoading();
            view.showResults(list);
        }
    }
}