Deprecated ManagedQuery() issue

2019-01-04 21:54发布

I have this method:

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Unfortunately the compiler show me a problem on:

Cursor cursor = managedQuery(contentUri, proj, null, null, null);

Because managedQuery() is deprecated.

How could I rewrite this method without use managedQuery()?

3条回答
做个烂人
2楼-- · 2019-01-04 22:49
public void getBrowserHist(Context context) {
        Cursor mCur = context.getContentResolver().query(Browser.BOOKMARKS_URI,
                Browser.HISTORY_PROJECTION, null, null, null);
        mCur.moveToFirst();
        if (mCur != null && mCur.moveToFirst() && mCur.getCount() > 0) {
            while (mCur.isAfterLast() == false) {
                Log.e("hist_titleIdx",
                        mCur.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX));
                Log.e("hist_urlIdx",
                        mCur.getString(Browser.HISTORY_PROJECTION_URL_INDEX));
                mCur.moveToNext();
            }
        }
    }
查看更多
我命由我不由天
3楼-- · 2019-01-04 22:50

you need to initialize the cursor becauese it will be close before method start or some where else

cursor = null;
public void method(){
// do your stuff here 
cursor.close();
}
查看更多
祖国的老花朵
4楼-- · 2019-01-04 22:51

You could replace it with context.getContentResolver().query and LoaderManager (you'll need to use the compatibility package to support devices before API version 11).

However, it looks like you're only using the query one time: you probably don't even need that. Maybe this would work?

public String getRealPathFromURI(Uri contentUri) {
    String res = null;
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
    if(cursor.moveToFirst()){;
       int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
       res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
}
查看更多
登录 后发表回答