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:com.nononsenseapps.notepad.sync.googleapi.GoogleTaskSync.java

/**
 * Loads the remote tasks from the database and merges the two lists. If the
 * remote list contains all items, then this method only adds local db-ids
 * to the items. If it does not contain all of them, this loads whatever
 * extra items are known in the db to the list also.
 *///ww w  . jav  a  2 s.c  o m
public static void mergeTasksWithLocalDB(final Context context, final String account,
        final List<GoogleTask> remoteTasks, long listDbId) {
    final HashMap<String, GoogleTask> localVersions = new HashMap<String, GoogleTask>();
    final Cursor c = context.getContentResolver().query(GoogleTask.URI, GoogleTask.Columns.FIELDS,
            GoogleTask.Columns.LISTDBID + " IS ? AND " + GoogleTask.Columns.ACCOUNT + " IS ? AND "
                    + GoogleTask.Columns.SERVICE + " IS ?",
            new String[] { Long.toString(listDbId), account, GoogleTaskList.SERVICENAME }, null);
    try {
        while (c.moveToNext()) {
            GoogleTask task = new GoogleTask(c);
            localVersions.put(task.remoteId, task);
        }
    } finally {
        if (c != null)
            c.close();
    }

    for (final GoogleTask task : remoteTasks) {
        // Set list on remote objects
        task.listdbid = listDbId;
        // Merge with hashmap
        if (localVersions.containsKey(task.remoteId)) {
            task.dbid = localVersions.get(task.remoteId).dbid;
            task.setDeleted(localVersions.get(task.remoteId).isDeleted());
            if (task.isDeleted()) {
                Log.d(TAG, "merge1: deleting " + task.title);
            }
            localVersions.remove(task.remoteId);
        }
    }

    // Remaining ones
    for (final GoogleTask task : localVersions.values()) {
        remoteTasks.add(task);
        if (task.isDeleted()) {
            Log.d(TAG, "merge2: was deleted " + task.title);
        }
    }
}

From source file:com.fada.sellsteward.myweibo.sina.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*from w  w  w  .j  a v a2 s .  co  m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            // ??APN
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.android.email.LegacyConversions.java

/**
 * Add a single attachment part to the message
 *
 * This will skip adding attachments if they are already found in the attachments table.
 * The heuristic for this will fail (false-positive) if two identical attachments are
 * included in a single POP3 message.// w w w  .j a  v  a 2s  . c  o m
 * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments
 * position within the list of multipart/mixed elements.  This would make every POP3 attachment
 * unique, and might also simplify the code (since we could just look at the positions, and
 * ignore the filename, etc.)
 *
 * TODO: Take a closer look at encoding and deal with it if necessary.
 *
 * @param context a context for file operations
 * @param localMessage the attachments will be built against this message
 * @param part a single attachment part from POP or IMAP
 * @param upgrading true if upgrading a local account - handle attachments differently
 * @throws IOException
 */
private static void addOneAttachment(Context context, EmailContent.Message localMessage, Part part,
        boolean upgrading) throws MessagingException, IOException {

    Attachment localAttachment = new Attachment();

    // Transfer fields from mime format to provider format
    String contentType = MimeUtility.unfoldAndDecode(part.getContentType());
    String name = MimeUtility.getHeaderParameter(contentType, "name");
    if (name == null) {
        String contentDisposition = MimeUtility.unfoldAndDecode(part.getDisposition());
        name = MimeUtility.getHeaderParameter(contentDisposition, "filename");
    }

    // Select the URI for the new attachments.  For attachments downloaded by the legacy
    // IMAP/POP code, this is not determined yet, so is null (it will be rewritten below,
    // or later, when the actual attachment file is created.)
    //
    // When upgrading older local accounts, the URI represents a local asset (e.g. a photo)
    // so we need to preserve the URI.
    // TODO This works for outgoing messages, where the URI does not change.  May need
    // additional logic to handle the case of rewriting URI for received attachments.
    Uri contentUri = null;
    String contentUriString = null;
    if (upgrading) {
        Body body = part.getBody();
        if (body instanceof LocalStore.LocalAttachmentBody) {
            LocalStore.LocalAttachmentBody localBody = (LocalStore.LocalAttachmentBody) body;
            contentUri = localBody.getContentUri();
            if (contentUri != null) {
                contentUriString = contentUri.toString();
            }
        }
    }

    // Find size, if available, via a number of techniques:
    long size = 0;
    if (upgrading) {
        // If upgrading a legacy account, the size must be recaptured from the data source
        if (contentUri != null) {
            Cursor metadataCursor = context.getContentResolver().query(contentUri,
                    ATTACHMENT_META_COLUMNS_PROJECTION, null, null, null);
            if (metadataCursor != null) {
                try {
                    if (metadataCursor.moveToFirst()) {
                        size = metadataCursor.getInt(ATTACHMENT_META_COLUMNS_SIZE);
                    }
                } finally {
                    metadataCursor.close();
                }
            }
        }
        // TODO: a downloaded legacy attachment - see if the above code works
    } else {
        // Incoming attachment: Try to pull size from disposition (if not downloaded yet)
        String disposition = part.getDisposition();
        if (disposition != null) {
            String s = MimeUtility.getHeaderParameter(disposition, "size");
            if (s != null) {
                size = Long.parseLong(s);
            }
        }
    }

    // Get partId for unloaded IMAP attachments (if any)
    // This is only provided (and used) when we have structure but not the actual attachment
    String[] partIds = part.getHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA);
    String partId = partIds != null ? partIds[0] : null;

    localAttachment.mFileName = name;
    localAttachment.mMimeType = part.getMimeType();
    localAttachment.mSize = size; // May be reset below if file handled
    localAttachment.mContentId = part.getContentId();
    localAttachment.mContentUri = contentUriString;
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mLocation = partId;
    localAttachment.mEncoding = "B"; // TODO - convert other known encodings

    if (DEBUG_ATTACHMENTS) {
        Log.d(Email.LOG_TAG, "Add attachment " + localAttachment);
    }

    // To prevent duplication - do we already have a matching attachment?
    // The fields we'll check for equality are:
    //  mFileName, mMimeType, mContentId, mMessageKey, mLocation
    // NOTE:  This will false-positive if you attach the exact same file, twice, to a POP3
    // message.  We can live with that - you'll get one of the copies.
    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null, null);
    boolean attachmentFoundInDb = false;
    try {
        while (cursor.moveToNext()) {
            Attachment dbAttachment = new Attachment().restore(cursor);
            // We test each of the fields here (instead of in SQL) because they may be
            // null, or may be strings.
            if (stringNotEqual(dbAttachment.mFileName, localAttachment.mFileName))
                continue;
            if (stringNotEqual(dbAttachment.mMimeType, localAttachment.mMimeType))
                continue;
            if (stringNotEqual(dbAttachment.mContentId, localAttachment.mContentId))
                continue;
            if (stringNotEqual(dbAttachment.mLocation, localAttachment.mLocation))
                continue;
            // We found a match, so use the existing attachment id, and stop looking/looping
            attachmentFoundInDb = true;
            localAttachment.mId = dbAttachment.mId;
            if (DEBUG_ATTACHMENTS) {
                Log.d(Email.LOG_TAG, "Skipped, found db attachment " + dbAttachment);
            }
            break;
        }
    } finally {
        cursor.close();
    }

    // Save the attachment (so far) in order to obtain an id
    if (!attachmentFoundInDb) {
        localAttachment.save(context);
    }

    // If an attachment body was actually provided, we need to write the file now
    if (!upgrading) {
        saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey);
    }

    if (localMessage.mAttachments == null) {
        localMessage.mAttachments = new ArrayList<Attachment>();
    }
    localMessage.mAttachments.add(localAttachment);
    localMessage.mFlagAttachment = true;
}

From source file:com.phonegap.Storage.java

/**
 * Execute SQL statement.//from  ww  w .  ja v  a2  s .c o  m
 * 
 * @param query            The SQL query
 * @param params         Parameters for the query
 * @param tx_id            Transaction id
 */
public void executeSql(String query, String[] params, String tx_id) {
    try {
        Cursor myCursor = this.myDb.rawQuery(query, params);
        this.processResults(myCursor, tx_id);
        myCursor.close();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        System.out.println("Storage.executeSql(): Error=" + ex.getMessage());

        // Send error message back to JavaScript
        this.sendJavascript("droiddb.fail('" + ex.getMessage() + "','" + tx_id + "');");
    }
}

From source file:com.dongfang.dicos.sina.UtilSina.java

/**
 * Get a HttpClient object which is setting correctly .
 * //from w w  w. j ava2s. c o  m
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static HttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, UtilSina.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, UtilSina.SET_SOCKET_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        // ??APN
        Uri uri = Uri.parse("content://telephony/carriers/preferapn");
        Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            // ???
            String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
            if (proxyStr != null && proxyStr.trim().length() > 0) {
                HttpHost proxy = new HttpHost(proxyStr, 80);
                client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
            }
            mCursor.close();
        }
    }
    return client;
}

From source file:com.onesignal.NotificationOpenedProcessor.java

private static void updateSummaryNotification(SQLiteDatabase writableDb) {
    String grpId = intent.getStringExtra("grp");

    Cursor cursor = writableDb.query(NotificationTable.TABLE_NAME,
            new String[] { NotificationTable.COLUMN_NAME_ANDROID_NOTIFICATION_ID }, // retColumn
            NotificationTable.COLUMN_NAME_GROUP_ID + " = ? AND " + // Where String
                    NotificationTable.COLUMN_NAME_DISMISSED + " = 0 AND " + NotificationTable.COLUMN_NAME_OPENED
                    + " = 0 AND " + NotificationTable.COLUMN_NAME_IS_SUMMARY + " = 0",
            new String[] { grpId }, // whereArgs
            null, null, null);//from  w  ww .  ja  v a  2 s. c  o  m

    // All individual notifications consumed, make summary notification as consumed as well.
    if (cursor.getCount() == 0)
        writableDb.update(NotificationTable.TABLE_NAME, newContentValuesWithConsumed(),
                NotificationTable.COLUMN_NAME_GROUP_ID + " = ?", new String[] { grpId });
    else {
        try {
            GenerateNotification.createSummaryNotification(context, true,
                    new JSONObject("{\"grp\": \"" + grpId + "\"}"));
        } catch (JSONException e) {
        }
    }

    cursor.close();
}

From source file:net.eledge.android.toolkit.db.internal.TableBuilder.java

private boolean doesTableExists(Class<?> clazz) {
    final String query = "SELECT DISTINCT tbl_name FROM sqlite_master WHERE type='table' AND tbl_name = ?";
    Cursor cursor = db.rawQuery(query, new String[] { SQLBuilder.getTableName(clazz) });
    boolean exists = cursor.getCount() == 1;
    cursor.close();
    return exists;
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

/**
 * Get display name from the uri/*from   w  ww.  j a v a  2  s.co m*/
 *
 * @param context
 * @param uri
 * @return
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getDisplayName(Context context, Uri uri) {

    String name = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        Cursor nameCursor = resolver.query(uri, null, null, null, null);
        try {
            if (nameCursor.getCount() > 0) {
                int displayNameIndex = nameCursor
                        .getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME);
                if (displayNameIndex >= 0 && nameCursor.moveToFirst()) {
                    name = nameCursor.getString(displayNameIndex);
                }
            }
        } finally {
            nameCursor.close();
        }
    }

    return name;
}

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

public static List<MhSpRequest> listLatestRequestsSince(Context context, String trollId, int dayCount) {
    List<MhSpRequest> result = new ArrayList<MhSpRequest>();

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

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

    Calendar calendar = Calendar.getInstance();

    Cursor cursor = database.rawQuery(SQL_LIST_REQUESTS_SINCE,
            new String[] { trollId, "" + sinceDate.getTime() });
    while (cursor.moveToNext()) {
        long startTimeMillis = cursor.getLong(0);
        long endTimeMillis = cursor.getLong(1);
        String scriptName = cursor.getString(2);
        String status = cursor.getString(3);

        calendar.setTimeInMillis(startTimeMillis);
        Date date = calendar.getTime();
        PublicScript script = PublicScript.valueOf(scriptName);

        long duration = 0;
        if (endTimeMillis > 0) {
            duration = endTimeMillis - startTimeMillis;
        }//from   ww w  . j a  v  a 2  s. c  om
        MhSpRequest request = new MhSpRequest(date, duration, script, status);
        result.add(request);
    }

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

    return result;
}

From source file:Main.java

/**
 * Retourner la liste des calendriers// ww  w .  j a v a  2  s  .  co  m
 * 
 * @return Liste des calendriers
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static Map<Integer, String> getCalendars(ContentResolver contentResolver) {
    Map<Integer, String> calendars = new HashMap<Integer, String>();
    String[] projection;
    Uri calendarUri;
    Cursor cursor;
    String accessLevelCol;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        calendarUri = CalendarContract.Calendars.CONTENT_URI;
        projection = new String[] { CalendarContract.Calendars._ID,
                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME };
        accessLevelCol = CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL;
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        calendarUri = Uri.parse("content://com.android.calendar/calendars");
        projection = new String[] { "_id", "displayname" };
        accessLevelCol = "ACCESS_LEVEL";
    } else {
        calendarUri = Uri.parse("content://calendar/calendars");
        projection = new String[] { "_id", "displayname" };
        accessLevelCol = "ACCESS_LEVEL";
    }

    cursor = contentResolver.query(calendarUri, projection, accessLevelCol + "=700", null, null);

    if (cursor != null && cursor.moveToFirst()) {
        while (cursor.isAfterLast() == false) {
            calendars.put(cursor.getInt(0), cursor.getString(1));
            cursor.moveToNext();
        }
        cursor.close();
    }

    return calendars;
}