How do I get a Uri to an image in my Assets that will work for the SearchManager.SUGGEST_COLUMN_ICON_1 column?

前端 未结 4 1103
臣服心动
臣服心动 2020-12-18 04:01

I have successfully integrated my app\'s country search into the global search facility and now I am trying to display each country\'s flag next to the search suggestions.

4条回答
  •  粉色の甜心
    2020-12-18 04:46

    You first create an AssetProvider. We will later create uris that will be handled by this class.

    public class AssetsProvider extends ContentProvider {
    
        private AssetManager assetManager;
        public static final Uri CONTENT_URI = 
                Uri.parse("content://com.example.assets");
    
        @Override
        public int delete(Uri arg0, String arg1, String[] arg2) { return 0; }
    
        @Override
        public String getType(Uri uri) { return null; }
    
        @Override
        public Uri insert(Uri uri, ContentValues values) { return null; }
    
        @Override
        public boolean onCreate() {
            assetManager = getContext().getAssets();
            return true;
        }
    
        @Override
        public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { return null; }
    
        @Override
        public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { return 0; }
    
        @Override
        public AssetFileDescriptor openAssetFile(Uri uri, String mode) throws FileNotFoundException {
            String path = uri.getPath().substring(1);
            try {
                AssetFileDescriptor afd = assetManager.openFd(path);
                return afd;
            } catch (IOException e) {
                throw new FileNotFoundException("No asset found: " + uri, e);
            }
        }
    }
    

    Lot's of boilerplate in there. The essential method is of course the openAssetFile that justs translates the path of the uri passed to it into a AssetFileDescriptor. In order for Android to be able to pass URIs to this provider, remember to include this in your AndroidManifest.xml file inside the application-tag:

        
    

    Now, in your search provider you can create an URI like this:

    content://com.example.assets/my_folder_inside_assets/myfile.png
    

提交回复
热议问题