如何将URL转换为URI?

8
我正在尝试使用以下代码缓存这些图像...
但是我一直在这里遇到语法错误?
 Uri imageUri = new Uri(aURL);

这是我正在使用的代码。

                                URL aURL = new URL(myRemoteImages[position]);



                                Uri imageUri = new Uri(aURL);
                                if (new File(new File(myContext.getCacheDir(), "thumbnails"), "" + imageUri.hashCode()).exists())
                                {
                                    String cachFile = ""+imageUri.hashCode();
                                    FileInputStream fis;

                                    try {
                                        fis = new FileInputStream(cachFile);
                                        Bitmap bm = BitmapFactory.decodeStream(fis); 
                                         i.setImageBitmap(bm);
                                            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                            /* Set the Width/Height of the ImageView. */
                                            if(Build.VERSION.SDK_INT >= 11){
                                                i.setLayoutParams(new Gallery.LayoutParams(450, 300));
                                            }
                                            else{
                                                i.setLayoutParams(new Gallery.LayoutParams(125, 125));
                                            }


                                    } catch (FileNotFoundException e) {

                                           Log.e("DEBUGTAG", "Remtoe Image Exception", e);





                                            /* Image should be scaled as width/height are set. */
                                            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                            /* Set the Width/Height of the ImageView. */
                                            if(Build.VERSION.SDK_INT >= 11){
                                                i.setLayoutParams(new Gallery.LayoutParams(450, 300));

                                            return i;
                                            }
                                                i.setLayoutParams(new Gallery.LayoutParams(125, 125));
                                                return i;
                                            }

1
所有的URL都是URI,但并非所有的URI都是URL。例如,URI可以是相对路径。只要URL有效(您有一个java.net.URL对象),您就可以像Niek建议的那样操作。 - Jeffrey Blattman
谢谢,是的,我通过执行imageUri = aUrl.toUri()解决了它。 - coder_For_Life22
顺便问一下,你能给我的问题点个赞吗? - coder_For_Life22
4个回答

9

5

阅读文档。 您不能使用URL创建URI。请使用类似以下内容的东西:

URI uri = new URI(aURL.toString());

当然,需要捕获任何必要的异常。

1
URI不等于Uri。而且那个构造函数不存在。 - Simian

0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接