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.eastedge.readnovel.weibo.net.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {//from  ww w. j av  a 2s .  c om
        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()) {
            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.ubuntuone.android.files.provider.MetaUtilities.java

public static Set<String> getUserNodePaths() {
    Set<String> userNodePaths = new TreeSet<String>();
    final String[] projection = new String[] { Nodes._ID, Nodes.NODE_RESOURCE_PATH };
    final String selection = Nodes.NODE_PARENT_PATH + " IS NULL";
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, null, null);
    try {/*from  w  ww.j  av  a2  s  . c  o  m*/
        if (c.moveToFirst()) {
            String resourcePath;
            do {
                resourcePath = c.getString(c.getColumnIndex(Nodes.NODE_RESOURCE_PATH));
                userNodePaths.add(resourcePath);
            } while (c.moveToNext());
        }
    } finally {
        c.close();
    }
    return userNodePaths;
}

From source file:Main.java

@SuppressLint("NewApi")
public static String uriToPath(Context activity, Uri uri) {
    if (null == uri) {
        return null;
    }//  w  w  w  .  j a va  2 s. c  om
    String urlStr = uri.toString();
    if (urlStr.startsWith("file://")) {
        return uri.getPath();
    }
    Cursor cursor = null;
    String idWhere;
    String id;
    String[] columns = { MediaStore.Images.Media.DATA };
    try {
        if (Build.VERSION.SDK_INT == 19 && DocumentsContract.isDocumentUri(activity, uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            id = split[1];
            idWhere = MediaStore.Images.Media._ID + "=?";
            cursor = activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                    idWhere, new String[] { id }, null);
        } else {
            cursor = activity.getContentResolver().query(uri, columns, null, null, null);
        }
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        }
    } catch (Exception e) {
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return null;
}

From source file:com.ubuntuone.android.files.provider.MetaUtilities.java

public static void cleanupTreeByResourcePath(String resourcePath) {
    Log.i(TAG, "cleaning up tree of: " + resourcePath);
    String kindString = MetaUtilities.getStringField(resourcePath, Nodes.NODE_KIND);
    if (kindString == null) {
        return;// w ww  .ja  va2s .  c  o m
    }

    U1NodeKind kind = U1NodeKind.valueOf(kindString.toUpperCase(Locale.US));
    if (kind == U1NodeKind.FILE) {
        String data = FileUtilities.getFilePathFromResourcePath(resourcePath);
        FileUtilities.removeSilently(data);
        MetaUtilities.deleteByResourcePath(resourcePath);
    } else {
        String resourcePathFmt = resourcePath + "/%";
        String[] projection = new String[] { Nodes.NODE_RESOURCE_PATH, Nodes.NODE_DATA };
        String selection = Nodes.NODE_RESOURCE_PATH + " LIKE ?";
        String[] selectionArgs = new String[] { resourcePathFmt };

        Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
        if (c != null) {
            try {
                while (c.moveToNext()) {
                    String data = FileUtilities.getFilePathFromResourcePath(resourcePathFmt);
                    FileUtilities.removeSilently(data);
                }
            } finally {
                c.close();
            }
        }

        sResolver.delete(Nodes.CONTENT_URI, selection, selectionArgs);

        selection = Nodes.NODE_RESOURCE_PATH + "=?";
        selectionArgs = new String[] { resourcePath };
        sResolver.delete(Nodes.CONTENT_URI, selection, selectionArgs);
    }
}

From source file:com.futurologeek.smartcrossing.crop.CropImageActivity.java

public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };

    try {//  www . j  av  a 2 s. c  om
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleTaskSync.java

/**
 * Loads the remote lists from the database and merges the two lists. If the
 * remote list contains all lists, 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.
 * //from w w w  . ja v  a 2  s .  c  o m
 * Since all lists are expected to be downloaded, any non-existing entries
 * are assumed to be deleted and marked as such.
 */
public static void mergeListsWithLocalDB(final Context context, final String account,
        final List<GoogleTaskList> remoteLists) {
    Log.d(TAG, "mergeList starting with: " + remoteLists.size());

    final HashMap<String, GoogleTaskList> localVersions = new HashMap<String, GoogleTaskList>();
    final Cursor c = context.getContentResolver().query(GoogleTaskList.URI, GoogleTaskList.Columns.FIELDS,
            GoogleTaskList.Columns.ACCOUNT + " IS ? AND " + GoogleTaskList.Columns.SERVICE + " IS ?",
            new String[] { account, GoogleTaskList.SERVICENAME }, null);
    try {
        while (c.moveToNext()) {
            GoogleTaskList list = new GoogleTaskList(c);
            localVersions.put(list.remoteId, list);
        }
    } finally {
        if (c != null)
            c.close();
    }

    for (final GoogleTaskList remotelist : remoteLists) {
        // Merge with hashmap
        if (localVersions.containsKey(remotelist.remoteId)) {
            //Log.d(TAG, "Setting merge id");
            remotelist.dbid = localVersions.get(remotelist.remoteId).dbid;
            //Log.d(TAG, "Setting merge delete status");
            remotelist.setDeleted(localVersions.get(remotelist.remoteId).isDeleted());
            localVersions.remove(remotelist.remoteId);
        }
    }

    // Remaining ones
    for (final GoogleTaskList list : localVersions.values()) {
        list.remotelyDeleted = true;
        remoteLists.add(list);
    }
    Log.d(TAG, "mergeList finishing with: " + remoteLists.size());
}

From source file:com.andrewshu.android.reddit.common.Common.java

public static boolean isClicked(Context context, String url) {
    Cursor cursor;
    try {//from www . j  a  va2  s . c  o  m
        cursor = context.getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION,
                Browser.HISTORY_PROJECTION[Browser.HISTORY_PROJECTION_URL_INDEX] + "=?", new String[] { url },
                null);
    } catch (Exception ex) {
        if (Constants.LOGGING)
            Log.w(TAG, "Error querying Android Browser for history; manually revoked permission?", ex);
        return false;
    }

    if (cursor != null) {
        boolean isClicked = cursor.moveToFirst(); // returns true if cursor is not empty
        cursor.close();
        return isClicked;
    } else {
        return false;
    }
}

From source file:Main.java

public static HashSet<String> getUserContacts(ContentResolver cr) {
    HashSet<String> contactsList = new HashSet<String>();
    //ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            // We could store names and numbers in a dictionary if we ever needed that
            // String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(
                    cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
                while (pCur.moveToNext()) {
                    String phoneNo = pCur
                            .getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    // If the number stored isn't long enough to be in our database then don't bother.
                    if (phoneNo.length() >= 10) {
                        // Use regex to remove '+', spaces, '(', and ')' and '-' form user contacts to match database format
                        String formattedPhoneNo = phoneNo.replaceAll(DELIMITERS, "");
                        // Remove the '1' in front of the number
                        if (formattedPhoneNo.charAt(0) == '1') {
                            formattedPhoneNo = formattedPhoneNo.substring(1);
                        }//from w  w  w . ja va 2  s.  c  o  m
                        contactsList.add(formattedPhoneNo);
                    }
                }
                pCur.close();
            }
        }
    }
    return contactsList;
}

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

/**
 * Get a HttpClient object which is setting correctly .
 * //  w  w w. j a  va 2  s .  co 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, Utility.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Utility.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:edu.mit.mobile.android.locast.data.TaggableItem.java

/**
 * @param cr/*from  w  w  w .  j  a v a  2  s .c om*/
 * @param item
 * @param prefix
 * @return a list of all the tags attached to a given item
 */
public static Set<String> getTags(ContentResolver cr, Uri item, String prefix) {
    final Cursor tags = cr.query(Uri.withAppendedPath(item, Tag.PATH), Tag.DEFAULT_PROJECTION, null, null,
            null);
    final Set<String> tagSet = new HashSet<String>(tags.getCount());
    final int tagColumn = tags.getColumnIndex(Tag._NAME);
    final Predicate<String> predicate = getPrefixPredicate(prefix);
    for (tags.moveToFirst(); !tags.isAfterLast(); tags.moveToNext()) {
        final String tag = tags.getString(tagColumn);
        if (predicate.apply(tag)) {
            final int separatorIndex = tag.indexOf(PREFIX_SEPARATOR);
            if (separatorIndex == -1) {
                tagSet.add(tag);
            } else {
                tagSet.add(tag.substring(separatorIndex + 1));
            }
        }
    }
    tags.close();
    return tagSet;
}