2012-06-26 132 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 –

相關問題