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.mpower.daktar.android.tasks.InstanceUploaderTask.java

@Override
protected HashMap<String, String> doInBackground(final Long... values) {
    mResults = new HashMap<String, String>();

    String postResponse;/*ww w. j  a  va2  s.  co  m*/
    String selection = BaseColumns._ID + "=?";
    final String[] selectionArgs = new String[values.length];
    for (int i = 0; i < values.length; i++) {
        if (i != values.length - 1) {
            selection += " or " + BaseColumns._ID + "=?";
        }
        selectionArgs[i] = values[i].toString();
    }

    // get shared HttpContext so that authentication and cookies are
    // retained.
    final HttpContext localContext = MIntel.getInstance().getHttpContext();
    final HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);

    final Map<URI, URI> uriRemap = new HashMap<URI, URI>();

    final Cursor c = MIntel.getInstance().getContentResolver().query(InstanceColumns.CONTENT_URI, null,
            selection, selectionArgs, null);

    if (c.getCount() > 0) {
        c.moveToPosition(-1);
        next_submission: while (c.moveToNext()) {
            if (isCancelled())
                return mResults;
            publishProgress(c.getPosition() + 1, c.getCount());
            final String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
            final String id = c.getString(c.getColumnIndex(BaseColumns._ID));
            final Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);

            String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
            if (urlString == null) {
                final SharedPreferences settings = PreferenceManager
                        .getDefaultSharedPreferences(MIntel.getInstance());
                urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
                urlString = urlString + WebUtils.URL_PART_SUBMISSION;
            }

            final ContentValues cv = new ContentValues();
            URI u = null;
            try {
                final URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
                u = url.toURI();
            } catch (final MalformedURLException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (final URISyntaxException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            } catch (final UnsupportedEncodingException e) {
                e.printStackTrace();
                mResults.put(id, fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            boolean openRosaServer = false;
            if (uriRemap.containsKey(u)) {
                // we already issued a head request and got a response,
                // so we know the proper URL to send the submission to
                // and the proper scheme. We also know that it was an
                // OpenRosa compliant server.
                openRosaServer = true;
                u = uriRemap.get(u);
            } else {
                // we need to issue a head request
                final HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);

                // prepare response
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httpHead, localContext);
                    final int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 401) {
                        // we need authentication, so stop and return what
                        // we've
                        // done so far.
                        mAuthRequestingServer = u;
                        return null;
                    } else if (statusCode == 204) {
                        final Header[] locations = response.getHeaders("Location");
                        if (locations != null && locations.length == 1) {
                            try {
                                final URL url = new URL(URLDecoder.decode(locations[0].getValue(), "utf-8"));
                                final URI uNew = url.toURI();
                                if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
                                    openRosaServer = true;
                                    // trust the server to tell us a new
                                    // location
                                    // ... and possibly to use https
                                    // instead.
                                    uriRemap.put(u, uNew);
                                    u = uNew;
                                } else {
                                    // Don't follow a redirection attempt to
                                    // a different host.
                                    // We can't tell if this is a spoof or
                                    // not.
                                    mResults.put(id,
                                            fail + "Unexpected redirection attempt to a different host: "
                                                    + uNew.toString());
                                    cv.put(InstanceColumns.STATUS,
                                            InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                    continue;
                                }
                            } catch (final Exception e) {
                                e.printStackTrace();
                                mResults.put(id, fail + urlString + " " + e.getMessage());
                                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                                continue;
                            }
                        }
                    } else {
                        // may be a server that does not handle
                        try {
                            // have to read the stream in order to reuse the
                            // connection
                            final InputStream is = response.getEntity().getContent();
                            // read to end of stream...
                            final long count = 1024L;
                            while (is.skip(count) == count) {
                                ;
                            }
                            is.close();
                        } catch (final IOException e) {
                            e.printStackTrace();
                        } catch (final Exception e) {
                            e.printStackTrace();
                        }

                        Log.w(t, "Status code on Head request: " + statusCode);
                        if (statusCode >= 200 && statusCode <= 299) {
                            mResults.put(id, fail
                                    + "Invalid status code on Head request.  If you have a web proxy, you may need to login to your network. ");
                            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                            continue;
                        }
                    }
                } catch (final ClientProtocolException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Client Protocol Exception");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final ConnectTimeoutException e) {
                    e.printStackTrace();
                    Log.e(t, e.getMessage());
                    mResults.put(id, fail + "Connection Timeout");
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final UnknownHostException e) {
                    e.printStackTrace();
                    mResults.put(id, fail + e.getMessage() + " :: Network Connection Failed");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                } catch (final Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + "Generic Exception");
                    Log.e(t, e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue;
                }
            }

            // At this point, we may have updated the uri to use https.
            // This occurs only if the Location header keeps the host name
            // the same. If it specifies a different host name, we error
            // out.
            //
            // And we may have set authentication cookies in our
            // cookiestore (referenced by localContext) that will enable
            // authenticated publication to the server.
            //
            // get instance file
            final File instanceFile = new File(instance);

            if (!instanceFile.exists()) {
                mResults.put(id, fail + "instance XML file does not exist!");
                cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                continue;
            }

            // find all files in parent directory
            final File[] allFiles = instanceFile.getParentFile().listFiles();

            // add media files
            final List<File> files = new ArrayList<File>();
            for (final File f : allFiles) {
                final String fileName = f.getName();

                final int dotIndex = fileName.lastIndexOf(".");
                String extension = "";
                if (dotIndex != -1) {
                    extension = fileName.substring(dotIndex + 1);
                }

                if (fileName.startsWith(".")) {
                    // ignore invisible files
                    continue;
                }
                if (fileName.equals(instanceFile.getName())) {
                    continue; // the xml file has already been added
                } else if (openRosaServer) {
                    files.add(f);
                } else if (extension.equals("jpg")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gpp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("3gp")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("mp4")) { // legacy 0.9x
                    files.add(f);
                } else if (extension.equals("amr")) { // legacy 0.9x
                    files.add(f);
                } else {
                    Log.w(t, "unrecognized file type " + f.getName());
                }
            }

            postResponse = "";
            boolean first = true;
            int j = 0;
            while (j < files.size() || first) {
                first = false;

                final HttpPost httppost = WebUtils.createOpenRosaHttpPost(u, mAuth);

                final MimeTypeMap m = MimeTypeMap.getSingleton();

                long byteCount = 0L;

                // mime post
                final MultipartEntity entity = new MultipartEntity();

                // add the submission file first...
                FileBody fb = new FileBody(instanceFile, "text/xml");
                entity.addPart("xml_submission_file", fb);
                Log.i(t, "added xml_submission_file: " + instanceFile.getName());
                byteCount += instanceFile.length();

                for (; j < files.size(); j++) {
                    final File f = files.get(j);
                    final String fileName = f.getName();
                    final int idx = fileName.lastIndexOf(".");
                    String extension = "";
                    if (idx != -1) {
                        extension = fileName.substring(idx + 1);
                    }
                    String contentType = m.getMimeTypeFromExtension(extension);

                    // we will be processing every one of these, so
                    // we only need to deal with the content type
                    // determination...
                    if (extension.equals("xml")) {
                        fb = new FileBody(f, "text/xml");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xml file " + f.getName());
                    } else if (extension.equals("jpg")) {
                        fb = new FileBody(f, "image/jpeg");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added image file " + f.getName());
                    } else if (extension.equals("3gpp")) {
                        fb = new FileBody(f, "audio/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("3gp")) {
                        fb = new FileBody(f, "video/3gpp");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("mp4")) {
                        fb = new FileBody(f, "video/mp4");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added video file " + f.getName());
                    } else if (extension.equals("csv")) {
                        fb = new FileBody(f, "text/csv");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added csv file " + f.getName());
                    } else if (f.getName().endsWith(".amr")) {
                        fb = new FileBody(f, "audio/amr");
                        entity.addPart(f.getName(), fb);
                        Log.i(t, "added audio file " + f.getName());
                    } else if (extension.equals("xls")) {
                        fb = new FileBody(f, "application/vnd.ms-excel");
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added xls file " + f.getName());
                    } else if (contentType != null) {
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.i(t, "added recognized filetype (" + contentType + ") " + f.getName());
                    } else {
                        contentType = "application/octet-stream";
                        fb = new FileBody(f, contentType);
                        entity.addPart(f.getName(), fb);
                        byteCount += f.length();
                        Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
                    }

                    // we've added at least one attachment to the request...
                    if (j + 1 < files.size()) {
                        if (byteCount + files.get(j + 1).length() > 10000000L) {
                            // the next file would exceed the 10MB
                            // threshold...
                            Log.i(t, "Extremely long post is being split into multiple posts");
                            try {
                                final StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
                                entity.addPart("*isIncomplete*", sb);
                            } catch (final Exception e) {
                                e.printStackTrace(); // never happens...
                            }
                            ++j; // advance over the last attachment
                            // added...
                            break;
                        }
                    }
                }

                httppost.setEntity(entity);

                // prepare response and return uploaded
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost, localContext);
                    final int responseCode = response.getStatusLine().getStatusCode();

                    // try {
                    // // have to read the stream in order to reuse the
                    // connection
                    // InputStream is = response.getEntity().getContent();
                    // // read to end of stream...
                    // final long count = 1024L;
                    // while (is.skip(count) == count)
                    // ;
                    // is.close();
                    // } catch (IOException e) {
                    // e.printStackTrace();
                    // } catch (Exception e) {
                    // e.printStackTrace();
                    // }

                    final HttpEntity httpEntity = response.getEntity();
                    try {
                        postResponse = EntityUtils.toString(httpEntity, HTTP.UTF_8).trim();
                    } catch (final IOException e) {
                        e.printStackTrace();
                    }

                    Log.i(t, "Response code:" + responseCode);
                    // verify that the response was a 201 or 202.
                    // If it wasn't, the submission has failed.
                    if (responseCode != 201 && responseCode != 202) {
                        if (responseCode == 200) {
                            mResults.put(id, fail + "Network login failure? Again?");
                        } else {
                            if (postResponse.length() > 0) {
                                mResults.put(id, postResponse);
                            } else {
                                mResults.put(id, fail + response.getStatusLine().getReasonPhrase() + " ("
                                        + responseCode + ") at " + urlString);
                            }
                        }
                        cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                        MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                        continue next_submission;
                    }
                } catch (final Exception e) {
                    e.printStackTrace();
                    mResults.put(id, fail + " " + e.getMessage());
                    cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
                    MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);
                    continue next_submission;
                }
            }

            // if it got here, it must have worked
            if (postResponse.length() > 0) {
                // Custom msg from server
                mResults.put(id, postResponse);
            } else {
                // There is no response from server, use default string
                mResults.put(id, MIntel.getInstance().getString(R.string.success));
            }
            // mResults.put(id,
            // MIntel.getInstance().getString(R.string.success));
            cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
            MIntel.getInstance().getContentResolver().update(toUpdate, cv, null, null);

        }
        if (c != null) {
            c.close();
        }

    } // end while

    return mResults;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public String[] getRecipeTagStrings(long rid) {
    Cursor c = getRecipeTags(rid);
    String[] tags = new String[c.getCount()];

    c.moveToFirst();//  ww w.j a v a2s .  co  m
    while (!c.isAfterLast()) {
        tags[c.getPosition()] = c.getString(c.getColumnIndex(TT_TAG));
        c.moveToNext();
    }

    c.close();
    return tags;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public String[] getRecipeIngredientStrings(long rid) {
    Cursor c = getRecipeIngredients(rid);
    String[] ings = new String[c.getCount()];

    c.moveToFirst();//from w  w  w  . j  a  v  a  2 s .  co  m
    while (!c.isAfterLast()) {
        ings[c.getPosition()] = c.getString(c.getColumnIndex(IT_NAME));
        c.moveToNext();
    }

    c.close();
    return ings;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public String[] getRecipeDirectionStrings(long rid) {
    // NOTE: the returned array is in database sequential order
    Cursor c = getRecipeDirections(rid);
    String[] dirs = new String[c.getCount()];

    c.moveToFirst();//from  www  . j a  v a 2  s  . c  om
    while (!c.isAfterLast()) {
        dirs[c.getPosition()] = c.getString(c.getColumnIndex(DT_STEP));
        c.moveToNext();
    }

    c.close();
    return dirs;
}

From source file:net.potterpcs.recipebook.RecipeData.java

private String[] getRecipeDirectionPhotoStrings(long rid) {
    // NOTE: the returned array is in database sequential order
    Cursor c = getRecipeDirections(rid);
    String[] dirs = new String[c.getCount()];

    c.moveToFirst();/*from ww  w .  j a va 2s  .  c  o m*/
    while (!c.isAfterLast()) {
        dirs[c.getPosition()] = c.getString(c.getColumnIndex(DT_PHOTO));
        c.moveToNext();
    }

    c.close();
    return dirs;
}

From source file:net.olejon.mdapp.MedicationActivity.java

private boolean isFavorite() {
    SQLiteDatabase sqLiteDatabase = new MedicationsFavoritesSQLiteHelper(mContext).getReadableDatabase();

    String[] queryColumns = { MedicationsFavoritesSQLiteHelper.COLUMN_NAME,
            MedicationsFavoritesSQLiteHelper.COLUMN_MANUFACTURER };
    Cursor cursor = sqLiteDatabase.query(MedicationsFavoritesSQLiteHelper.TABLE, queryColumns,
            MedicationsFavoritesSQLiteHelper.COLUMN_NAME + " = " + mTools.sqe(medicationName) + " AND "
                    + MedicationsFavoritesSQLiteHelper.COLUMN_MANUFACTURER + " = "
                    + mTools.sqe(medicationManufacturer),
            null, null, null, null);/*from  w  w  w . ja va  2 s.  co m*/

    int count = cursor.getCount();

    cursor.close();
    sqLiteDatabase.close();

    return (count != 0);
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * @param threadId/*from   w  w  w  .j ava2  s . com*/
 * @param lastTime
 * @return
 */
public static ArrayList<ECMessage> queryIMessageListAfter(long threadId, String lastTime) {
    ArrayList<ECMessage> al = null;
    Cursor cursor = null;
    StringBuffer sb = new StringBuffer();
    if (lastTime != null && !lastTime.equals("") && !lastTime.equals("0")) {
        sb.append(IMessageColumn.CREATE_DATE + " > ").append(lastTime);
    } else {
        sb.append("1=1");
    }
    sb.append(" and " + IMessageColumn.OWN_THREAD_ID + " = ").append(threadId);
    sb.append(" and  " + IMessageColumn.BOX_TYPE + " != 3");
    try {
        cursor = getInstance().sqliteDB().query(false, DatabaseHelper.TABLES_NAME_IM_MESSAGE, null,
                sb.toString(), null, null, null, IMessageColumn.RECEIVE_DATE + " asc", null);
        if (cursor != null) {
            if (cursor.getCount() == 0) {
                return null;
            }
            al = new ArrayList<ECMessage>();
            while (cursor.moveToNext()) {

                long id = cursor.getLong(cursor.getColumnIndex(IMessageColumn.ID));
                String sender = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.sender));
                String msgId = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_ID));
                long ownThreadId = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.OWN_THREAD_ID));
                long createDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.CREATE_DATE));
                long receiveDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.RECEIVE_DATE));
                String userData = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.USER_DATA));
                int read = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.READ_STATUS));
                int boxType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.BOX_TYPE));
                int msgType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_TYPE));
                int sendStatus = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.SEND_STATUS));

                ECMessage ecMessage = null;
                if (msgType == ECMessage.Type.TXT.ordinal()) {
                    String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
                    ecMessage = ECMessage.createECMessage(ECMessage.Type.TXT);
                    ECTextMessageBody textBody = new ECTextMessageBody(content);
                    ecMessage.setBody(textBody);
                } else {
                    /*
                    * String fileUrl =
                    * cursor.getString(cursor.getColumnIndexOrThrow
                    * (IMessageColumn.FILE_URL)); String fileLocalPath =
                    * cursor
                    * .getString(cursor.getColumnIndexOrThrow(IMessageColumn
                    * .FILE_PATH));
                    * 
                    * if (msgType == ECMessage.Type.VOICE.ordinal()) { int
                    * duration =
                    * cursor.getInt(cursor.getColumnIndexOrThrow(
                    * IMessageColumn.DURATION)); ECVoiceMessageBody
                    * voiceBody = new ECVoiceMessageBody(new
                    * File(fileLocalPath), 0);
                    * voiceBody.setRemoteUrl(fileUrl);
                    * ecMessage.setBody(voiceBody); ecMessage =
                    * ECMessage.createECMessage(ECMessage.Type.VOICE); }
                    * else if (msgType == ECMessage.Type.IMAGE.ordinal() ||
                    * msgType == ECMessage.Type.FILE.ordinal()) {
                    * ECFileMessageBody fileBody = new } else { continue; }
                    */
                }
                ecMessage.setId(id);
                ecMessage.setFrom(sender);
                ecMessage.setMsgId(msgId);
                ecMessage.setMsgTime(createDate);
                ecMessage.setUserData(userData);
                ecMessage.setDirection(getMessageDirect(boxType));
                al.add(0, ecMessage);
            }
        }
    } catch (Exception e) {
        LogUtil.e(TAG + " " + e.toString());
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }
    return al;
}

From source file:mobisocial.bento.todo.io.BentoManager.java

synchronized public void loadBentoList() {
    long prevFeedId = -1;
    String[] projection = new String[] { DbObj.COL_ID, DbObj.COL_FEED_ID };
    Uri uri = Musubi.uriForDir(DbThing.OBJECT);
    String selection = "type = ?";
    String[] selectionArgs = new String[] { TYPE_TODOBENTO };
    String sortOrder = DbObj.COL_FEED_ID + " asc, " + DbObj.COL_LAST_MODIFIED_TIMESTAMP + " asc";

    Cursor c = mMusubi.getContext().getContentResolver().query(uri, projection, selection, selectionArgs,
            sortOrder);/*  w ww.j  a  va2 s.co m*/

    ArrayList<BentoListItem> tmpList = new ArrayList<BentoListItem>();
    if (c != null && c.moveToFirst()) {
        mBentoList = new ArrayList<BentoListItem>();

        for (int i = 0; i < c.getCount(); i++) {
            BentoListItem item = new BentoListItem();
            item.bento = new Bento();

            DbObj dbObj = mMusubi.objForCursor(c);
            LatestObj latestObj = null;

            latestObj = fetchLatestObj(c.getLong(0));
            if (latestObj != null && latestObj.json.has(STATE)) {
                JSONObject stateObj = latestObj.json.optJSONObject(STATE);
                if (fetchBentoObj(stateObj, item.bento)) {
                    item.objUri = dbObj.getUri();
                    item.feedId = c.getLong(1);
                    if (DEBUG) {
                        Log.d(TAG, item.objUri.toString());
                        Log.d(TAG, item.feedId + "");
                    }

                    // count number of todo
                    ArrayList<TodoListItem> todoList = new ArrayList<TodoListItem>();
                    if (fetchTodoListObj(stateObj, todoList)) {
                        item.bento.numberOfTodo = todoList.size();
                        tmpList.add(0, item);
                    }

                    // load members
                    fetchMemberNames(item.feedId);
                }
            }
            c.moveToNext();
        }
    }
    c.close();

    // insert dividers
    if (tmpList.size() > 0) {
        for (int j = 0; j < tmpList.size(); j++) {
            BentoListItem item = tmpList.get(j);
            if (prevFeedId != item.feedId) {
                BentoListItem divider = new BentoListItem();
                divider.enabled = false;
                divider.feedId = item.feedId;
                mBentoList.add(divider);

                prevFeedId = item.feedId;
            }
            mBentoList.add(item);
        }
    }

    if (DEBUG) {
        Log.d(TAG, "tmpList:" + tmpList.size() + " mBentoList:" + mBentoList.size());
    }
}

From source file:com.TomatoSauceStudio.OnTimeBirthdayPost.OnTimeBirthdayPost.java

private int fillData() {
    /**/*from   w w w  .j a  v  a 2  s  .c o  m*/
     * Fetch recent and upcoming birthdays from DB: We use comparison of the
     * MMdd date strings as the basis.
     */
    Calendar cal = new GregorianCalendar();
    cal.add(Calendar.DATE, -DAYS_PAST);
    String startDate = rawDF.format(cal.getTime());
    //Log.d("OnTimeBirthdayPost","Start Date Req: " + startDate);
    cal.add(Calendar.DATE, DAYS_PAST + DAYS_AHEAD);
    String endDate = rawDF.format(cal.getTime());
    //Log.d("OnTimeBirthdayPost","End Date Req: " + endDate);
    Cursor birthdaysCursor = null;
    /**
     * If database is empty or we can't access it for some reason, return err;
     * if our query returns no results return 0, else return success (1).
     */
    try {
        if (mDbHelper.getRowCount() <= 0) {
            return -1;
        }
        birthdaysCursor = mDbHelper.fetchBirthdays(startDate, endDate);
    } catch (Exception e) {
        return -1;
    }
    if (birthdaysCursor.getCount() == 0) {
        return 0;
    }
    startManagingCursor(birthdaysCursor);

    /**
     * Create an array to specify the fields we want to display in the list.
     */
    String[] from = new String[] { BirthdaysDbAdapter.KEY_NAME, BirthdaysDbAdapter.KEY_BIRTHDAY_FORMATTED,
            BirthdaysDbAdapter.KEY_LOCATION };

    /**
     * And an array of the fields we want to bind those fields to (in this case just text1)
     */
    int[] to = new int[] { R.id.fname, R.id.fbday, R.id.floc };

    /**
     * Now create a simple cursor adapter and set it to display
     */
    ColorfulSimpleCursorAdapter birthdays = new ColorfulSimpleCursorAdapter(this, R.layout.birthdays_row,
            birthdaysCursor, from, to);
    setListAdapter(birthdays);
    return 1;
}

From source file:net.potterpcs.recipebook.RecipeData.java

public String getOldestCacheEntry() {
    synchronized (DB_LOCK) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.query(CACHE_TABLE, CACHE_FIELDS, null, null, null, null, CT_CACHED, "1");
        if (c.getCount() > 0) {
            c.moveToFirst();//from   www  .  jav  a  2s .  co m
            String s = c.getString(c.getColumnIndex(CT_URI));
            c.close();
            return s;
        } else {
            c.close();
            return null;
        }
    }
}