Example usage for android.database Cursor close

List of usage examples for android.database Cursor close

Introduction

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

Prototype

void close();

Source Link

Document

Closes the Cursor, releasing all of its resources and making it completely invalid.

Usage

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

protected static int computeRequestCount(Context context, ScriptCategory category, String trollId) {

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Calendar instance = Calendar.getInstance();
    instance.add(Calendar.HOUR_OF_DAY, -24);
    Date sinceDate = instance.getTime();

    Cursor cursor = database.rawQuery(SQL_COUNT,
            new String[] { trollId, category.name(), "" + sinceDate.getTime() });
    int result = 0;
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();//from  w w w .j  ava2 s.  c  o m
        result = cursor.getInt(0);
    }

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

    String format = "Quota for category %s and troll=%s since '%s' is: %d";
    String message = String.format(format, category, trollId, sinceDate, result);
    Log.d(TAG, message);

    return result;
}

From source file:net.kourlas.voipms_sms.Utils.java

/**
 * Gets a URI pointing to a contact's photo, given the URI for that contact.
 *
 * @param applicationContext The application context.
 * @param uri                The URI of the contact.
 * @return a URI pointing to the contact's photo.
 *//*from  w ww .ja  v  a2s .c o  m*/
public static String getContactPhotoUri(Context applicationContext, Uri uri) {
    Cursor cursor = applicationContext.getContentResolver().query(uri,
            new String[] { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI },
            null, null, null);
    if (cursor.moveToFirst()) {
        String photoUri = cursor
                .getString(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
        cursor.close();
        return photoUri;
    } else {
        cursor.close();
        return null;
    }
}

From source file:Main.java

public static String resolveFileName(Uri uri, Activity activity) {
    String filename = null;/*from   w ww .j  a  v  a  2s.c  o m*/
    String uriString = uri.toString();

    if (uriString.startsWith("content://")) {
        Cursor cursor = null;
        try {
            cursor = activity.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                String mimeType = MimeTypeMap.getSingleton()
                        .getExtensionFromMimeType(activity.getContentResolver().getType(uri));
                filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

                if (mimeType != null && !filename.endsWith("." + mimeType)) {
                    filename += "." + mimeType;
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } else if (uriString.startsWith("file://")) {
        filename = (new File(uriString)).getName();
    }
    return filename;
}

From source file:Main.java

public static String getFirstCNLetterByContactId(Context context, long contactId) {
    String result = "";
    String[] projection = {/*www . j  a  v a  2  s .c o  m*/
            // Data._ID,
            // Data.DISPLAY_NAME,
            // Data.CONTACT_ID,
            Data.DATA12, };
    String where = Data.CONTACT_ID + "=?";
    final String sortOrder = null;
    Cursor cursor = context.getContentResolver().query(PHONE_CONTACTS_URI, projection, where,
            new String[] { String.valueOf(contactId) }, sortOrder);

    if (cursor != null) {
        try {
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    String nameLetters = cursor.getString(cursor.getColumnIndexOrThrow("data12"));
                    if (null != nameLetters && !"".equals(nameLetters)) {
                        result = nameLetters.substring(0, 1).toUpperCase();
                        break;
                    }
                }
            }

        } finally {
            cursor.close();
        }
    }

    return result;
}

From source file:com.deliciousdroid.platform.ContactManager.java

private static long lookupHighWatermark(ContentResolver resolver, long id) {
    long result = 0;
    final Cursor c = resolver.query(RawContacts.CONTENT_URI, HighWatermarkQuery.PROJECTION,
            HighWatermarkQuery.SELECTION, new String[] { Long.toString(id) }, null);
    try {//ww  w. java 2 s .c  o  m
        while (c.moveToNext()) {
            result = c.getLong(HighWatermarkQuery.COLUMN_ID);
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return result;
}

From source file:Main.java

public static byte[] getPersonPhoto(Context context, String id) {
    if (id == null)
        return null;
    byte photo[] = null;

    Cursor cursor = context.getContentResolver().query(Uri.withAppendedPath(Contacts.Photos.CONTENT_URI, id),
            new String[] { PhotosColumns.DATA }, null, null, null);
    if (cursor != null) {
        try {//  w  w  w .  j a va2s  . c om
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                photo = cursor.getBlob(0);
                if (photo != null) {
                    return photo;
                    // Log.v("Found photo for person: " + id);
                    // bitmap = BitmapFactory.decodeStream(new
                    // ByteArrayInputStream(photo));
                }
            }
        } finally {
            cursor.close();
        }
    }
    return photo;
}

From source file:edu.stanford.mobisocial.dungbeetle.model.DbObject.java

/**
 * @param v the view to bind/*from w w w.j a  va  2 s  .  co m*/
 * @param context standard activity context
 * @param c the cursor source for the object in the db object table.
 * Must include _id in the projection.
 * 
 * @param allowInteractions controls whether the bound view is
 * allowed to intercept touch events and do its own processing.
 */
public static void bindView(View v, final Context context, Cursor cursor, boolean allowInteractions) {
    TextView nameText = (TextView) v.findViewById(R.id.name_text);
    ViewGroup frame = (ViewGroup) v.findViewById(R.id.object_content);
    frame.removeAllViews();

    // make sure we have all the columns we need
    Long objId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
    String[] projection = null;
    String selection = DbObj.COL_ID + " = ?";
    String[] selectionArgs = new String[] { Long.toString(objId) };
    String sortOrder = null;
    Cursor c = context.getContentResolver().query(DbObj.OBJ_URI, projection, selection, selectionArgs,
            sortOrder);
    if (!c.moveToFirst()) {
        Log.w(TAG, "could not find obj " + objId);
        c.close();
        return;
    }
    DbObj obj = App.instance().getMusubi().objForCursor(c);
    if (obj == null) {
        nameText.setText("Failed to access database.");
        Log.e("DbObject", "cursor was null for bindView of DbObject");
        return;
    }
    DbUser sender = obj.getSender();
    Long timestamp = c.getLong(c.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
    Long hash = obj.getHash();
    short deleted = c.getShort(c.getColumnIndexOrThrow(DELETED));
    String feedName = obj.getFeedName();
    String type = obj.getType();
    Date date = new Date(timestamp);
    c.close();
    c = null;

    if (sender == null) {
        nameText.setText("Message from unknown contact.");
        return;
    }
    nameText.setText(sender.getName());

    final ImageView icon = (ImageView) v.findViewById(R.id.icon);
    if (sViewProfileAction == null) {
        sViewProfileAction = new OnClickViewProfile((Activity) context);
    }
    icon.setTag(sender.getLocalId());
    if (allowInteractions) {
        icon.setOnClickListener(sViewProfileAction);
        v.setTag(objId);
    }
    icon.setImageBitmap(sender.getPicture());

    if (deleted == 1) {
        v.setBackgroundColor(sDeletedColor);
    } else {
        v.setBackgroundColor(Color.TRANSPARENT);
    }

    TextView timeText = (TextView) v.findViewById(R.id.time_text);
    timeText.setText(RelativeDate.getRelativeDate(date));

    frame.setTag(objId); // TODO: error prone! This is database id
    frame.setTag(R.id.object_entry, cursor.getPosition()); // this is cursor id
    FeedRenderer renderer = DbObjects.getFeedRenderer(type);
    if (renderer != null) {
        renderer.render(context, frame, obj, allowInteractions);
    }

    if (!allowInteractions) {
        v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
        v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
    } else {
        if (!MusubiBaseActivity.isDeveloperModeEnabled(context)) {
            v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
            v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
        } else {
            ImageView attachmentCountButton = (ImageView) v.findViewById(R.id.obj_attachments_icon);
            TextView attachmentCountText = (TextView) v.findViewById(R.id.obj_attachments);
            attachmentCountButton.setVisibility(View.VISIBLE);

            if (hash == 0) {
                attachmentCountButton.setVisibility(View.GONE);
            } else {
                //int color = DbObject.colorFor(hash);
                boolean selfPost = false;
                DBHelper helper = new DBHelper(context);
                try {
                    Cursor attachments = obj.getSubfeed().query("type=?", new String[] { LikeObj.TYPE });
                    try {
                        attachmentCountText.setText("+" + attachments.getCount());

                        if (attachments.moveToFirst()) {
                            while (!attachments.isAfterLast()) {
                                if (attachments.getInt(attachments.getColumnIndex(CONTACT_ID)) == -666) {
                                    selfPost = true;
                                    break;
                                }
                                attachments.moveToNext();

                            }
                        }
                    } finally {
                        attachments.close();
                    }
                } finally {
                    helper.close();
                }
                if (selfPost) {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love_red);
                } else {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love);
                }
                attachmentCountText.setTag(R.id.object_entry, hash);
                attachmentCountText.setTag(R.id.feed_label, Feed.uriForName(feedName));
                attachmentCountText.setOnClickListener(LikeListener.getInstance(context));
            }
        }
    }
}

From source file:com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java

/**
 * Creates objects for quizzes according to a category id.
 *
 * @param categoryId The category to create quizzes for.
 * @param database The database containing the quizzes.
 * @return The found quizzes or an empty list if none were available.
 *///from w w  w  .j  a  v a  2s  .  co  m
private static List<Quiz> getQuizzes(final String categoryId, SQLiteDatabase database) {
    final List<Quiz> quizzes = new ArrayList<>();
    final Cursor cursor = database.query(QuizTable.NAME, QuizTable.PROJECTION,
            QuizTable.FK_CATEGORY + " LIKE ?", new String[] { categoryId }, null, null, null);
    cursor.moveToFirst();
    do {
        quizzes.add(createQuizDueToType(cursor));
    } while (cursor.moveToNext());
    cursor.close();
    return quizzes;
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static Date geLastRequest(Context context, PublicScript script, String trollId) {

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Cursor cursor = database.rawQuery(SQL_LAST_REQUEST, new String[] { trollId, script.name() });
    Date result = null;//from ww w. j a v a2 s .co m
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        long resultTimestamp = cursor.getLong(0);
        result = new Date(resultTimestamp);
    }

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

    String format = "Last request for category %s (script=%s) and troll=%s is: '%s'";
    String message = String.format(format, script.category, script, trollId, result);
    Log.d(TAG, message);

    return result;
}

From source file:fr.mixit.android.io.JsonHandlerApplyInterests.java

private static boolean isItemUpdated(Uri uri, JSONObject item, ContentResolver resolver) throws JSONException {
    final Cursor cursor = resolver.query(uri, MixItContract.Interests.PROJ.PROJECTION, null, null, null);
    try {/*from  ww  w.  ja v  a 2 s  .  co m*/
        if (!cursor.moveToFirst()) {
            return false;
        }

        final String curName = cursor.getString(MixItContract.Interests.PROJ.NAME)
                .toLowerCase(Locale.getDefault()).trim();

        final String newName = item.has(TAG_NAME)
                ? item.getString(TAG_NAME).toLowerCase(Locale.getDefault()).trim()
                : curName;

        return !curName.equals(newName);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}