Example usage for android.database Cursor getColumnIndex

List of usage examples for android.database Cursor getColumnIndex

Introduction

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

Prototype

int getColumnIndex(String columnName);

Source Link

Document

Returns the zero-based index for the given column name, or -1 if the column doesn't exist.

Usage

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

/**
 * @param v the view to bind/*from   ww w. j  ava  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.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java

/**
 * Removes all data from themovies, thevideos, and thereviews tables.  Does not remove data
 * flagged favorite but the columns istoprated, and ispopular will be set to false, "0".
 * @param context/*from w  w w .java2  s. co  m*/
 */
public static void deletePopularAndTopRated(Context context) {
    ContentResolver contentResolver = context.getContentResolver();

    ContentValues removePopAndTop = new ContentValues(2);
    removePopAndTop.put(TMDbContract.Movies.IS_POPULAR, "0");
    removePopAndTop.put(TMDbContract.Movies.IS_TOP_RATED, "0");

    contentResolver.update(TMDbContract.Movies.URI, removePopAndTop, TMDbContract.Movies.IS_FAVORITE + " = ?",
            new String[] { "1" });

    contentResolver.delete(TMDbContract.Movies.URI,
            TMDbContract.Movies.IS_POPULAR + " = ? OR " + TMDbContract.Movies.IS_TOP_RATED + " = ?",
            new String[] { "1", "1" });

    Cursor favoriteMovieIds = getFavoriteIds(context);

    int numberOfIds = favoriteMovieIds.getCount();
    String[] movieIds = new String[numberOfIds];
    String whereClauseVideos = "";
    String whereClauseReviews = "";

    for (int i = 0; i < numberOfIds; i++) {
        favoriteMovieIds.moveToNext();
        movieIds[i] = Integer.toString(
                favoriteMovieIds.getInt(favoriteMovieIds.getColumnIndex(TMDbContract.Movies.MOVIE_ID)));
        if (i == numberOfIds - 1) {
            whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? ";
            whereClauseReviews += TMDbContract.Videos.MOVIE_IDS + " != ? ";
        } else {
            whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? OR ";
            whereClauseReviews += TMDbContract.Reviews.MOVIE_IDS + " != ? OR ";
        }
    }

    contentResolver.delete(TMDbContract.Videos.URI, whereClauseVideos, movieIds);
    contentResolver.delete(TMDbContract.Reviews.URI, whereClauseReviews, movieIds);
}

From source file:com.facebook.Settings.java

/**
 * Acquire the current attribution id from the facebook app.
 * @return returns null if the facebook app is not present on the phone.
 *///  w  ww. ja v a  2s .  co  m
public static String getAttributionId(ContentResolver contentResolver) {
    Cursor c = null;
    try {
        String[] projection = { ATTRIBUTION_ID_COLUMN_NAME };
        c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null);
        if (c == null || !c.moveToFirst()) {
            return null;
        }
        String attributionId = c.getString(c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME));
        return attributionId;
    } catch (Exception e) {
        Log.d(TAG, "Caught unexpected exception in getAttributionId(): " + e.toString());
        return null;
    } finally {
        if (c != null) {
            c.close();
        }
    }
}

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

public static String getStringField(String resourcePath, String columnName) {
    String result = null;//from   w ww .  j  av  a 2  s  .c o m
    final String[] projection = new String[] { columnName };
    final String[] selectionArgs = new String[] { resourcePath };
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, sSelection, selectionArgs, null);
    try {
        if (c.moveToFirst()) {
            result = c.getString(c.getColumnIndex(columnName));
        }
    } finally {
        c.close();
    }
    return result;
}

From source file:com.rsegismont.androlife.core.utils.AndrolifeUtils.java

public static long getCurrentIndex(Cursor mCursor) {

    long dateUtc = -1;

    if (mCursor == null)
        return -1;

    if (mCursor.getCount() <= 0)
        return -1;

    final int initialPosition = mCursor.getPosition();

    int index = -1;

    for (int i = 0; i < mCursor.getCount(); i++) {
        mCursor.moveToPosition(i);/*  ww  w .  j a v  a 2  s  . co m*/
        final long value = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
        if (System.currentTimeMillis() - value < 0) {
            index = i - 1;
            mCursor.moveToPosition(Math.max(0, index));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }

        if ((i == 0) && (System.currentTimeMillis() - value < 0)) {

            mCursor.moveToPosition(0);
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }

        if (i == (mCursor.getCount() - 1)) {
            index = (mCursor.getCount() - 1);
            mCursor.moveToPosition(Math.max(0, index));
            dateUtc = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue));
            break;
        }
    }

    if (initialPosition >= 0)
        mCursor.moveToPosition(initialPosition);
    return dateUtc;

}

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

public static long getSize(final String resourcePath) {
    final String[] projection = new String[] { Nodes.NODE_SIZE };
    final String selection = Nodes.NODE_RESOURCE_PATH + "=?";
    final String[] selectionArgs = new String[] { resourcePath };
    Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
    long size = 0L;
    try {//  w  ww . j a v  a  2s .  c  o  m
        if (c.moveToFirst()) {
            size = c.getLong(c.getColumnIndex(Nodes.NODE_SIZE));
        }
    } finally {
        c.close();
    }
    return size;
}

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

/**
 * Get display name from the uri/*from  www  .  j av  a 2  s  .c  o 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:com.ubuntuone.android.files.provider.MetaUtilities.java

public static String getPublicUrl(final String resourcePath) {
    final String[] projection = new String[] { Nodes.NODE_PUBLIC_URL };
    final String selection = Nodes.NODE_RESOURCE_PATH + "=?";
    final String[] selectionArgs = new String[] { resourcePath };
    Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
    String url = null;/*from w w  w.  j a  v  a2 s .  c o  m*/
    try {
        if (c.moveToFirst()) {
            url = c.getString(c.getColumnIndex(Nodes.NODE_PUBLIC_URL));
        }
    } finally {
        c.close();
    }
    return TextUtils.isEmpty(url) ? null : url;
}

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

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

public static boolean isDirectory(long id) {
    String[] projection = new String[] { Nodes.NODE_KIND };
    String selection = Nodes._ID + "=?";
    String[] selectionArgs = new String[] { String.valueOf(id) };
    final Cursor c = sResolver.query(Nodes.CONTENT_URI, projection, selection, selectionArgs, null);
    String type = null;//from  www .j a v  a2  s.c o m
    try {
        if (c.moveToFirst()) {
            type = c.getString(c.getColumnIndex(Nodes.NODE_KIND));
        }
    } finally {
        c.close();
    }
    return (type != null) ? U1NodeKind.DIRECTORY == U1NodeKind.valueOf(type.toUpperCase(Locale.US)) : false;
}