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:com.app.uafeed.activity.EditFeedActivity.java

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

    getActionBar().setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.activity_feed_edit);
    setResult(RESULT_CANCELED);/* www  . j av  a2 s . com*/

    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, 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 (savedInstanceState == null) {
            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:de.fahrgemeinschaft.RideDetailsFragment.java

private void updateOptionsMenu() {
    Cursor cursor = getCursor();
    if (cursor != null && cursor.getCount() >= selected && edit != null && getActivity() != null) {
        cursor.moveToPosition(selected);
        if (isMyRide(cursor)) {
            edit.setVisible(true);//w ww  . j a  v  a2 s.c om
            delete.setVisible(true);
            duplicate.setVisible(true);
            duplicate_retour.setVisible(true);
            toggle_active.setVisible(true);
            if (cursor.getInt(COLUMNS.ACTIVE) == 1) {
                toggle_active.setTitle(R.string.deactivate);
            } else {
                toggle_active.setTitle(R.string.activate);
            }
        } else {
            edit.setVisible(false);
            delete.setVisible(false);
            duplicate.setVisible(false);
            duplicate_retour.setVisible(false);
            toggle_active.setVisible(false);
        }
    }
}

From source file:com.money.manager.ex.reports.IncomeVsExpensesListFragment.java

private void showChartInternal() {
    // take a adapter and cursor
    IncomeVsExpensesAdapter adapter = ((IncomeVsExpensesAdapter) getListAdapter());
    if (adapter == null)
        return;//from   ww  w  .j a v a2s .  com
    Cursor cursor = adapter.getCursor();
    if (cursor == null)
        return;
    // Move to the first record.
    if (cursor.getCount() <= 0)
        return;

    // arrays
    ArrayList<Double> incomes = new ArrayList<>();
    ArrayList<Double> expenses = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();

    // Reset cursor to initial position.
    cursor.moveToPosition(-1);
    // cycle cursor
    while (cursor.moveToNext()) {
        int month = cursor.getInt(cursor.getColumnIndex(IncomeVsExpenseReportEntity.Month));
        // check if not subtotal
        if (month != IncomeVsExpensesActivity.SUBTOTAL_MONTH) {
            // incomes and expenses
            incomes.add(cursor.getDouble(cursor.getColumnIndex(IncomeVsExpenseReportEntity.Income)));
            expenses.add(
                    Math.abs(cursor.getDouble(cursor.getColumnIndex(IncomeVsExpenseReportEntity.Expenses))));
            // titles
            int year = cursor.getInt(cursor.getColumnIndex(IncomeVsExpenseReportEntity.YEAR));

            // format month
            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month - 1, 1);
            // titles
            titles.add(Integer.toString(year) + "-" + new SimpleDateFormat("MMM").format(calendar.getTime()));
        }
    }
    //compose bundle for arguments
    Bundle args = new Bundle();
    args.putDoubleArray(IncomeVsExpensesChartFragment.KEY_EXPENSES_VALUES,
            ArrayUtils.toPrimitive(expenses.toArray(new Double[0])));
    args.putDoubleArray(IncomeVsExpensesChartFragment.KEY_INCOME_VALUES,
            ArrayUtils.toPrimitive(incomes.toArray(new Double[0])));
    args.putStringArray(IncomeVsExpensesChartFragment.KEY_XTITLES, titles.toArray(new String[titles.size()]));
    //get fragment manager
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
    if (fragmentManager != null) {
        IncomeVsExpensesChartFragment fragment;
        fragment = (IncomeVsExpensesChartFragment) fragmentManager
                .findFragmentByTag(IncomeVsExpensesChartFragment.class.getSimpleName());
        if (fragment == null) {
            fragment = new IncomeVsExpensesChartFragment();
        }
        fragment.setChartArguments(args);
        fragment.setDisplayHomeAsUpEnabled(true);

        if (fragment.isVisible())
            fragment.onResume();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        if (((IncomeVsExpensesActivity) getActivity()).mIsDualPanel) {
            fragmentTransaction.replace(R.id.fragmentChart, fragment,
                    IncomeVsExpensesChartFragment.class.getSimpleName());
        } else {
            fragmentTransaction.replace(R.id.fragmentMain, fragment,
                    IncomeVsExpensesChartFragment.class.getSimpleName());
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }
}

From source file:com.flowzr.export.FlowzrIntegrationTest.java

public void test_push_accounts() throws Exception {
    if (dba.em().getAllAccounts().getCount() < 1) {
        Currency c = createCurrency("CZK");
        com.flowzr.model.Account a = new com.flowzr.model.Account();
        a.title = "My Bank Account";
        a.type = AccountType.BANK.name();
        a.currency = c;//from  w  w  w .ja va 2s  .  c  o  m
        a.totalAmount = 23450;
        a.sortOrder = 50;
        a.cardIssuer = "card issuer";
        a.closingDay = 30;
        a.creationDate = 0;
        a.isActive = true;
        a.isIncludeIntoTotals = true;
        a.issuer = "issuer";
        a.limitAmount = 1000;
        a.note = "note";
        a.number = "6004300";
        a.paymentDay = 1;
        a.sortOrder = 1;
        a.id = -1;
        dba.em().saveAccount(a);
    }

    FlowzrSyncEngine.fixCreatedEntities();
    FlowzrSyncEngine.pushUpdate("currency", Currency.class);
    FlowzrSyncEngine.pushUpdate("account", com.flowzr.model.Account.class);

    JSONObject json = getJsonResponse(
            FlowzrSyncEngine.FLOWZR_API_URL + "admin_example.com/account/?last_sync_ts=0");
    JSONArray arr = json.getJSONArray("account");

    Cursor cursor = dba.em().getAllAccounts();

    assertEquals(valueOf(cursor.getCount()), valueOf(arr.length()));

    if (cursor.moveToFirst()) {
        do {
            //Log.i("flowzr", "account:" + cursor.getInt(0) + " " + cursor.getString(cursor.getColumnIndex("name")) + " " + cursor.getInt(cursor.getColumnIndex("remote_key")));
            // the view doesn't contains remote_key, the test is unoptimized
            com.flowzr.model.Account a = dba.em().getAccount(cursor.getInt(cursor.getColumnIndex("_id")));
            //em.load(Attribute.class, cursor.getInt(cursor.getColumnIndex("_id")));
            boolean gotIt = false;
            for (int i = 0; i < arr.length(); i++) {
                if (a.remoteKey.equals(arr.getJSONObject(i).getString("key"))) {
                    Log.i("flowzr", "got account " + a.title);
                    assertEquals(a.title, arr.getJSONObject(i).getString("name"));
                    assertEquals(a.type, arr.getJSONObject(i).getString("type"));
                    assertEquals(a.currency.name, arr.getJSONObject(i).getString("currency_name"));
                    assertEquals(a.sortOrder, arr.getJSONObject(i).getInt("sort_order"));
                    ;
                    if (a.cardIssuer != null) {
                        assertEquals(a.cardIssuer, arr.getJSONObject(i).getString("card_issuer"));
                    }
                    assertEquals(a.closingDay, arr.getJSONObject(i).getInt("closing_day"));
                    ;
                    assertFalse(a.isActive == arr.getJSONObject(i).getBoolean("hidden"));
                    assertEquals(a.isIncludeIntoTotals,
                            arr.getJSONObject(i).getBoolean("is_include_into_totals"));
                    if (a.issuer != null) {
                        assertEquals(a.issuer, arr.getJSONObject(i).getString("issuer"));
                    }
                    assertEquals(a.limitAmount, arr.getJSONObject(i).getInt("total_limit"));
                    if (a.note != null) {
                        assertEquals(a.note, arr.getJSONObject(i).getString("description"));
                    }
                    if (a.number != null) {
                        assertEquals(a.number, arr.getJSONObject(i).getString("code"));
                    }
                    assertEquals(a.paymentDay, arr.getJSONObject(i).getInt("payment_day"));
                    ;
                    assertEquals(a.sortOrder, arr.getJSONObject(i).getInt("sort_order"));
                    ;
                    gotIt = true;
                }
            }
            assertTrue(gotIt);
        } while (cursor.moveToNext());
    }
    cursor.close();
}

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

/**
 * Test that query for the next card in the schedule returns a valid result WITH a deck selector
 *//*from  w w w . j  a  va 2  s.  c o  m*/
public void testQueryCardFromCertainDeck() {
    long deckToTest = mTestDeckIds[0];
    String deckSelector = "deckID=?";
    String deckArguments[] = { Long.toString(deckToTest) };
    Collection col;
    col = CollectionHelper.getInstance().getCol(getContext());
    Sched sched = col.getSched();
    long selectedDeckBeforeTest = col.getDecks().selected();
    col.getDecks().select(1); //select Default deck

    Cursor reviewInfoCursor = getContext().getContentResolver().query(FlashCardsContract.ReviewInfo.CONTENT_URI,
            null, deckSelector, deckArguments, null);
    assertNotNull(reviewInfoCursor);
    assertEquals("Check that we actually received one card", 1, reviewInfoCursor.getCount());
    try {
        reviewInfoCursor.moveToFirst();
        int cardOrd = reviewInfoCursor
                .getInt(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.CARD_ORD));
        long noteID = reviewInfoCursor
                .getLong(reviewInfoCursor.getColumnIndex(FlashCardsContract.ReviewInfo.NOTE_ID));
        assertEquals("Check that the selected deck has not changed", 1, col.getDecks().selected());

        col.getDecks().select(deckToTest);
        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);
    } finally {
        reviewInfoCursor.close();
    }

    col.getDecks().select(selectedDeckBeforeTest);
}

From source file:org.mythtv.service.content.v25.LiveStreamHelperV25.java

private Integer countLiveStreamsNotComplete(final Context context, final LocationProfile locationProfile) {
    Log.d(TAG, "countLiveStreamsNotComplete : enter");

    String[] projection = new String[] {
            "count(" + LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants._ID + ")" };
    String selection = "NOT " + LiveStreamConstants.TABLE_NAME + "."
            + LiveStreamConstants.FIELD_PERCENT_COMPLETE + " = ?";
    String[] selectionArgs = new String[] { "100" };

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

    Integer count = null;//from w  ww  . ja va  2 s .co  m

    Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection, selection,
            selectionArgs, null);
    if (cursor.moveToFirst()) {
        //         Log.v( TAG, "findProgram : program=" + program.toString() );

        count = cursor.getInt(0);
    }
    cursor.close();

    Log.d(TAG, "countLiveStreamsNotComplete : exit");
    return null != count ? count : 0;
}

From source file:ru.orangesoftware.financisto.activity.FlowzrIntegrationTest.java

public void test_push_accounts() throws Exception {
    if (dba.em().getAllAccounts().getCount() < 1) {
        Currency c = createCurrency("CZK");
        ru.orangesoftware.financisto.model.Account a = new ru.orangesoftware.financisto.model.Account();
        a.title = "My Bank Account";
        a.type = AccountType.BANK.name();
        a.currency = c;//from w  ww.j a va 2  s  .co m
        a.totalAmount = 23450;
        a.sortOrder = 50;
        a.cardIssuer = "card issuer";
        a.closingDay = 30;
        a.creationDate = 0;
        a.isActive = true;
        a.isIncludeIntoTotals = true;
        a.issuer = "issuer";
        a.limitAmount = 1000;
        a.note = "note";
        a.number = "6004300";
        a.paymentDay = 1;
        a.sortOrder = 1;
        a.id = -1;
        dba.em().saveAccount(a);
    }

    FlowzrSyncEngine.fixCreatedEntities();
    FlowzrSyncEngine.pushUpdate("currency", Currency.class);
    FlowzrSyncEngine.pushUpdate("account", ru.orangesoftware.financisto.model.Account.class);

    JSONObject json = getJsonResponse(
            FlowzrSyncEngine.FLOWZR_API_URL + "admin_example.com/account/?last_sync_ts=0");
    JSONArray arr = json.getJSONArray("account");

    Cursor cursor = dba.em().getAllAccounts();

    assertEquals(valueOf(cursor.getCount()), valueOf(arr.length()));

    if (cursor.moveToFirst()) {
        do {
            //Log.i("flowzr", "account:" + cursor.getInt(0) + " " + cursor.getString(cursor.getColumnIndex("name")) + " " + cursor.getInt(cursor.getColumnIndex("remote_key")));
            // the view doesn't contains remote_key, the test is unoptimized
            ru.orangesoftware.financisto.model.Account a = dba.em()
                    .getAccount(cursor.getInt(cursor.getColumnIndex("_id")));
            //em.load(Attribute.class, cursor.getInt(cursor.getColumnIndex("_id")));
            boolean gotIt = false;
            for (int i = 0; i < arr.length(); i++) {
                if (a.remoteKey.equals(arr.getJSONObject(i).getString("key"))) {
                    Log.i("flowzr", "got account " + a.title);
                    assertEquals(a.title, arr.getJSONObject(i).getString("name"));
                    assertEquals(a.type, arr.getJSONObject(i).getString("type"));
                    assertEquals(a.currency.name, arr.getJSONObject(i).getString("currency_name"));
                    assertEquals(a.sortOrder, arr.getJSONObject(i).getInt("sort_order"));
                    ;
                    if (a.cardIssuer != null) {
                        assertEquals(a.cardIssuer, arr.getJSONObject(i).getString("card_issuer"));
                    }
                    assertEquals(a.closingDay, arr.getJSONObject(i).getInt("closing_day"));
                    ;
                    assertFalse(a.isActive == arr.getJSONObject(i).getBoolean("hidden"));
                    assertEquals(a.isIncludeIntoTotals,
                            arr.getJSONObject(i).getBoolean("is_include_into_totals"));
                    if (a.issuer != null) {
                        assertEquals(a.issuer, arr.getJSONObject(i).getString("issuer"));
                    }
                    assertEquals(a.limitAmount, arr.getJSONObject(i).getInt("total_limit"));
                    if (a.note != null) {
                        assertEquals(a.note, arr.getJSONObject(i).getString("description"));
                    }
                    if (a.number != null) {
                        assertEquals(a.number, arr.getJSONObject(i).getString("code"));
                    }
                    assertEquals(a.paymentDay, arr.getJSONObject(i).getInt("payment_day"));
                    ;
                    assertEquals(a.sortOrder, arr.getJSONObject(i).getInt("sort_order"));
                    ;
                    gotIt = true;
                }
            }
            assertTrue(gotIt);
        } while (cursor.moveToNext());
    }
    cursor.close();
}

From source file:com.android.unit_tests.CheckinProviderTest.java

@MediumTest
public void testCrashReport() throws Exception {
    long start = System.currentTimeMillis();
    ContentResolver r = getContext().getContentResolver();

    // Log a test (fake) crash report.
    Checkin.reportCrash(r, new CrashData("Test", "Test Activity", new BuildData("Test Build", "123", start),
            new ThrowableData(new RuntimeException("Test Exception"))));

    // Crashes aren't indexed; go through them all to find the one we added.
    Cursor c = r.query(Checkin.Crashes.CONTENT_URI, null, null, null, null);

    Uri uri = null;//from  w  w w  .  ja  v a2 s  .com
    while (c.moveToNext()) {
        String coded = c.getString(c.getColumnIndex(Checkin.Crashes.DATA));
        byte[] bytes = Base64.decodeBase64(coded.getBytes());
        CrashData crash = new CrashData(new DataInputStream(new ByteArrayInputStream(bytes)));

        // Should be exactly one recently added "Test" crash.
        if (crash.getId().equals("Test") && crash.getTime() > start) {
            assertEquals("Test Activity", crash.getActivity());
            assertEquals("Test Build", crash.getBuildData().getFingerprint());
            assertEquals("Test Exception", crash.getThrowableData().getMessage());

            assertNull(uri);
            uri = ContentUris.withAppendedId(Checkin.Crashes.CONTENT_URI,
                    c.getInt(c.getColumnIndex(Checkin.Crashes._ID)));
        }
    }
    assertNotNull(uri);
    c.close();

    // Update the "logs" column.
    ContentValues values = new ContentValues();
    values.put(Checkin.Crashes.LOGS, "Test Logs");
    assertEquals(1, r.update(uri, values, null, null));

    c = r.query(uri, null, null, null, null);
    assertTrue(c.moveToNext());
    String logs = c.getString(c.getColumnIndex(Checkin.Crashes.LOGS));
    assertEquals("Test Logs", logs);
    c.deleteRow();
    c.close();

    c.requery();
    assertFalse(c.moveToNext());
    c.close();
}

From source file:com.hichinaschool.flashcards.libanki.Card.java

/**
 * Reload Card details from db./*from  w  w  w .  java  2 s .  c  om*/
 * @return True if the load was successful, false if no card with such id was found.
 */
public boolean load() {
    Cursor cursor = null;
    try {
        cursor = mCol.getDb().getDatabase().rawQuery("SELECT * FROM cards WHERE id = " + mId, null);
        if (!cursor.moveToFirst()) {
            Log.w(AnkiDroidApp.TAG, "Card.load: No card with id " + mId);
            return false;
        }
        mId = cursor.getLong(0);
        mNid = cursor.getLong(1);
        mDid = cursor.getLong(2);
        mOrd = cursor.getInt(3);
        mMod = cursor.getLong(4);
        mUsn = cursor.getInt(5);
        mType = cursor.getInt(6);
        mQueue = cursor.getInt(7);
        mDue = cursor.getInt(8);
        mIvl = cursor.getInt(9);
        mFactor = cursor.getInt(10);
        mReps = cursor.getInt(11);
        mLapses = cursor.getInt(12);
        mLeft = cursor.getInt(13);
        mODue = cursor.getLong(14);
        mODid = cursor.getLong(15);
        mFlags = cursor.getInt(16);
        mData = cursor.getString(17);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    mQA = null;
    mNote = null;
    return true;
}

From source file:com.android.server.MaybeDatabaseHelper.java

public boolean hasEntries(String packagename) {
    if (!checkInitialized()) {
        return false;
    }/*from w ww .ja  v  a 2s. co  m*/

    Cursor cursor = null;
    boolean ret = false;

    try {
        /* cursor = sDatabase.query(APP_TABLE_NAME, new String[]{DATA_COL}, PACKAGE_COL+"="+packagename,
           null, null, null, null, null);
         */
        cursor = sDatabase.rawQuery("SELECT count(*) FROM " + APP_TABLE_NAME + " where " + PACKAGE_COL + " = ?",
                new String[] { packagename });
        /*
        if(cursor == null){
          Log.v(DBTAG, "cursor is null");
          return false;
        }
        ret = (cursor.moveToFirst() == true);
        */
        Log.v(DBTAG, "num columns|column" + cursor.getColumnCount() + "|" + cursor.getColumnName(0) + "|");
        cursor.moveToFirst();
        ret = (cursor.getInt(cursor.getColumnIndex("count(*)")) > 0);
        Log.v(DBTAG, "Package exists: Count:" + ret + cursor.getCount());
    } catch (IllegalStateException e) {
        Log.e(DBTAG, "IllegalStateException in hasEntries", e);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return ret;
}