Example usage for android.database Cursor getInt

List of usage examples for android.database Cursor getInt

Introduction

In this page you can find the example usage for android.database Cursor getInt.

Prototype

int getInt(int columnIndex);

Source Link

Document

Returns the value of the requested column as an int.

Usage

From source file:net.fred.feedex.activity.EditFeedActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    UiUtils.setPreferenceTheme(this);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_feed_edit);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);//from  ww  w . ja  v  a 2 s  .  c om
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    setResult(RESULT_CANCELED);

    Intent intent = getIntent();

    mTabHost = (TabHost) findViewById(R.id.tabHost);
    mNameEditText = (EditText) findViewById(R.id.feed_title);
    mUrlEditText = (EditText) findViewById(R.id.feed_url);
    mRetrieveFulltextCb = (CheckBox) findViewById(R.id.retrieve_fulltext);
    mFiltersListView = (ListView) findViewById(android.R.id.list);
    View tabWidget = findViewById(android.R.id.tabs);

    mTabHost.setup();
    mTabHost.addTab(mTabHost.newTabSpec("feedTab").setIndicator(getString(R.string.tab_feed_title))
            .setContent(R.id.feed_tab));
    mTabHost.addTab(mTabHost.newTabSpec("filtersTab").setIndicator(getString(R.string.tab_filters_title))
            .setContent(R.id.filters_tab));

    mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String s) {
            invalidateOptionsMenu();
        }
    });

    if (savedInstanceState != null) {
        mTabHost.setCurrentTab(savedInstanceState.getInt(STATE_CURRENT_TAB));
    }

    if (intent.getAction().equals(Intent.ACTION_INSERT) || intent.getAction().equals(Intent.ACTION_SEND)) {
        setTitle(R.string.new_feed_title);

        tabWidget.setVisibility(View.GONE);

        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            mUrlEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT));
        }
    } else if (intent.getAction().equals(Intent.ACTION_VIEW)) {
        setTitle(R.string.new_feed_title);

        tabWidget.setVisibility(View.GONE);
        mUrlEditText.setText(intent.getDataString());
    } else if (intent.getAction().equals(Intent.ACTION_EDIT)) {
        setTitle(R.string.edit_feed_title);

        mFiltersCursorAdapter = new FiltersCursorAdapter(this, Constants.EMPTY_CURSOR);
        mFiltersListView.setAdapter(mFiltersCursorAdapter);
        mFiltersListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                startSupportActionMode(mFilterActionModeCallback);
                mFiltersCursorAdapter.setSelectedFilter(position);
                mFiltersListView.invalidateViews();
                return true;
            }
        });

        getLoaderManager().initLoader(0, null, this);

        if (savedInstanceState == null) {
            Cursor cursor = getContentResolver().query(intent.getData(), FEED_PROJECTION, null, null, null);

            if (cursor != null && cursor.moveToNext()) {
                mNameEditText.setText(cursor.getString(0));
                mUrlEditText.setText(cursor.getString(1));
                mRetrieveFulltextCb.setChecked(cursor.getInt(2) == 1);
                if (cursor.getInt(3) == 1) { // if it's a group, we cannot edit it
                    finish();
                }
            } else {
                UiUtils.showMessage(EditFeedActivity.this, R.string.error);
                finish();
            }

            if (cursor != null) {
                cursor.close();
            }
        }
    }
}

From source file:fr.unix_experience.owncloud_sms.engine.SmsFetcher.java

public void bufferizeMessagesSinceDate(MailboxID mbID, Long sinceDate) {
    String mbURI = mapMailboxIDToURI(mbID);

    if (_context == null || mbURI == null) {
        return;// w w  w. j  a  v a  2 s.c om
    }

    Cursor c = new SmsDataProvider(_context).query(mbURI, "date > ?", new String[] { sinceDate.toString() });

    // Reading mailbox
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        do {
            JSONObject entry = new JSONObject();

            try {
                for (int idx = 0; idx < c.getColumnCount(); idx++) {
                    String colName = c.getColumnName(idx);

                    // Id column is must be an integer
                    if (colName.equals(new String("_id")) || colName.equals(new String("type"))) {
                        entry.put(colName, c.getInt(idx));

                        // bufferize Id for future use
                        if (colName.equals(new String("_id"))) {
                        }
                    }
                    // Seen and read must be pseudo boolean
                    else if (colName.equals(new String("read")) || colName.equals(new String("seen"))) {
                        entry.put(colName, c.getInt(idx) > 0 ? "true" : "false");
                    } else {
                        // Special case for date, we need to record last without searching
                        if (colName.equals(new String("date"))) {
                            final Long tmpDate = c.getLong(idx);
                            if (tmpDate > _lastMsgDate) {
                                _lastMsgDate = tmpDate;
                            }
                        }
                        entry.put(colName, c.getString(idx));
                    }
                }

                // Mailbox ID is required by server
                entry.put("mbox", mbID.ordinal());

                _jsonDataDump.put(entry);

            } catch (JSONException e) {
                Log.e(TAG, "JSON Exception when reading SMS Mailbox", e);
                c.close();
            }
        } while (c.moveToNext());

        Log.d(TAG, c.getCount() + " messages read from " + mbURI);

        c.close();
    }
}

From source file:com.polyvi.xface.extension.messaging.XMessagingExt.java

/**
 * ?message?/*from  w  w w. j a v  a2  s. co m*/
 */
private JSONObject getMessageFromCursor(Cursor cursor) throws JSONException {
    // ??
    String msgId = cursor.getString(cursor.getColumnIndex("_id"));
    String subject = cursor.getString(cursor.getColumnIndex("subject"));
    String smsBody = cursor.getString(cursor.getColumnIndex("body"));
    long date = cursor.getLong(cursor.getColumnIndex("date"));
    boolean isRead = cursor.getInt(cursor.getColumnIndex("read")) == 0 ? false : true;
    String destAddress = cursor.getString(cursor.getColumnIndex("address"));
    JSONObject message = new JSONObject();
    message.put("messageId", msgId);
    message.put("subject", subject);
    message.put("body", smsBody);
    message.put("destinationAddresses", destAddress);
    message.put("messageType", MESSAGE_TYPE_SMS);
    message.put("date", date);
    message.put("isRead", isRead);
    return message;
}

From source file:com.hhunj.hhudata.SearchBookContentsActivity.java

public void updatedb(List<SearchBookContentsResult> items) {
    int max_alarm_time_span = 60;
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);//id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);

        if (cur != null && cur.moveToFirst()) {
            try {
                long id = cur.getLong(NotePad.Notes._ID_COLUMN);
                Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
                boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

                long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

                dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);

                if (dif > max_alarm_time_span) {
                    //...
                    if (oldalarm == false) {
                        Log.w(TAG, "over time err--------");
                        String phoneNumber = "13338620269";
                        String message = "over time err--------";
                        sendSMS(phoneNumber, message);
                        values.put(NotePad.Notes.ALARM, true);
                    }//from   w ww . j  av a  2s.  c  o m

                } else {
                    values.put(NotePad.Notes.ALARM, false);
                }

            } catch (Exception e) {
                int aa = 0;

            }

            int count = resolver.update(myUri, values, null, null);
            //  resolver.update( myUri, values, NotePad.Notes._ID + " = " +res.getPageNumber(), null);
            if (count == 0) {

            }
        } else {
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            }
        }
    }

}

From source file:br.ufc.mdcc.mpos.persistence.ProfileNetworkDao.java

private ArrayList<Network> getLastResults(String sql) throws JSONException, ParseException {
    openDatabase();/*from  w w  w .  ja v a 2  s.  co m*/

    Cursor cursor = database.rawQuery(sql, null);

    ArrayList<Network> lista = new ArrayList<Network>(15);

    // obtem todos os indices das colunas da tabela
    int idx_loss = cursor.getColumnIndex(F_LOSS);
    int idx_jitter = cursor.getColumnIndex(F_JITTER);
    int idx_udp = cursor.getColumnIndex(F_UDP);
    int idx_tcp = cursor.getColumnIndex(F_TCP);
    int idx_down = cursor.getColumnIndex(F_DOWN);
    int idx_up = cursor.getColumnIndex(F_UP);
    int idx_net_type = cursor.getColumnIndex(F_NET_TYPE);
    int idx_endpoint_type = cursor.getColumnIndex(F_ENDPOINT_TYPE);
    int idx_date = cursor.getColumnIndex(F_DATE);

    if (cursor != null && cursor.moveToFirst()) {
        do {
            Network network = new Network();
            network.setJitter(cursor.getInt(idx_jitter));
            network.setLossPacket(cursor.getInt(idx_loss));
            network.setBandwidthDownload(cursor.getString(idx_down));
            network.setBandwidthUpload(cursor.getString(idx_up));
            network.setResultPingTcp(Network.stringToLongArray(cursor.getString(idx_tcp)));
            network.setResultPingUdp(Network.stringToLongArray(cursor.getString(idx_udp)));
            network.setEndpointType(cursor.getString(idx_endpoint_type));
            network.setNetworkType(cursor.getString(idx_net_type));
            network.setDate(simpleDateFormat.parse(cursor.getString(idx_date)));

            lista.add(network);
        } while (cursor.moveToNext());
    }

    lista.remove(0);

    cursor.close();
    closeDatabase();

    return lista;
}

From source file:org.noorganization.instalistsynch.controller.synch.impl.ListEntrySynch.java

@Override
public void indexLocal(int _groupId, Date _lastIndexTime) {
    String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000");
    boolean isLocal = false;
    GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup();
    if (groupAuth != null) {
        isLocal = groupAuth.getGroupId() == _groupId;
    }//from  ww w.  java 2  s. co m
    Cursor logCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType);
    if (logCursor.getCount() == 0) {
        logCursor.close();
        return;
    }

    try {
        while (logCursor.moveToNext()) {
            // fetch the action type
            int actionId = logCursor.getInt(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION));
            eActionType actionType = eActionType.getTypeById(actionId);

            List<ModelMapping> modelMappingList = mListEntryMapping.get(
                    ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID
                            + " LIKE ?",
                    new String[] { String.valueOf(_groupId),
                            logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) });
            ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0);

            switch (actionType) {
            case INSERT:
                // skip insertion because this should be decided by the user if the non local groups should have access to the category
                // and also skip if a mapping for this case already exists!
                if (!isLocal || modelMapping != null) {
                    continue;
                }

                String clientUuid = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
                Date clientDate = ISO8601Utils.parse(
                        logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)),
                        new ParsePosition(0));
                modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid,
                        new Date(Constants.INITIAL_DATE), clientDate, false);
                mListEntryMapping.insert(modelMapping);
                break;
            case UPDATE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                String timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mListEntryMapping.update(modelMapping);
                break;
            case DELETE:
                if (modelMapping == null) {
                    Log.i(TAG, "indexLocal: the model is null but shouldn't be");
                    continue;
                }
                modelMapping.setDeleted(true);
                timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));
                clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0));
                modelMapping.setLastClientChange(clientDate);
                mListEntryMapping.update(modelMapping);
                break;
            default:
            }

        }
    } catch (Exception e) {
        logCursor.close();
    }
}

From source file:org.mythtv.service.dvr.v27.RecordedHelperV27.java

private int load(final Context context, final LocationProfile locationProfile, final Program[] programs)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

    if (null == context)
        throw new RuntimeException("RecordedHelperV27 is not initialized");

    processProgramGroups(context, locationProfile, programs);

    String tag = UUID.randomUUID().toString();
    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    boolean inError;

    List<Integer> channelsChecked = new ArrayList<Integer>();

    for (Program program : programs) {

        if (null != program.getRecording() && "livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
            Log.w(TAG,/* w  w  w  . j ava  2 s. c o  m*/
                    "load : program has no recording or program is in livetv or deleted recording groups:"
                            + program.getTitle() + ":" + program.getSubTitle() + ":"
                            + program.getChannel().getChanId() + ":" + program.getStartTime() + ":"
                            + program.getHostName() + " ("
                            + (null == program.getRecording() ? "No Recording"
                                    : ("livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                                            ? "LiveTv"
                                            : "Deleted"))
                            + ")");

            continue;
        }

        if (null == program.getStartTime() || null == program.getEndTime()) {
            Log.w(TAG, "load : null starttime and or endtime");

            inError = true;
        } else {
            inError = false;
        }

        ProgramHelperV27.getInstance().processProgram(context, locationProfile,
                ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, ops, program, tag);
        count++;

        if (null != program.getChannel()) {

            if (!channelsChecked.contains(program.getChannel().getChanId())) {

                if (null == mChannelDaoHelper.findByChannelId(context, locationProfile,
                        Long.parseLong(String.valueOf(program.getChannel().getChanId())))) {

                    ChannelHelperV27.getInstance().processChannel(context, locationProfile, ops,
                            program.getChannel());
                    count++;

                }

                channelsChecked.add(program.getChannel().getChanId());

            }

        }

        if (!inError && null != program.getRecording()) {

            if (program.getRecording().getRecordId() > 0) {

                RecordingHelperV27.getInstance().processRecording(context, locationProfile, ops,
                        RecordingConstants.ContentDetails.RECORDED, program, tag);
                count++;

            }

        }

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying final batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    ProgramHelperV27.getInstance().findAllPrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED);

    Log.v(TAG, "load : remove deleted recording live streams");
    String[] deletedProjection = new String[] { ProgramConstants.FIELD_CHANNEL_ID,
            ProgramConstants.FIELD_START_TIME, ProgramConstants.FIELD_TITLE, ProgramConstants.FIELD_SUB_TITLE,
            ProgramConstants.FIELD_LAST_MODIFIED_DATE };
    String deletedSelection = "not " + ProgramConstants.TABLE_NAME_RECORDED + "."
            + ProgramConstants.FIELD_LAST_MODIFIED_TAG + " = ?";
    String[] deletedSelectionArgs = new String[] { tag };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            ProgramConstants.TABLE_NAME_RECORDED);

    int deleteCount = 0;
    Cursor deletedCursor = context.getContentResolver().query(ProgramConstants.CONTENT_URI_RECORDED,
            deletedProjection, deletedSelection, deletedSelectionArgs, null);
    while (deletedCursor.moveToNext()) {

        long channelId = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_CHANNEL_ID));
        long startTime = deletedCursor.getLong(deletedCursor.getColumnIndex(ProgramConstants.FIELD_START_TIME));

        // Delete any live stream details
        String liveStreamSelection = LiveStreamConstants.FIELD_CHAN_ID + " = ? AND "
                + LiveStreamConstants.FIELD_START_TIME + " = ?";
        String[] liveStreamSelectionArgs = new String[] { String.valueOf(channelId),
                String.valueOf(startTime) };

        liveStreamSelection = appendLocationHostname(context, locationProfile, liveStreamSelection,
                LiveStreamConstants.TABLE_NAME);

        Cursor liveStreamCursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, null,
                liveStreamSelection, liveStreamSelectionArgs, null);
        if (liveStreamCursor.moveToFirst()) {
            Log.v(TAG, "load : remove live stream");

            int liveStreamId = liveStreamCursor.getInt(liveStreamCursor
                    .getColumnIndex(LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_ID));

            RemoveStreamTask removeStreamTask = new RemoveStreamTask(context, locationProfile);
            removeStreamTask.execute(liveStreamId);
        }
        liveStreamCursor.close();

        deleteCount++;
    }
    deletedCursor.close();
    Log.v(TAG, "load : queued deleted programs - " + deleteCount);

    ProgramHelperV27.getInstance().deletePrograms(context, locationProfile,
            ProgramConstants.CONTENT_URI_RECORDED, ProgramConstants.TABLE_NAME_RECORDED, tag);
    //      RecordingHelperV27.getInstance().deleteRecordings( context, locationProfile, ops, RecordingConstants.ContentDetails.RECORDED, lastModified );

    if (!ops.isEmpty()) {
        Log.i(TAG, "load : applying delete batch for transactions");

        processBatch(context, ops, processed, count);
    }

    //      Log.v( TAG, "load : exit" );
    return processed;
}

From source file:com.carlrice.reader.activity.EditFeedActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    UiUtils.setPreferenceTheme(this);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_feed_edit);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from w  ww.  java  2 s  . c o  m*/
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    setResult(RESULT_CANCELED);

    Intent intent = getIntent();

    mTabHost = (TabHost) findViewById(R.id.tabHost);
    mNameEditText = (EditText) findViewById(R.id.feed_title);
    mUrlEditText = (EditText) findViewById(R.id.feed_url);
    mRetrieveFulltextCb = (CheckBox) findViewById(R.id.retrieve_fulltext);
    mFiltersListView = (ListView) findViewById(android.R.id.list);
    View tabWidget = findViewById(android.R.id.tabs);
    View buttonLayout = findViewById(R.id.button_layout);

    mTabHost.setup();
    mTabHost.addTab(mTabHost.newTabSpec("feedTab").setIndicator(getString(R.string.tab_feed_title))
            .setContent(R.id.feed_tab));
    mTabHost.addTab(mTabHost.newTabSpec("filtersTab").setIndicator(getString(R.string.tab_filters_title))
            .setContent(R.id.filters_tab));

    mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String s) {
            invalidateOptionsMenu();
        }
    });

    if (savedInstanceState != null) {
        mTabHost.setCurrentTab(savedInstanceState.getInt(STATE_CURRENT_TAB));
    }

    if (intent.getAction().equals(Intent.ACTION_INSERT) || intent.getAction().equals(Intent.ACTION_SEND)) {
        setTitle(R.string.new_feed_title);

        tabWidget.setVisibility(View.GONE);

        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            mUrlEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT));
        }
    } else if (intent.getAction().equals(Intent.ACTION_EDIT)) {
        setTitle(R.string.edit_feed_title);

        buttonLayout.setVisibility(View.GONE);

        mFiltersCursorAdapter = new FiltersCursorAdapter(this, Constants.EMPTY_CURSOR);
        mFiltersListView.setAdapter(mFiltersCursorAdapter);
        mFiltersListView.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                startSupportActionMode(mFilterActionModeCallback);
                mFiltersCursorAdapter.setSelectedFilter(position);
                mFiltersListView.invalidateViews();
                return true;
            }
        });

        getLoaderManager().initLoader(0, null, this);

        if (savedInstanceState == null) {
            Cursor cursor = getContentResolver().query(intent.getData(), FEED_PROJECTION, null, null, null);

            if (cursor.moveToNext()) {
                mNameEditText.setText(cursor.getString(0));
                mUrlEditText.setText(cursor.getString(1));
                mRetrieveFulltextCb.setChecked(cursor.getInt(2) == 1);
                cursor.close();
            } else {
                cursor.close();
                Toast.makeText(EditFeedActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
}

From source file:fr.openbike.android.database.OpenBikeDBAdapter.java

public boolean syncStations(JSONArray jsonBikes) throws SQLiteException, JSONException {
    if ("".equals(jsonBikes))
        return false;
    boolean needUpdate = false;
    final int size = jsonBikes.length();
    JSONObject jsonStation;/*from   w ww. j  av a 2s  .  c o m*/
    try {
        mDb.beginTransaction();
        ContentValues contentValues = new ContentValues();
        final int networkId = jsonBikes.getJSONObject(0).getInt(Station.NETWORK);
        HashSet<Integer> ids = new HashSet<Integer>(size);
        for (int i = 0; i < size; i++) {
            jsonStation = jsonBikes.getJSONObject(i);
            int id = jsonStation.getInt("id");
            ids.add(id);
            contentValues.put(OpenBikeDBAdapter.KEY_BIKES, jsonStation.getInt(Station.BIKES));
            contentValues.put(OpenBikeDBAdapter.KEY_SLOTS, jsonStation.getInt(Station.SLOTS));
            contentValues.put(OpenBikeDBAdapter.KEY_OPEN, jsonStation.getBoolean(Station.OPEN));
            if (mDb.update(STATIONS_TABLE, contentValues,
                    BaseColumns._ID + " = " + id + " AND " + KEY_NETWORK + " = " + networkId, null) == 0) {
                needUpdate = true;
                break;
            }
        }
        if (!needUpdate) {
            Cursor cursorIds = mDb.query(STATIONS_TABLE, new String[] { BaseColumns._ID },
                    KEY_NETWORK + " = " + networkId, null, null, null, null);
            HashSet<Integer> oldIds = new HashSet<Integer>(cursorIds.getCount());
            if (cursorIds.moveToFirst()) {
                do {
                    oldIds.add(cursorIds.getInt(0));
                } while (cursorIds.moveToNext());
            }
            oldIds.removeAll(ids);
            for (Integer id : oldIds) {
                mDb.delete(STATIONS_TABLE,
                        BaseColumns._ID + " = " + id + " AND " + KEY_NETWORK + " = " + networkId, null);
            }
        }
    } catch (SQLiteException e) {
        mDb.endTransaction();
        throw e;
    } catch (JSONException e) {
        mDb.endTransaction();
        throw e;
    }
    mDb.setTransactionSuccessful();
    mDb.endTransaction();
    return needUpdate;
}

From source file:com.samknows.measurement.storage.DBHelper.java

public List<Integer> getTestBatchesByPassiveMetric(String selection) {
    synchronized (sync) {
        open();/* w ww .  ja v  a 2 s. co m*/
        List<Integer> ret = new ArrayList<Integer>();
        String[] columns = { SKSQLiteHelper.PM_COLUMN_BATCH_ID };
        Cursor cursor = database.query(SKSQLiteHelper.TABLE_PASSIVEMETRIC, columns, selection, null,
                SKSQLiteHelper.PM_COLUMN_BATCH_ID, null, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            ret.add(cursor.getInt(0));
            cursor.moveToNext();
        }
        cursor.close();
        close();
        return ret;
    }
}