Example usage for android.database Cursor moveToNext

List of usage examples for android.database Cursor moveToNext

Introduction

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

Prototype

boolean moveToNext();

Source Link

Document

Move the cursor to the next row.

Usage

From source file:com.intel.xdk.contacts.Contacts.java

@SuppressWarnings("deprecation")
private String getAllContacts() {

    // Run query//from  ww w  .j  a  v a  2  s .c  o  m
    Uri uri = ContactsContract.Contacts.CONTENT_URI;
    String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.LOOKUP_KEY };
    String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + "1" + "'";
    String[] selectionArgs = null;
    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

    Cursor cursor = activity.managedQuery(uri, projection, selection, selectionArgs, sortOrder);
    //Cursor cursor = activity.getContentResolver().query(uri, null, null, null, null);

    String jsContacts = "[";

    if (cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            //GRAB CURRENT LOOKUP_KEY;   
            String lk = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
            String jsPerson = JSONValueForPerson(lk);
            jsContacts += jsPerson;
        }
    }

    jsContacts += "]";
    String js = " var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.internal.get',true,true);e.success=true;e.contacts="
            + jsContacts + ";document.dispatchEvent(e);";
    injectJS("javascript:" + js);

    return jsContacts;
}

From source file:se.lu.nateko.edca.svc.GetCapabilities.java

/**
 * Method that calls a geospatial server using a GetCapablities request and,
 * if successful, forwards the resulting XML object to the XML parser.
 * @return   Returns true if successful, otherwise false.
 *//*from w w  w  . j  a  va2  s .  c o  m*/
protected boolean getCapabilitiesRequest() {
    Log.d(TAG, "getCapabilitiesRequest() called.");

    /* Execute the HTTP request. */
    HttpGet httpGetMethod = new HttpGet(mServerURI);
    HttpResponse response;
    try {
        final HttpParams httpParameters = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT * 1000);
        HttpConnectionParams.setSoTimeout(httpParameters, TIME_OUT * 1000);

        response = mHttpClient.execute(httpGetMethod);
        Log.i(TAG, "GetCapabilities request made to server: " + httpGetMethod.getURI().toString());

        //          Log.v(TAG, "Length: " + response.getEntity().getContentLength() + ", Type: " + response.getEntity().getContentType() + ", Encoding: " + response.getEntity().getContentEncoding());

        InputStream xmlStream = response.getEntity().getContent();
        InputStreamReader reader = new InputStreamReader(xmlStream, "UTF-8");
        BufferedReader buffReader = new BufferedReader(reader, 4096);

        /* Remove all non-stored and inactive layers from the table to make room for the new result of the GetCapabilities XML parsing. */
        mService.clearRemoteLayers();

        /* Check for already stored layers so they are not duplicated. */
        Cursor storedCursor = mService.getSQLhelper().fetchData(LocalSQLDBhelper.TABLE_LAYER,
                LocalSQLDBhelper.KEY_LAYER_COLUMNS, LocalSQLDBhelper.ALL_RECORDS, null, true);
        mService.getActiveActivity().startManagingCursor(storedCursor);
        while (storedCursor.moveToNext()) {
            mStoredLayers.add(storedCursor.getString(1));
            Log.v(TAG, "Stored layer: " + storedCursor.getString(1));
        }

        try {
            Log.v(TAG, "Sending response (BufferedReader) to parser...");
            return parseXMLResponse(buffReader); // Send the HttpResponse as a Reader to parse its content.
        } finally {
            buffReader.close();
        }

    } catch (MalformedURLException e) {
        Log.e(TAG, e.toString());
        return false;
    } catch (IOException e) {
        Log.e(TAG, e.toString());
        return false;
    }
}

From source file:com.nolanlawson.cordova.sqlite.SQLitePlugin.java

private SQLitePLuginResult doSelectInBackgroundAndPossiblyThrow(String sql, String[] bindArgs,
        SQLiteDatabase db) {/*from   w w  w.java2  s . c  o m*/
    debug("\"all\" query: %s", sql);
    Cursor cursor = null;
    try {
        cursor = db.rawQuery(sql, bindArgs);
        int numRows = cursor.getCount();
        if (numRows == 0) {
            return EMPTY_RESULT;
        }
        int numColumns = cursor.getColumnCount();
        Object[][] rows = new Object[numRows][];
        String[] columnNames = cursor.getColumnNames();
        for (int i = 0; cursor.moveToNext(); i++) {
            Object[] row = new Object[numColumns];
            for (int j = 0; j < numColumns; j++) {
                row[j] = getValueFromCursor(cursor, j, cursor.getType(j));
            }
            rows[i] = row;
        }
        debug("returning %d rows", numRows);
        return new SQLitePLuginResult(rows, columnNames, 0, 0, null);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

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

public static void updateSubscribedFeeds(ContentResolver cr, String account) {
    Set<String> feedsToSync = Sets.newHashSet();
    feedsToSync.add(getGroupsFeedForAccount(account));
    addContactsFeedsToSync(cr, account, feedsToSync);

    Cursor c = SubscribedFeeds.Feeds.query(cr, sSubscriptionProjection,
            SubscribedFeeds.Feeds.AUTHORITY + "=? AND " + SubscribedFeeds.Feeds._SYNC_ACCOUNT + "=?",
            new String[] { Contacts.AUTHORITY, account }, null);
    try {//  ww w . ja  v  a 2s  .  c om
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "scanning over subscriptions with authority " + Contacts.AUTHORITY + " and account "
                    + account);
        }
        c.moveToNext();
        while (!c.isAfterLast()) {
            String feedInCursor = c.getString(1);
            if (feedsToSync.contains(feedInCursor)) {
                feedsToSync.remove(feedInCursor);
                c.moveToNext();
            } else {
                c.deleteRow();
            }
        }
        c.commitUpdates();
    } finally {
        c.close();
    }

    // any feeds remaining in feedsToSync need a subscription
    for (String feed : feedsToSync) {
        SubscribedFeeds.addFeed(cr, feed, account, Contacts.AUTHORITY, ContactsClient.SERVICE);

        // request a sync of this feed
        Bundle extras = new Bundle();
        extras.putString(ContentResolver.SYNC_EXTRAS_ACCOUNT, account);
        extras.putString("feed", feed);
        cr.startSync(Contacts.CONTENT_URI, extras);
    }
}

From source file:com.samsung.android.remindme.SyncAdapter.java

public List<ModelJava.Alert> getLocallyChangedAlerts(ContentProviderClient provider, Account account,
        Date sinceDate) throws RemoteException {
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Getting local alerts changed since " + Long.toString(sinceDate.getTime()));
    }// w  ww  .  j a  v  a2 s  . c  om
    Cursor alertsCursor = provider.query(RemindMeContract.buildAlertListUri(account.name), PROJECTION,
            RemindMeContract.Alerts.MODIFIED_DATE + " > ?", new String[] { Long.toString(sinceDate.getTime()) },
            null);

    List<ModelJava.Alert> locallyChangedAlerts = new ArrayList<ModelJava.Alert>();
    while (alertsCursor.moveToNext()) {
        ContentValues values = new ContentValues();
        DatabaseUtils.cursorRowToContentValues(alertsCursor, values);
        ModelJava.Alert changedAlert = new ModelJava.Alert(values);
        locallyChangedAlerts.add(changedAlert);
    }

    alertsCursor.close();
    return locallyChangedAlerts;
}

From source file:at.bitfire.davdroid.resource.LocalCollection.java

/**
 * Finds new resources (resources which haven't been uploaded yet).
 * New resources are 1) dirty, and 2) don't have an ETag yet.
 * Only records matching sqlFilter will be returned.
 * /*from w  ww . j  ava2 s  . c o  m*/
 * @return IDs of new resources
 * @throws LocalStorageException when the content provider couldn't be queried
 */
public long[] findNew() throws LocalStorageException {
    String where = entryColumnDirty() + "=1 AND " + entryColumnETag() + " IS NULL";
    if (entryColumnParentID() != null)
        where += " AND " + entryColumnParentID() + "=" + String.valueOf(getId());
    if (sqlFilter != null)
        where += " AND (" + sqlFilter + ")";
    try {
        @Cleanup
        Cursor cursor = providerClient.query(entriesURI(), new String[] { entryColumnID() }, where, null, null);
        if (cursor == null)
            throw new LocalStorageException("Couldn't query new records");

        long[] fresh = new long[cursor.getCount()];
        for (int idx = 0; cursor.moveToNext(); idx++) {
            long id = cursor.getLong(0);

            // new record: we have to generate UID + remote file name for uploading
            T resource = findById(id, false);
            resource.initialize();
            // write generated UID + remote file name into database
            ContentValues values = new ContentValues(2);
            values.put(entryColumnUID(), resource.getUid());
            values.put(entryColumnRemoteName(), resource.getName());
            providerClient.update(ContentUris.withAppendedId(entriesURI(), id), values, null, null);

            fresh[idx] = id;
        }
        return fresh;
    } catch (RemoteException ex) {
        throw new LocalStorageException(ex);
    }
}

From source file:com.ptts.sync.SyncAdapter.java

/**
 * Read JSON from an input stream, storing it into the content provider.
 *
 * <p>This is where incoming data is persisted, committing the results of a sync. In order to
 * minimize (expensive) disk operations, we compare incoming data with what's already in our
 * database, and compute a merge. Only changes (insert/update/delete) will result in a database
 * write./*  w  w w  . ja  va  2s.  co m*/
 *
 * <p>As an additional optimization, we use a batch operation to perform all database writes at
 * once.
 *
 * <p>Merge strategy:
 * 1. Get cursor to all items in feed<br/>
 * 2. For each item, check if it's in the incoming data.<br/>
 *    a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform
 *            database UPDATE.<br/>
 *    b. NO: Schedule DELETE from database.<br/>
 * (At this point, incoming database only contains missing items.)<br/>
 * 3. For any items remaining in incoming list, ADD to database.
 */
public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult)
        throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException {
    final FeedParserJson feedParser = new FeedParserJson();
    final ContentResolver contentResolver = getContext().getContentResolver();

    Log.i(TAG, "Parsing stream as Json feed");
    final List<FeedParserJson.Entry> entries = feedParser.parse(stream);
    Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries");

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

    // Build hash table of incoming entries
    HashMap<String, FeedParserJson.Entry> entryMap = new HashMap<String, FeedParserJson.Entry>();
    for (FeedParserJson.Entry e : entries) {
        entryMap.put(e.id, e);
    }

    // Get list of all items
    Log.i(TAG, "Fetching local entries for merge");
    Uri uri = FeedContract.Entry.CONTENT_URI; // Get all entries
    Cursor c = contentResolver.query(uri, PROJECTION, null, null, null);
    assert c != null;
    Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution...");

    // Find stale data
    int id;
    String entryId;
    String name;
    String start;
    String end;
    String stops;
    while (c.moveToNext()) {
        syncResult.stats.numEntries++;
        id = c.getInt(COLUMN_ID);
        entryId = c.getString(COLUMN_ENTRY_ID);
        name = c.getString(COLUMN_NAME);
        start = c.getString(COLUMN_START);
        end = c.getString(COLUMN_END);
        stops = c.getString(COLUMN_STOPS);

        Log.i("STOPS FROM PROJECTION", stops);

        FeedParserJson.Entry match = entryMap.get(entryId);
        if (match != null) {
            // Entry exists. Remove from entry map to prevent insert later.
            entryMap.remove(entryId);
            // Check to see if the entry needs to be updated
            Uri existingUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id))
                    .build();

            if ((match.name != null && !match.name.equals(name))
                    || (match.start != null && !match.start.equals(start))
                    || (match.stops != null && !match.stops.equals(stops)) || (match.end != end)) {

                Log.i("STOPS FROM HASHMAP", match.stops);
                if (!match.stops.equals(stops)) {
                    Log.i("COMPARING PROJECTION " + match.stops + " & HASHMAP " + stops,
                            "The two aren't equal");
                } else {
                    Log.i("COMPARING PROJECTION & HASHMAP", "The two are equal");
                }

                // Update existing record

                Log.i(TAG, "Scheduling update: " + existingUri);
                batch.add(ContentProviderOperation.newUpdate(existingUri)
                        .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, entryId)
                        .withValue(FeedContract.Entry.COLUMN_NAME_NAME, name)
                        .withValue(FeedContract.Entry.COLUMN_NAME_START, start)
                        .withValue(FeedContract.Entry.COLUMN_NAME_END, end)
                        .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, stops).build());
                syncResult.stats.numUpdates++;
            } else {
                Log.i(TAG, "No action: " + existingUri);
            }
        } else {
            // Entry doesn't exist. Remove it from the database.
            Uri deleteUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build();
            Log.i(TAG, "Scheduling delete: " + deleteUri);
            batch.add(ContentProviderOperation.newDelete(deleteUri).build());
            syncResult.stats.numDeletes++;
        }
    }
    c.close();

    // Add new items
    for (FeedParserJson.Entry e : entryMap.values()) {
        Log.i(TAG, "Scheduling insert: entry_id=" + e.id);
        batch.add(ContentProviderOperation.newInsert(FeedContract.Entry.CONTENT_URI)
                .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, e.id)
                .withValue(FeedContract.Entry.COLUMN_NAME_NAME, e.name)
                .withValue(FeedContract.Entry.COLUMN_NAME_START, e.start)
                .withValue(FeedContract.Entry.COLUMN_NAME_END, e.end)
                .withValue(FeedContract.Entry.COLUMN_NAME_STOPS, e.stops).build());
        syncResult.stats.numInserts++;
    }
    Log.i(TAG, "Merge solution ready. Applying batch update");
    mContentResolver.applyBatch(FeedContract.CONTENT_AUTHORITY, batch);
    mContentResolver.notifyChange(FeedContract.Entry.CONTENT_URI, // URI where data was modified
            null, // No local observer
            false); // IMPORTANT: Do not sync to network
    // This sample doesn't support uploads, but if *your* code does, make sure you set
    // syncToNetwork=false in the line above to prevent duplicate syncs.
}

From source file:com.ichi2.libanki.Tags.java

/**
 * FIXME: This method must be fixed before it is used. Its behaviour is currently incorrect.
 * This method is currently unused in AnkiDroid so it will not cause any errors in its current state.
 *///from   w ww  .  jav a 2  s.c  o  m
public void bulkAdd(List<Long> ids, String tags, boolean add) {
    List<String> newTags = split(tags);
    if (newTags == null || newTags.isEmpty()) {
        return;
    }
    // cache tag names
    register(newTags);
    // find notes missing the tags
    String l;
    if (add) {
        l = "tags not ";
    } else {
        l = "tags ";
    }
    StringBuilder lim = new StringBuilder();
    for (String t : newTags) {
        if (lim.length() != 0) {
            lim.append(" or ");
        }
        lim.append(l).append("like '% ").append(t).append(" %'");
    }
    Cursor cur = null;
    List<Long> nids = new ArrayList<Long>();
    ArrayList<Object[]> res = new ArrayList<Object[]>();
    try {
        cur = mCol.getDb().getDatabase().rawQuery(
                "select id, tags from notes where id in " + Utils.ids2str(ids) + " and (" + lim + ")", null);
        if (add) {
            while (cur.moveToNext()) {
                nids.add(cur.getLong(0));
                res.add(new Object[] { addToStr(tags, cur.getString(1)), Utils.intNow(), mCol.usn(),
                        cur.getLong(0) });
            }
        } else {
            while (cur.moveToNext()) {
                nids.add(cur.getLong(0));
                res.add(new Object[] { remFromStr(tags, cur.getString(1)), Utils.intNow(), mCol.usn(),
                        cur.getLong(0) });
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    // update tags
    mCol.getDb().executeMany("update notes set tags=:t,mod=:n,usn=:u where id = :id", res);
}

From source file:cn.edu.nju.dapenti.activity.EditFeedActivity.java

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

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.activity_feed_edit);
    setResult(RESULT_CANCELED);/*from   w w  w. j  a  v  a 2  s  . c om*/

    Intent intent = getIntent();

    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 filtersLayout = findViewById(R.id.filters_layout);
    View buttonLayout = findViewById(R.id.button_layout);

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

        filtersLayout.setVisibility(View.GONE);

        if (intent.hasExtra(Intent.EXTRA_TEXT)) {
            mUrlEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT));
        }

        restoreInstanceState(savedInstanceState);
    } else if (intent.getAction().equals(Intent.ACTION_EDIT)) {
        setTitle(R.string.edit_feed_title);

        buttonLayout.setVisibility(View.GONE);

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

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

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

            if (cursor.moveToNext()) {
                mPreviousName = cursor.getString(0);
                mNameEditText.setText(mPreviousName);
                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:cn.loveapple.client.android.database.impl.TemperatureDaoImpl.java

/**
 * {@inheritDoc}/*from  www .  j  a v a  2  s .co m*/
 */
@Override
public List<TemperatureEntity> findByTerm(String start, String end) {
    List<TemperatureEntity> result = null;

    Cursor cursor = null;
    try {
        writableDb = getWritableDb();

        cursor = writableDb.query(TABLE_NAME, null,
                "?<=" + COLUMN_DATE + " AND ?>=" + COLUMN_DATE + " ORDER BY " + COLUMN_DATE,
                new String[] { start, end }, null, null, null);
        result = new ArrayList<TemperatureEntity>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            result.add(getTemperatureEntity(cursor));
            cursor.moveToNext();
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return result;
}