2012-06-26 129 views
0

在我的应用程序中,我试图将图像存储在内部存储器中,以便它只能在我的应用程序中使用,并且无法以其他方式看到。android-在内部存储器中存储图像缓存并重新使用它

在下面的方式我已经存储了图像缓存内存

File cacheDir = getApplicationContext().getDir("", Context.MODE_PRIVATE); 
File fileWithinMyDir = new File(cacheDir, ""); 

for(int i = 0; i < img.size(); i++) 
{    
    String filename = String.valueOf(img.get(i).hashCode()); 
    String urlString = img.get(i); 
    String PATH = fileWithinMyDir + filename; 
    DownloadFromUrl(PATH, urlString); 
    img_path.add(PATH); 
} 

    private void DownloadFromUrl(String fileName, String urlStr) 
    { 
     try 
     { 
     URL url = new URL(urlStr); 
     File file = new File(fileName); 
     URLConnection ucon = url.openConnection(); 
     InputStream is = ucon.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 
     ByteArrayBuffer baf = new ByteArrayBuffer(50); 
     int current = 0; 
     while ((current = bis.read()) != -1) 
     { 
     baf.append((byte) current); 
     } 

     FileOutputStream fos = new FileOutputStream(file); 
     fos.write(baf.toByteArray()); 
     fos.close(); 
    } 
    catch (IOException e) 
    { 
     Log.e("download", e.getMessage()); 
    } 
    } 

IMG是包含图片的URL从中我还没有下载一个ArrayList。 img_path是一个ArrayList,我在其中存储图像缓存存储的路径。

所保存的路径似乎是如下

/data/data/com.intr.store/app_1219784788 

这条道路与我的包名,这是一个正确的?我没有在任何地方给出app_,但它是如何发生的?

在我的其他活动之一,我想加载它在图像视图。我用以下方法试了

File filePath = getFileStreamPath(pth); 
     i.setImageDrawable(Drawable.createFromPath(filePath.toString())); 

这里pth是路径,我是图像视图。但该应用程序崩溃说,

06-26 14:40:08.259: E/AndroidRuntime(6531): Caused by: java.lang.IllegalArgumentException: File /data/data/com.intr.store/app_1219784788 contains a path separator 
+1

你可以发布完整的源代码一样getFileStreamPath体 –

+0

使用aContext.getCacheDir()存储你的文件 –

+0

@VipulShah我已经添加了图像下载代码... –

回答

1

你写错了代码。

更换

File cacheDir = getApplicationContext().getDir("", Context.MODE_PRIVATE); 
File fileWithinMyDir = new File(cacheDir, ""); 

File fileWithinMyDir = getApplicationContext().getFilesDir(); 

然后

更换

String PATH = fileWithinMyDir + filename; 

String PATH = fileWithinMyDir.getAbsolutePath() + "/" +filename+".file extension"; 
+0

现在我得到的图像路径为 -/data/data/com.intr.store/files1219784788。当我试图加载另一个活动中的图像相同的错误 - 文件/ data/data/com.intr.store/files1219784788包含一个路径分隔符 –

+0

检查我更新的答案。您需要将扩展​​名也添加到文件 –

+0

我已经给文件扩展名为.png,我得到的路径如下/data/data/com.intr.store/files/1219784788.png –

相关问题