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

@Override
public List<LogInfo> getElementByUuid(String _uuid, eActionType _actionType, eModelType _modelType,
        String _time) {/* www .ja v  a  2s  .  co  m*/
    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:notused.Login.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);//  w  w w.j  a  v a  2s .  c  o m

    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);
    validator = new Validator();
    config = new Config(Login.this);
    dbAdapter = new UserDBAdapter(this);

    baseUrl = "http://lawpavilionstore.com/android/login";

    dbAdapter.open(DB_NAME);
    //TODO: remove drop table query
    dbAdapter.executeQuery("DROP TABLE IF EXISTS" + dbAdapter.TABLE_NAME + ";");
    //dbAdapter.createUserTable();

    Cursor cursor = dbAdapter.fetch("SELECT * from " + dbAdapter.TABLE_NAME);

    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();

                Login.this.finish();
                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);
                } else {
                    Intent intent = new Intent(Login.this, Dashboard.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }

            } else {
                //user has been forced to login..
                SIGN_IN_TYPE = LOGGED_OUT_USER_TYPE;
            }
        } else {
            //New user account..
            SIGN_IN_TYPE = NEW_USER_TYPE;
        }
    } else {
        Toast.makeText(Login.this, "DB error", Toast.LENGTH_SHORT).show();
        //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) {
                if (config.isConnectingToInternet()) {

                    AsyncLogin asyncLogin = new AsyncLogin();
                    asyncLogin.execute();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
                    builder.setTitle("Error");
                    builder.setMessage("Oops! Something went wrong!\n\nplease check your internet connection")
                            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            }).setPositiveButton("Retry", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AsyncLogin asyncLogin = new AsyncLogin();
                                    asyncLogin.execute();
                                }
                            });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }

            } else {
                return;
            }

        }
    });
    txtForgotPassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Login.this, ForgotPassword.class);
            startActivity(intent);
        }
    });

    txtSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(Login.this, SignUp.class);
            startActivity(intent);
        }
    });

}

From source file:org.bwgz.quotation.activity.QuotationActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    Log.d(TAG, String.format("onLoadFinished - loader: %s  cursor: %s (count: %d)", loader, cursor,
            cursor != null ? cursor.getCount() : 0));

    FragmentManager fragmentManager = getSupportFragmentManager();

    switch (loader.getId()) {
    case LOADER_ID_QUTOATION:
        if (fragmentManager != null) {
            QuotationFragment fragment = (QuotationFragment) fragmentManager
                    .findFragmentById(R.id.quotationFragment);

            if (fragment != null) {
                fragment.setQuotation(cursor);
            }//  ww  w.j  av a2  s .c o  m
        }
        if (cursor.getCount() != 0) {
            setLoadState(LoadState.LOADED);
        }
        break;
    case LOADER_ID_AUTHOR:
        if (fragmentManager != null) {
            AuthorFragment fragment = (AuthorFragment) fragmentManager.findFragmentById(R.id.authorFragment);
            if (fragment != null) {
                fragment.setAuthors(cursor);
            }
        }
        break;
    }
}

From source file:com.dileepindia.cordova.sms.SMSPlugin.java

protected void createContentObserver()

{
    Context ctx = this.cordova.getActivity();

    this.mObserver = new ContentObserver(new Handler()) {

        public void onChange(boolean selfChange) {
            onChange(selfChange, null);//  w  w  w .  j  a va2  s  .  co m
        }

        public void onChange(boolean selfChange, Uri uri) {
            Log.d("SMSPlugin", "onChange, selfChange: " + selfChange + ", uri: " + uri);

            int id = -1;

            if (uri != null) {
                String str = uri.toString();
                if (str.startsWith("content://sms/")) {
                    String box_or_id = str.substring("content://sms/".length());
                    try {
                        id = Integer.parseInt(str);
                        Log.d("SMSPlugin", "sms id: " + id);
                    } catch (NumberFormatException localNumberFormatException) {
                    }
                }
            }

            if (id == -1) {
                uri = Uri.parse("content://sms/inbox");
            }

            ContentResolver resolver = SMSPlugin.this.cordova.getActivity().getContentResolver();
            Cursor cur = resolver.query(uri, null, null, null, "_id desc");
            if (cur != null) {
                int n = cur.getCount();
                Log.d("SMSPlugin", "n = " + n);
                if ((n > 0) && (cur.moveToFirst())) {
                    JSONObject json = SMSPlugin.this.getJsonFromCursor(cur);
                    if (json != null) {
                        SMSPlugin.this.onSMSArrive(json);
                    } else {
                        Log.d("SMSPlugin", "fetch record return null");
                    }
                }
                cur.close();
            }

        }
    };
    ctx.getContentResolver().registerContentObserver(Uri.parse("content://sms/inbox"), true, this.mObserver);
    Log.d("SMSPlugin", "sms inbox observer registered");
}

From source file:com.aware.utils.WebserviceHelper.java

@Override
protected void onHandleIntent(Intent intent) {

    WEBSERVER = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_SERVER);
    DEVICE_ID = Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID);
    DEBUG = Aware.getSetting(getApplicationContext(), Aware_Preferences.DEBUG_FLAG).equals("true");
    DATABASE_TABLE = intent.getStringExtra(EXTRA_TABLE);
    TABLES_FIELDS = intent.getStringExtra(EXTRA_FIELDS);
    CONTENT_URI = Uri.parse(intent.getStringExtra(EXTRA_CONTENT_URI));

    //Fixed: not using webservices
    if (WEBSERVER.length() == 0)
        return;/*from w  w  w  .  j  a  v  a 2  s .com*/

    if (intent.getAction().equals(ACTION_AWARE_WEBSERVICE_SYNC_TABLE)) {

        //Check if we should do this only over Wi-Fi
        boolean wifi_only = Aware.getSetting(getApplicationContext(), Aware_Preferences.WEBSERVICE_WIFI_ONLY)
                .equals("true");
        if (wifi_only) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo active_network = cm.getActiveNetworkInfo();
            if (active_network != null && active_network.getType() != ConnectivityManager.TYPE_WIFI) {
                if (DEBUG) {
                    Log.i("AWARE", "User not connected to Wi-Fi, skipping data sync.");
                }
                return;
            }
        }

        //Check first if we have database table remotely, otherwise create it!
        ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>();
        fields.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
        fields.add(new BasicNameValuePair(EXTRA_FIELDS, TABLES_FIELDS));

        //Create table if doesn't exist on the remote webservice server
        HttpResponse response = new Https(getApplicationContext())
                .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/create_table", fields);
        if (response != null && response.getStatusLine().getStatusCode() == 200) {
            if (DEBUG) {
                HttpResponse copy = response;
                try {
                    if (DEBUG)
                        Log.d(Aware.TAG, EntityUtils.toString(copy.getEntity()));
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String[] columnsStr = new String[] {};
            Cursor columnsDB = getContentResolver().query(CONTENT_URI, null, null, null, null);
            if (columnsDB != null && columnsDB.moveToFirst()) {
                columnsStr = columnsDB.getColumnNames();
                if (DEBUG)
                    Log.d(Aware.TAG, "Total records on " + DATABASE_TABLE + ": " + columnsDB.getCount());
            }
            if (columnsDB != null && !columnsDB.isClosed())
                columnsDB.close();

            try {
                ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
                request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));

                //check the latest entry in remote database
                HttpResponse latest = new Https(getApplicationContext())
                        .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/latest", request);
                if (latest == null)
                    return;

                String data = "[]";
                try {
                    data = EntityUtils.toString(latest.getEntity());
                } catch (IllegalStateException e) {
                    Log.d(Aware.TAG, "Unable to connect to webservices...");
                }

                if (DEBUG) {
                    Log.d(Aware.TAG, "Webservice response: " + data);
                }

                //If in a study, get from joined date onwards
                String study_condition = "";
                if (Aware.getSetting(getApplicationContext(), "study_id").length() > 0
                        && Aware.getSetting(getApplicationContext(), "study_start").length() > 0) {
                    String study_start = Aware.getSetting(getApplicationContext(), "study_start");
                    study_condition = " AND timestamp > " + Long.parseLong(study_start);
                }
                if (DATABASE_TABLE.equalsIgnoreCase("aware_device"))
                    study_condition = "";

                JSONArray remoteData = new JSONArray(data);

                Cursor context_data;
                if (remoteData.length() == 0) {
                    if (exists(columnsStr, "double_end_timestamp")) {
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "double_end_timestamp != 0" + study_condition, null, "timestamp ASC");
                    } else if (exists(columnsStr, "double_esm_user_answer_timestamp")) {
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "double_esm_user_answer_timestamp != 0" + study_condition, null,
                                "timestamp ASC");
                    } else {
                        context_data = getContentResolver().query(CONTENT_URI, null, "1" + study_condition,
                                null, "timestamp ASC");
                    }
                } else {
                    long last = 0;
                    if (exists(columnsStr, "double_end_timestamp")) {
                        last = remoteData.getJSONObject(0).getLong("double_end_timestamp");
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "timestamp > " + last + " AND double_end_timestamp != 0" + study_condition,
                                null, "timestamp ASC");
                    } else if (exists(columnsStr, "double_esm_user_answer_timestamp")) {
                        last = remoteData.getJSONObject(0).getLong("double_esm_user_answer_timestamp");
                        context_data = getContentResolver().query(
                                CONTENT_URI, null, "timestamp > " + last
                                        + " AND double_esm_user_answer_timestamp != 0" + study_condition,
                                null, "timestamp ASC");
                    } else {
                        last = remoteData.getJSONObject(0).getLong("timestamp");
                        context_data = getContentResolver().query(CONTENT_URI, null,
                                "timestamp > " + last + study_condition, null, "timestamp ASC");
                    }
                }

                JSONArray context_data_entries = new JSONArray();
                if (context_data != null && context_data.moveToFirst()) {
                    if (DEBUG)
                        Log.d(Aware.TAG, "Uploading " + context_data.getCount() + " from " + DATABASE_TABLE);

                    do {
                        JSONObject entry = new JSONObject();

                        String[] columns = context_data.getColumnNames();
                        for (String c_name : columns) {

                            //Skip local database ID
                            if (c_name.equals("_id"))
                                continue;

                            if (c_name.equals("timestamp") || c_name.contains("double")) {
                                entry.put(c_name, context_data.getDouble(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("float")) {
                                entry.put(c_name, context_data.getFloat(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("long")) {
                                entry.put(c_name, context_data.getLong(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("blob")) {
                                entry.put(c_name, context_data.getBlob(context_data.getColumnIndex(c_name)));
                            } else if (c_name.contains("integer")) {
                                entry.put(c_name, context_data.getInt(context_data.getColumnIndex(c_name)));
                            } else {
                                entry.put(c_name, context_data.getString(context_data.getColumnIndex(c_name)));
                            }
                        }
                        context_data_entries.put(entry);

                        if (context_data_entries.length() == 1000) {
                            request = new ArrayList<NameValuePair>();
                            request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
                            request.add(new BasicNameValuePair("data", context_data_entries.toString()));
                            new Https(getApplicationContext())
                                    .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/insert", request);

                            context_data_entries = new JSONArray();
                        }
                    } while (context_data.moveToNext());

                    if (context_data_entries.length() > 0) {
                        request = new ArrayList<NameValuePair>();
                        request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
                        request.add(new BasicNameValuePair("data", context_data_entries.toString()));
                        new Https(getApplicationContext())
                                .dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/insert", request);
                    }
                } else {
                    if (DEBUG)
                        Log.d(Aware.TAG,
                                "Nothing new in " + DATABASE_TABLE + "!" + " URI=" + CONTENT_URI.toString());
                }

                if (context_data != null && !context_data.isClosed())
                    context_data.close();

            } catch (ParseException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //Clear database table remotely
    if (intent.getAction().equals(ACTION_AWARE_WEBSERVICE_CLEAR_TABLE)) {
        ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
        request.add(new BasicNameValuePair(Aware_Preferences.DEVICE_ID, DEVICE_ID));
        new Https(getApplicationContext()).dataPOST(WEBSERVER + "/" + DATABASE_TABLE + "/clear_table", request);
    }
}

From source file:com.navjagpal.fileshare.WebServer.java

private boolean isValidCookie(String cookie) {
    Cursor cursor = mCookiesDatabase.query("cookies", new String[] { "value" },
            "name = ? and value = ? and expiry > ?",
            new String[] { "id", cookie, "" + (int) System.currentTimeMillis() / 1000 }, null, null, null);
    boolean isValid = cursor.getCount() > 0;
    cursor.close();//from   w  ww  . j  a va  2s.c o  m
    return isValid;
}

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;
    }/*  w ww  .  ja v a2  s  .c o  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:com.polyvi.xface.extension.XMessagingExt.java

/**
 * ????/*from  w  w w .  java  2  s .c  o m*/
 */
private int getRecordCount(Uri queryUri, String selection, String[] selectionArgs)
        throws InvalidParameterException {
    ContentResolver resolver = getContext().getContentResolver();
    Cursor cursor = resolver.query(queryUri, new String[] { BaseColumns._ID }, selection, selectionArgs, null);
    if (null == cursor) {
        throw new InvalidParameterException();
    }
    final int count = cursor.getCount();
    cursor.close();
    return count;
}

From source file:com.yohpapa.research.simplemusicplayer.plugins.ListManager.java

/**
 * @see CordovaPlugin/*  w  w w. j  ava 2 s.c om*/
 * @param action
 * @param args
 * @param callbackContext
 * @return
 * @throws JSONException
 */
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    if ("get_album_info".equals(action)) {
        final Context context = cordova.getActivity().getApplicationContext();

        cordova.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                ContentResolver resolver = context.getContentResolver();
                Cursor cursor = null;
                try {
                    cursor = resolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                            new String[] { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM,
                                    MediaStore.Audio.Albums.NUMBER_OF_SONGS, MediaStore.Audio.Albums.ARTIST,
                                    MediaStore.Audio.Albums.ALBUM_ART, },
                            null, null, MediaStore.Audio.Albums.ALBUM + " ASC");

                    if (cursor == null || !cursor.moveToFirst()) {
                        callbackContext.error("The cursor is invalid.");
                        return;
                    }

                    JSONArray results = new JSONArray();
                    do {
                        JSONObject obj = new JSONObject();
                        obj.put("id", CursorHelper.getLong(cursor, MediaStore.Audio.Albums._ID));
                        obj.put("name", CursorHelper.getString(cursor, MediaStore.Audio.Albums.ALBUM));
                        obj.put("numTracks",
                                CursorHelper.getInt(cursor, MediaStore.Audio.Albums.NUMBER_OF_SONGS));
                        obj.put("artist", CursorHelper.getString(cursor, MediaStore.Audio.Albums.ARTIST));
                        obj.put("artwork", CursorHelper.getString(cursor, MediaStore.Audio.Albums.ALBUM_ART));

                        results.put(obj);

                    } while (cursor.moveToNext());

                    callbackContext.success(results);

                } catch (JSONException e) {
                    callbackContext.error(e.toString());
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                }
            }
        });
        return true;

    } else if ("get_track_info".equals(action)) {
        final long albumId = args.getLong(0);
        final Context context = cordova.getActivity().getApplicationContext();

        cordova.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                ContentResolver resolver = context.getContentResolver();
                Cursor albumCursor = null;
                Cursor trackCursor = null;

                try {
                    albumCursor = resolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                            new String[] { MediaStore.Audio.Albums.ALBUM, MediaStore.Audio.Albums.ALBUM_ART, },
                            MediaStore.Audio.Albums._ID + "=?", new String[] { String.valueOf(albumId) }, null);

                    if (albumCursor == null || !albumCursor.moveToFirst() || albumCursor.getCount() != 1) {
                        callbackContext.error("The album's cursor is invalid.");
                        return;
                    }

                    trackCursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                            new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE,
                                    MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
                                    MediaStore.Audio.Media.DURATION, },
                            MediaStore.Audio.Media.ALBUM_ID + "=?", new String[] { String.valueOf(albumId) },
                            MediaStore.Audio.Media.TRACK + " ASC");

                    if (trackCursor == null || !trackCursor.moveToFirst()) {
                        callbackContext.error("The cursor is invalid.");
                        return;
                    }

                    JSONObject result = new JSONObject();
                    result.put("album", CursorHelper.getString(albumCursor, MediaStore.Audio.Albums.ALBUM));
                    result.put("artwork",
                            CursorHelper.getString(albumCursor, MediaStore.Audio.Albums.ALBUM_ART));

                    JSONArray tracks = new JSONArray();
                    do {
                        JSONObject obj = new JSONObject();
                        obj.put("id", CursorHelper.getLong(trackCursor, MediaStore.Audio.Media._ID));
                        obj.put("title", CursorHelper.getString(trackCursor, MediaStore.Audio.Media.TITLE));
                        obj.put("artist", CursorHelper.getString(trackCursor, MediaStore.Audio.Media.ARTIST));
                        obj.put("duration", CursorHelper.getLong(trackCursor, MediaStore.Audio.Media.DURATION));

                        tracks.put(obj);

                    } while (trackCursor.moveToNext());

                    result.put("tracks", tracks);
                    callbackContext.success(result);

                } catch (JSONException e) {
                    callbackContext.error(e.toString());
                } finally {
                    if (albumCursor != null) {
                        albumCursor.close();
                    }
                    if (trackCursor != null) {
                        trackCursor.close();
                    }
                }
            }
        });
        return true;
    }

    return false;
}

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

private List<Long> getFeedSubscribers(Uri feedUri) {
    if (feedUri == null) {
        throw new NullPointerException("Feed cannot be null");
    }/*from  ww w.  j a  va 2  s .  co  m*/
    String feedName = feedUri.getLastPathSegment();
    switch (Feed.typeOf(feedUri)) {
    case FRIEND:
        String personId = Feed.friendIdForFeed(feedUri);
        if (personId == null) {
            return new ArrayList<Long>(0);
        }
        String table = Contact.TABLE;
        String[] columns = new String[] { Contact._ID };
        String selection = Contact.PERSON_ID + " = ?";
        String[] selectionArgs = new String[] { personId };
        String groupBy = null;
        String having = null;
        String orderBy = null;
        Cursor c = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, groupBy,
                having, orderBy);
        if (c == null || !c.moveToFirst()) {
            Log.w(TAG, "Could not find user for id " + personId);
            return new ArrayList<Long>(0);
        }
        return Collections.singletonList(c.getLong(0));
    case APP:
        // Currently, we send app messages to all users, which are registered
        // as subscribers to the "friend" feed. The subscribers model needs to
        // be reworked, and further the "app" feed needs further thinking.
        // Messages should be lossy, and encryption should not require keys
        // for each recipient.
        feedName = "friend";
        // No break:
    case GROUP:
        Cursor subs = mHelper.querySubscribers(feedName);
        List<Long> recipientIds = new ArrayList<Long>(subs.getCount());
        subs.moveToFirst();
        while (!subs.isAfterLast()) {
            long id = subs.getLong(subs.getColumnIndexOrThrow(Subscriber.CONTACT_ID));
            recipientIds.add(id);
            subs.moveToNext();
        }
        subs.close();
        return recipientIds;
    default:
        Log.w(TAG, "unmatched feed type for " + feedUri);
        return new ArrayList<Long>();
    }
}