安卓(Android) 怎么从Context获取实体(Entity)ID

2019年10月18日21:57:30安卓(Android) 怎么从Context获取实体(Entity)ID已关闭评论 270 1331字阅读4分26秒

1.简介

安卓(Android) 怎么从Context获取实体(Entity)ID?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import android.content.ContentResolver;

import android.content.Context;
import android.database.Cursor;

import android.net.Uri;
import android.provider.BaseColumns;

public class Main {
    private static final String[] PROJECTION_ID = new String[] { BaseColumns._ID };

    public static long getEntityId(Context context, Uri uri) {
        return getEntityId(context.getContentResolver(), uri);
    }

    public static long getEntityId(ContentResolver cr, Uri uri) {
        return getEntityId(cr, uri, null, null);
    }

    public static long getEntityId(Context context, Uri uri,
            String selection, String[] selectionArgs) {
        return getEntityId(context.getContentResolver(), uri, selection,
                selectionArgs);
    }

    public static long getEntityId(ContentResolver cr, Uri uri,
            String selection, String[] selectionArgs) {
        return getEntityId(cr, uri, selection, selectionArgs, null);
    }

    public static long getEntityId(Context context, Uri uri,
            String selection, String[] selectionArgs, String sortOrder) {
        return getEntityId(context.getContentResolver(), uri, selection,
                selectionArgs, sortOrder);
    }

    public static long getEntityId(ContentResolver cr, Uri uri,
            String selection, String[] selectionArgs, String sortOrder) {
        Cursor cursor = null;
        try {
            cursor = cr.query(uri, PROJECTION_ID, selection, selectionArgs,
                    sortOrder);
            if (cursor.moveToNext()) {
                return cursor.getLong(0);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return -1;
    }
}

 
继续阅读
编程十万个怎么办