Example usage for android.database Cursor getCount

List of usage examples for android.database Cursor getCount

Introduction

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

Prototype

int getCount();

Source Link

Document

Returns the numbers of rows in the cursor.

Usage

From source file:com.sqlite.multiread.java

public void run() {
    newSqLiteAdapter.openToRead();// w w  w . j  a  va2  s  . c  o m
    long seconds1 = 0;
    long seconds2 = 0;
    Cursor cur = null;
    Transactions transactions = new Transactions();
    ArrayList<Long> array = new ArrayList<Long>();
    for (int i = 0; i < 10; i++) {
        seconds1 = System.currentTimeMillis();
        //cur = newSqLiteAdapter.queueAll("dammyTable", false, false, false,
        //         false, false, false, true, threadNum);
        seconds2 = System.currentTimeMillis();
        array.add(seconds2 - seconds1);
    }
    //   newSqLiteAdapter.close();
    FileOutputStream fos = null;
    try {
        byte[] data = new String("\nTotal time: " + transactions.average_time(array) / 8 + "ms  Thread Id: "
                + currentThread().getId() + " I Have read " + cur.getCount()).getBytes();

        File file = new File(Environment.getExternalStorageDirectory() + "/Aaa/", "threadsResults.txt");

        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        FileLock lock = channel.lock();

        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {

        }

        fos = new FileOutputStream(file, true);
        fos.write(data);

        fos.flush();

        lock.release();
        channel.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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

/**
 * Check that querying the current model gives a valid result
 *//*from  w w  w .  j  a  v a2s . c o m*/
public void testQueryCurrentModel() {
    final ContentResolver cr = getContext().getContentResolver();
    Uri uri = Uri.withAppendedPath(FlashCardsContract.Model.CONTENT_URI,
            FlashCardsContract.Model.CURRENT_MODEL_ID);
    final Cursor modelCursor = cr.query(uri, null, null, null, null);
    assertNotNull(modelCursor);
    try {
        assertEquals("Check that there is exactly one result", 1, modelCursor.getCount());
        assertTrue("Move to beginning of cursor", modelCursor.moveToFirst());
        assertNotNull("Check non-empty field names",
                modelCursor.getString(modelCursor.getColumnIndex(FlashCardsContract.Model.FIELD_NAMES)));
        assertTrue("Check at least one template",
                modelCursor.getInt(modelCursor.getColumnIndex(FlashCardsContract.Model.NUM_CARDS)) > 0);
    } finally {
        modelCursor.close();
    }
}

From source file:com.google.android.dialer.provider.DialerProvider.java

private Cursor handleFilter(String[] projection, String filter, int limitInt, Location lastLocation) {
    if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
        Log.v("DialerProvider", "handleFilter(" + filter + ")");
    }/* w w  w .  j av a2 s. c  o  m*/

    if (filter != null) {
        JSONArray response = null;

        try {
            filter = URLDecoder.decode(filter, "UTF-8");
            ContentResolver resolver = getContext().getContentResolver();

            int minQueryLen = com.google.android.gsf.Gservices.getInt(resolver,
                    "dialer_nearby_places_min_query_len", 2);
            int maxQueryLen = com.google.android.gsf.Gservices.getInt(resolver,
                    "dialer_nearby_places_max_query_len", 50);
            int radius = com.google.android.gsf.Gservices.getInt(resolver,
                    "dialer_nearby_places_directory_radius_meters", 1000);

            int length = filter.length();
            if (length >= minQueryLen) {
                if (length > maxQueryLen) {
                    filter = filter.substring(0, maxQueryLen);
                }

                Uri.Builder builder = Uri
                        .parse(rewriteUrl("https://www.google.com/complete/search?gs_ri=dialer")).buildUpon()
                        .appendQueryParameter("q", filter).appendQueryParameter("hl",
                                getContext().getResources().getConfiguration().locale.getLanguage());

                builder = builder
                        .appendQueryParameter("sll",
                                String.format("%f,%f", lastLocation.getLatitude(), lastLocation.getLongitude()))
                        .appendQueryParameter("radius", Integer.toString(radius))
                        .appendQueryParameter("gs_gbg", getRandomNoiseString());

                response = getSuggestResponseInJsonArrayFormat(builder.build());

                if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                    Log.v("DialerProvider", "Results: " + response);
                }

                Cursor cur = buildResultCursor(projection, response, limitInt);
                if (Log.isLoggable("DialerProvider", Log.VERBOSE)) {
                    Log.v("DialerProvider", "handleFilter(" + filter + "): " + cur.getCount() + " matches");
                }

                return cur;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO: Something should probably go here
        } catch (IOException e) {
            Log.e("DialerProvider", "Failed to execute query", e);
        } catch (JSONException e) {
            Log.e("DialerProvider", "Invalid response to query: " + response, e);
        }
    }

    return null;
}

From source file:git.lawpavilionprime.auth._Login.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_);/*from ww w.  ja  v  a2 s. c  o  m*/

    mContext = _Login.this;
    txtEmail = (TextView) findViewById(R.id.email);
    txtPassword = (TextView) findViewById(R.id.password);
    btnLogin = (Button) findViewById(R.id.login);
    ckRememberMe = (CheckBox) findViewById(R.id.checkbox);
    txtForgotPassword = (TextView) findViewById(R.id.forgotPassword);
    txtSignUp = (TextView) findViewById(R.id.signUp);
    btnSignUp = (Button) findViewById(R.id.btnSignUp);

    validator = new Validator();
    config = new Config(_Login.this);
    dbAdapter = new UserDBAdapter(this);

    mProgressBar = (LinearLayout) findViewById(R.id.progressMum);
    txtProgressMessage = (TextView) findViewById(R.id.progressMessage);
    btnBkStore = (Button) findViewById(R.id.btnBkStore);
    baseUrl = "http://lawpavilionstore.com/android/login";

    dbAdapter.open(DB_NAME);

    dbAdapter.createUserTable();

    Cursor cursor = dbAdapter.fetch("SELECT * from " + dbAdapter.TABLE_NAME + " limit 1");
    if (cursor != null) {
        //new user
        if (cursor.getCount() == 1) {
            String loggedOut = cursor.getString(cursor.getColumnIndex(dbAdapter.LOG_OUT));
            if (loggedOut.equalsIgnoreCase("0")) {
                //User not looged out..continue
                String token = cursor.getString(cursor.getColumnIndex(dbAdapter.TOKEN));
                Toast.makeText(_Login.this, "Existing", Toast.LENGTH_SHORT).show();

                String set_up_status = cursor.getString(cursor.getColumnIndex(dbAdapter.SET_UP_STATUS));

                if (set_up_status.equalsIgnoreCase("pending")) {

                    Intent intent = new Intent(_Login.this, _Module.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    //TODO: remove this
                    //dbAdapter.executeQuery("DROP TABLE " + dbAdapter.TABLE_NAME + ";");
                    _Login.this.finish();
                } else {
                    Intent intent = new Intent(_Login.this, Dashboard.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    //TODO: remove this
                    //dbAdapter.executeQuery("DROP TABLE " + dbAdapter.TABLE_NAME + ";");
                    _Login.this.finish();
                }
            } else {
                //user has been forced to login..
                //check if gcm exist for user..
                SIGN_IN_TYPE = LOGGED_OUT_USER_TYPE;
            }
        } else {
            //try register GCM for new user
            Log.d("---LOG---", "GCM started");
            new RegisterApp(getApplicationContext()).execute();

            //New user account..
            SIGN_IN_TYPE = NEW_USER_TYPE;
        }
        cursor.close();
    } else {
        Toast.makeText(_Login.this, "DB error", Toast.LENGTH_SHORT).show();
        _Login.this.finish();
        //Do something here
    }
    dbAdapter.close();
    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            _email = txtEmail.getText().toString().trim();
            _password = txtPassword.getText().toString().trim();
            boolean isFieldSet = true;

            if (!validator.isValidEmail(_email)) {
                txtEmail.setError(Validator.emailErrorMessage);
                isFieldSet = false;
            }

            if (validator.isEmpty(_password)) {
                txtPassword.setError(Validator.defaultErrorMessage);
                isFieldSet = false;
            }
            //Toast.makeText(_Login.this, "Ready for Async Task", Toast.LENGTH_SHORT).show();

            if (isFieldSet) {
                connectIfInternetIsAvailable();
            } else {
                return;
            }
        }
    });
    txtForgotPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(_Login.this, _ForgotPassword.class);
            startActivity(intent);
        }
    });

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(_Login.this, _SignUp.class);
            startActivity(intent);
        }
    });

    //        txtSignUp.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //
    //                Intent intent = new Intent(_Login.this, _SignUp.class);
    //                startActivity(intent);
    //            }
    //        });
    btnBkStore.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(_Login.this, BookStore.class);
            startActivity(intent);
        }
    });
    mProgressBar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //no action
        }
    });
}

From source file:com.rukman.emde.smsgroups.syncadapter.SyncAdapter.java

private boolean shouldSyncNow(Account account, Bundle extras, ContentProviderClient provider,
        SyncResult syncResult) throws RemoteException {
    Cursor c = null;
    try {//from w ww .j ava  2 s  .  c  o m
        c = provider.query(GMSSyncs.CONTENT_URI, new String[] { GMSSync._ID, GMSSync.SYNC_DATE }, null, null,
                GMSSync.DEFAULT_SORT_ORDER);
        if (c == null) {
            syncResult.databaseError = true;
        } else if (c.getCount() == 0) {
            // Setup our group visibility on the very first sync
            GMSContactOperations.setAccountContactsVisibility(getContext(), account, true);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return true;
}

From source file:com.ericsender.android_nanodegree.popmovie.com.ericsender.android_nanodegree.popmovie.data.TestProvider.java

public void deleteAllRecordsFromProvider() {
    mContext.getContentResolver().delete(MovieContract.MovieEntry.CONTENT_URI, null, null);
    mContext.getContentResolver().delete(MovieContract.FavoriteEntry.CONTENT_URI, null, null);

    Cursor cursor = mContext.getContentResolver().query(MovieContract.MovieEntry.CONTENT_URI, null, null, null,
            null);/*from   w  w w  .j  a v  a  2s  . co  m*/
    assertEquals("Error: Records not deleted from Weather table during delete", 0, cursor.getCount());
    cursor.close();

    cursor = mContext.getContentResolver().query(MovieContract.FavoriteEntry.CONTENT_URI, null, null, null,
            null);
    assertEquals("Error: Records not deleted from Location table during delete", 0, cursor.getCount());
    cursor.close();
}

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 ww  w .  j a  va 2 s.  c om
    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.jsonstore.database.WritableDatabase.java

public int deleteIfRequired(JSONObject obj, boolean isErase, boolean exact) throws JSONException {
    boolean doErase = isErase; // start with the value that was passed in, override if necessary...
    boolean theEasyWay = true; // if there is an id, we have one object and can optimize the removal.
    int result = 0;
    int id = 0;/*from w  w w .j  a  v a 2 s.  c  o  m*/
    String operation = null;

    try { // try the easy way first, check if there is a single id.
        id = obj.getInt(DatabaseConstants.FIELD_ID);
        operation = findOperationForObjectById(id);
    } catch (JSONException e) { // No ID was found, it either means no object found or the object didn't contain an ID field.
        theEasyWay = false; // Have to find the object the "hard" way (via query, using the info in obj) 
    }

    if (theEasyWay) {
        if ((operation != null) && (operation.equals(DatabaseConstants.OPERATION_ADD))) {
            doErase = true; // ...and force it to "true" if a non-pushed add/store is pending. Don't tag as "pending remove", just delete it.
        }

        if (doErase) {
            // We're going to immediately delete the objects.
            result = delete(new String[] { DatabaseConstants.FIELD_ID },
                    new Object[] { obj.getInt(DatabaseConstants.FIELD_ID) });
        } else {
            // We're not immediately removing the objects, so just mark them as dirty and update the operation to "remove".
            result = update(
                    new String[] { DatabaseConstants.FIELD_DELETED, DatabaseConstants.FIELD_DIRTY,
                            DatabaseConstants.FIELD_OPERATION },
                    new Object[] { 1, new Date().getTime(), DatabaseConstants.OPERATION_REMOVE }, id);
        }
    } else { // we have to do it the hard way, with a query and possibly multiple matches to loop through, some of which may be marked add, some not.
        String strOp;
        int intId;
        int actionCount = 0;
        Cursor removeSet = null;
        int setSize;

        // Use the JSONObject info to query a list of matches.
        removeSet = findUsingQueryObject(obj,
                new String[] { DatabaseConstants.FIELD_ID, DatabaseConstants.FIELD_OPERATION },
                new String[] { DatabaseConstants.FIELD_DELETED + " = 0" }, null, null, exact); //$NON-NLS-1$

        // Loop through the matches to separate the objects marked "add" from those marked !"add"
        setSize = removeSet.getCount();

        for (int i = 0; i < setSize; ++i) {
            JSONObject item = new JacksonSerializedJSONObject();

            removeSet.moveToNext();

            // Get the ID and Operation fields from each object in the set returned by the query.
            intId = removeSet.getInt(0);
            strOp = removeSet.getString(1);

            if ((DatabaseConstants.OPERATION_ADD.compareToIgnoreCase(strOp) == 0) || (isErase)) {
                // Actually delete all the matches marked "add" (count them up for return)
                result = delete(new String[] { DatabaseConstants.FIELD_ID }, new Object[] { intId });
            } else {
                // Actually update all the matches marked !"add" (count them up for return)
                result = update(
                        new String[] { DatabaseConstants.FIELD_DELETED, DatabaseConstants.FIELD_DIRTY,
                                DatabaseConstants.FIELD_OPERATION },
                        new Object[] { 1, new Date().getTime(), DatabaseConstants.OPERATION_REMOVE }, intId);
            }
            actionCount += result; // Keep a running tally of the total number of objects deleted/marked for delete.
        }

        result = actionCount;
        removeSet.close();
    }

    return result;
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return 0;
    }//from  w ww . j a  va2  s  .  com
    String appSelection = DbObject.APP_ID + "= ?";
    String[] appSelectionArgs = new String[] { appId };
    selection = DBHelper.andClauses(selection, appSelection);
    selectionArgs = DBHelper.andArguments(selectionArgs, appSelectionArgs);
    String[] projection = new String[] { DbObject.HASH };

    int count = 0;
    Cursor c = mHelper.getReadableDatabase().query(DbObject.TABLE, projection, selection, selectionArgs, null,
            null, null);
    if (c != null && c.moveToFirst()) {
        count = c.getCount();
        long[] hashes = new long[count];
        int i = 0;
        do {
            hashes[i++] = c.getLong(0);
        } while (c.moveToNext());
        Helpers.sendToFeed(getContext(), DeleteObj.from(hashes, true), uri);
    }
    return count;
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public String getOnline(String buddyId) {
    int index = buddyId.indexOf('@');
    if (index >= 0) {
        buddyId = buddyId.substring(0, index);
    }/*from   w w  w . ja  v  a  2s .co  m*/
    SQLiteDatabase db = mDbHelper.getReadableDatabase();
    Cursor c = db.query(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS,
            new String[] { MessageHistoryContract.ChatEntry.COLUMN_NAME_LAST_ONLINE },
            MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID + "=?", new String[] { buddyId }, null, null,
            null);
    String result = null;
    try {
        c.moveToFirst();
        if (c.getCount() > 0)
            result = c.getString(0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    c.close();
    db.close();
    return result;
}