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:org.noorganization.instalistsynch.controller.local.dba.impl.ClientLogDbController.java

@Override
public List<LogInfo> getElementByUuid(String _uuid, eActionType _actionType, eModelType _modelType,
        String _time) {/*from  w w  w . j  av a2s  . com*/
    Cursor cursor = mContentResolver.query(Uri.withAppendedPath(InstalistProvider.BASE_CONTENT_URI, "log"),
            LogInfo.COLUMN.ALL_COLUMNS,
            LogInfo.COLUMN.ITEM_UUID + " LIKE ? AND " + LogInfo.COLUMN.ACTION + " = ? AND "
                    + LogInfo.COLUMN.MODEL + " = ? AND " + LogInfo.COLUMN.ACTION_DATE + " >= ? ",
            new String[] { _uuid, String.valueOf(_actionType.ordinal()), String.valueOf(_modelType.ordinal()),
                    _time },
            null);
    if (cursor == null) {
        return new ArrayList<>();
    }

    if (cursor.getCount() == 0) {
        cursor.close();
        return new ArrayList<>();
    }

    List<LogInfo> list = new ArrayList<>(cursor.getCount());
    cursor.moveToFirst();
    try {
        do {
            int id = cursor.getInt(cursor.getColumnIndex(LogInfo.COLUMN.ID));
            String uuid = cursor.getString(cursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID));
            int action = cursor.getInt(cursor.getColumnIndex(LogInfo.COLUMN.ACTION));
            eActionType actionType = eActionType.getTypeById(action);
            int model = cursor.getInt(cursor.getColumnIndex(LogInfo.COLUMN.MODEL));
            eModelType modelType = eModelType.getTypeId(model);
            String date = cursor.getString(cursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE));

            list.add(new LogInfo(id, uuid, actionType, modelType,
                    ISO8601Utils.parse(date, new ParsePosition(0))));
        } while (cursor.moveToNext());
    } catch (ParseException e) {
        e.printStackTrace();
        return new ArrayList<>();
    } finally {
        cursor.close();
    }
    return list;
}

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 2s.co  m*/

    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:co.nerdart.ourss.activity.EditFeedActivity.java

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

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

    setContentView(R.layout.feed_edit);//w  ww. j  a  va 2  s.c  o m
    setResult(RESULT_CANCELED);

    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();
                Crouton.makeText(EditFeedActivity.this, R.string.error, Style.INFO);
                finish();
            }
        }
    }
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 * Get local version of issues /* w  w w. ja  v  a  2 s .  c o m*/
 * 
 * @return
 */
public VersionDB getVersion() {

    VersionDB mVersionDB = new VersionDB(0, null);

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_Version, null);

    if (cursor.moveToFirst())
        mVersionDB = new VersionDB(cursor.getInt(0), cursor.getString(1));

    cursor.close();
    if (db.isOpen())
        db.close();

    return mVersionDB;
}

From source file:se.kth.ssvl.tslab.bytewalla.androiddtn.servlib.storage.SQLiteImplementation.java

/**
 * Get the ids of all the bundles in a list.
 * @return Return List of bundle ids/* w w  w  . ja va2 s.  c  o  m*/
 */
public Iterator<Integer> get_all_bundles() {

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

    try {

        Cursor cursor = db.query("bundles", null, null, null, null, null, null, null);
        Log.d(TAG, "Reading Row");

        int idColumn = cursor.getColumnIndex("id");

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    list.add(cursor.getInt(idColumn));
                    Log.d(TAG, "Found it@:" + cursor.getInt(idColumn));
                } while (cursor.moveToNext());
            }
        } else {
            Log.d(TAG, "Row not found!");
            //   return "Not Found";
        }
        cursor.close();
    } catch (IndexOutOfBoundsException e) {
        Log.e(TAG, "Id Already deleted");
        //return "Not Found";
    } catch (SQLiteException e) {
        Log.e(TAG, "Coundn't run the query");
        //return "Not Found";
    } catch (Exception e) {
        Log.e(TAG, "General Exception");
        //return "Not Found";
    }

    return list.iterator();
}

From source file:com.weimed.app.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./*from  ww  w.ja  v  a2s.  c  o  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 updateLocalJSONData(final InputStream stream, final SyncResult syncResult)
        throws IOException, JSONException, RemoteException, OperationApplicationException, ParseException {
    final JSONParser JSONParser = new JSONParser();
    final ContentResolver contentResolver = getContext().getContentResolver();

    Log.i(TAG, "Parsing stream as JSON Array");
    final JSONObject json = JSONParser.parseJSONObject(stream);
    Log.i(TAG, "Parsing complete. Found " + json.getInt("total_rows") + " entries");

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

    // Build hash table of incoming entries
    HashMap<String, JSONObject> entryMap = new HashMap<String, JSONObject>();
    final JSONArray entries = json.getJSONArray("rows");
    for (int i = 0; i < json.getInt("total_rows"); i++) {
        JSONObject e = entries.getJSONObject(i).getJSONObject("value");
        entryMap.put(e.getString("_id"), e);
    }

    // Get list of all items
    Log.i(TAG, "Fetching local entries for merge");
    Uri uri = NewsContract.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 title;
    String content;
    String publisher;
    String picurl;
    String originalurl;
    String createdat;
    String updatedat;
    String publishedat;

    while (c.moveToNext()) {
        syncResult.stats.numEntries++;
        id = c.getInt(COLUMN_ID);
        entryId = c.getString(COLUMN_ENTRY_ID);
        title = c.getString(COLUMN_TITLE);
        content = c.getString(COLUMN_CONTENT);
        publisher = c.getString(COLUMN_PUBLISHER);
        picurl = c.getString(COLUMN_PICURL);
        originalurl = c.getString(COLUMN_ORIGINALURL);
        createdat = c.getString(COLUMN_CREATEDAT);
        updatedat = c.getString(COLUMN_UPDATEDAT);
        publishedat = c.getString(COLUMN_PUBLISHEDAT);
        JSONObject 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
        // How to know update local or remote? updatedAt! which is newer, update another.
        //                Uri existingUri = NewsContract.Entry.CONTENT_URI.buildUpon()
        //                                              .appendPath(Integer.toString(id)).build();
        //                if ((match.getString("title") != null && !match.getString("title").equals(title)) ||
        //                    (match.getString("content") != null && !match.getString("content").equals(content)) ||
        //                    (match.getString("publisher") != null && !match.getString("publisher").equals(publisher)) ||
        //                    (match.getString("picurl") != null && !match.getString("picurl").equals(picurl)) ||
        //                    (match.getString("originalurl") != null && !match.getString("originalurl").equals(originalurl)) ||
        //                    (match.getString("createdat") != null && !match.getString("createdat").equals(createdat)) ||
        //                    (match.getString("updatedat") != null && !match.getString("updatedat").equals(updatedat)) ||
        //                    (match.getString("publishedat") != null && !match.getString("publishedat").equals(publishedat))
        //                   ) {
        //                    // Update existing record
        //                    Log.i(TAG, "Scheduling update: " + existingUri);
        //                    batch.add(ContentProviderOperation.newUpdate(existingUri)
        //                         .withValue(NewsContract.Entry.COLUMN_TITLE, title)
        //                         .withValue(NewsContract.Entry.COLUMN_CONTENT, content)
        //                         .withValue(NewsContract.Entry.COLUMN_PUBLISHER, publisher)
        //                         .withValue(NewsContract.Entry.COLUMN_PICURL, picurl)
        //                         .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, originalurl)
        //                         .withValue(NewsContract.Entry.COLUMN_CREATEDAT, createdat)
        //                         .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, updatedat)
        //                         .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, publishedat)
        //                         .build());
        //                    syncResult.stats.numUpdates++;
        //                } else {
        //                    Log.i(TAG, "No action: " + existingUri);
        //                }
        //            } else {
        // Entry doesn't exist. Remove it from the database.
        Uri deleteUri = NewsContract.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 (JSONObject e : entryMap.values()) {
        Log.i(TAG, "Scheduling insert: entry_id=" + e.getString("_id"));
        batch.add(ContentProviderOperation.newInsert(NewsContract.Entry.CONTENT_URI)
                .withValue(NewsContract.Entry.COLUMN_ENTRY_ID, e.getString("_id"))
                .withValue(NewsContract.Entry.COLUMN_TITLE, e.getString("title"))
                .withValue(NewsContract.Entry.COLUMN_CONTENT,
                        fetchTextFileToString(NEWS_URL_BASE + '/' + e.getString("_id") + "/content.md"))
                .withValue(NewsContract.Entry.COLUMN_PUBLISHER, e.getString("publisher"))
                .withValue(NewsContract.Entry.COLUMN_PICURL, e.has("pic_link") ? e.getString("pic_link") : null)
                .withValue(NewsContract.Entry.COLUMN_ORIGINALURL, e.getString("origin_link"))
                .withValue(NewsContract.Entry.COLUMN_CREATEDAT, e.getString("created_at"))
                .withValue(NewsContract.Entry.COLUMN_UPDATEDAT, e.getString("updated_at"))
                .withValue(NewsContract.Entry.COLUMN_PUBLISHEDAT, e.getString("publish_at")).build());
        syncResult.stats.numInserts++;
    }
    Log.i(TAG, "Merge solution ready. Applying batch update");
    mContentResolver.applyBatch(NewsContract.CONTENT_AUTHORITY, batch);
    mContentResolver.notifyChange(NewsContract.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.mk4droid.IMC_Services.DatabaseHandler.java

/**
 * Get local version of categories table 
 * //from  w  ww  .  j  a  va 2  s .c o m
 * @return
 */
public VersionDB getCategVersion() {

    VersionDB mVersionDB = new VersionDB(0, null);

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CategVersion, null);

    if (cursor.moveToFirst())
        mVersionDB = new VersionDB(cursor.getInt(0), cursor.getString(1));

    cursor.close();
    if (db.isOpen())
        db.close();

    return mVersionDB;
}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 * Getting all issues./*from w ww  .j a v  a  2s . c  om*/
 * 
 * @return
 */
public ArrayList<Issue> getAllIssues() {
    ArrayList<Issue> mIssueL = new ArrayList<Issue>();
    // Select All Query
    String selectQuery = "SELECT * FROM " + TABLE_Issues + " ORDER BY " + KEY_IssueID + " DESC";

    if (!db.isOpen())
        db = this.getWritableDatabase();

    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            Issue mIssue = new Issue(cursor.getInt(0), cursor.getString(1), cursor.getInt(2),
                    cursor.getDouble(3), cursor.getDouble(4), cursor.getString(5), cursor.getString(6),
                    cursor.getString(7), cursor.getInt(8), cursor.getInt(9), cursor.getString(10),
                    cursor.getString(11), cursor.getString(12), cursor.getInt(13), cursor.getInt(14),
                    cursor.getString(15), cursor.getInt(16), cursor.getString(17), cursor.getInt(18),
                    cursor.getString(19));

            mIssueL.add(mIssue);
        } while (cursor.moveToNext());
    }

    cursor.close();
    return mIssueL;
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Test that query for the next card in the schedule returns a valid result without any deck selector
 *//*from  w w  w .  j  av  a 2s .c  o m*/
public void testQueryNextCard() {
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Sched sched = col.getSched();

    Cursor reviewInfoCursor = getContext().getContentResolver().query(FlashCardsContract.ReviewInfo.CONTENT_URI,
            null, null, null, null);
    assertNotNull(reviewInfoCursor);
    assertEquals("Check that we actually received one card", 1, reviewInfoCursor.getCount());

    reviewInfoCursor.moveToFirst();
    int cardOrd = reviewInfoCursor
            .getInt(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.CARD_ORD));
    long noteID = reviewInfoCursor
            .getLong(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.NOTE_ID));

    Card nextCard = null;
    for (int i = 0; i < 10; i++) {//minimizing fails, when sched.reset() randomly chooses between multiple cards
        sched.reset();
        nextCard = sched.getCard();
        if (nextCard.note().getId() == noteID && nextCard.getOrd() == cardOrd)
            break;
    }
    assertNotNull("Check that there actually is a next scheduled card", nextCard);
    assertEquals("Check that received card and actual card have same note id", nextCard.note().getId(), noteID);
    assertEquals("Check that received card and actual card have same card ord", nextCard.getOrd(), cardOrd);

}

From source file:com.rs.TCOfflineStatementCollection.java

/**
 * get all statements that haven't been posted
 * @param limit/*  w w  w.j  a  v  a  2s.com*/
 * @return List of LocalStatementsItem
 */
List<LocalStatementsItem> getUnsentStatements(int limit) {
    List<LocalStatementsItem> statementArray = new ArrayList<LocalStatementsItem>();

    Cursor cursor;
    SQLiteDatabase database;
    TCLocalStorageDatabaseOpenHelper dbHelper;
    dbHelper = new TCLocalStorageDatabaseOpenHelper(appContext);
    database = dbHelper.getWritableDatabase();

    String select = LocalStatements.POSTED_DATE + "=" + "\'" + "0" + "\'";

    cursor = database.query(TCOfflineDataManager.LOCAL_STATEMENT_TABLE_NAME, null, select, null, null, null,
            LocalStatements.CREATE_DATE + " ASC", Integer.toString(limit)); //query for all the unposted statements

    cursor.moveToFirst(); //go to the beginning of the query and then loop through all the packages, adding them to the return List
    while (!cursor.isAfterLast()) {
        LocalStatementsItem thisPackage = new LocalStatementsItem();
        thisPackage.id = cursor.getInt(0);
        thisPackage.statementId = cursor.getString(cursor.getColumnIndex("statementId"));
        thisPackage.statementJson = cursor.getString(cursor.getColumnIndex("statementJson"));
        thisPackage.createDate = cursor.getLong(cursor.getColumnIndex("createDate"));
        thisPackage.postedDate = cursor.getLong(cursor.getColumnIndex("postedDate"));
        thisPackage.querystring = cursor.getString(cursor.getColumnIndex("querystring"));

        statementArray.add(thisPackage);
        cursor.moveToNext();
    }

    cursor.close();
    database.close();

    return statementArray;
}