【问题标题】:How to Generate Random names for Images while storing in Internal Memory?如何在存储在内存中时为图像生成随机名称?
【发布时间】:2016-01-18 08:36:12
【问题描述】:

我正在开发的 Android 应用程序基本上是一个购物应用程序,它有一个购物车选项,用户可以在其中添加商品。

商品有图片、名称、价格等。

我从服务器获取所有这些数据。

当用户单击“添加到购物车”选项时,会创建一个 sqlite 数据库,用于存储名称、价格和图像路径。

当点击添加到购物车时,基本上图像存储在内存中,数据库中只存储图像路径。

问题:

为了将图像存储在内部存储器中,我使用下面的代码,我将自己给出文件名(在这种情况下,我将文件名命名为 profile.jpg)。

保存到内存:

 private String saveToInternalSorage(Bitmap bitmapImage){
    ContextWrapper cw = new ContextWrapper(getApplicationContext());
    // path to /data/data/yourapp/app_data/imageDir
     directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
    // Create imageDir
    mypath=new File(directory,"profile.jpg");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(mypath);
        // Use the compress method on the BitMap object to write image to the OutputStream
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            fos.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return directory.getAbsolutePath();

}

从内存加载:

private Bitmap loadImageFromStorage(String path)
{

    try {
        File f=new File(path, "");
        f.canRead();
        b = BitmapFactory.decodeStream(new FileInputStream(f));
        return b;


    }

如果我这样做,最新的图像会被之前的图像覆盖。我无法在内存中存储多张图像。

例如,如果我在购物车中添加两个项目,我不知道如何存储这两个图像并获取它。

瞄准

需要在内存中存储任意数量的随机文件名的图像

将文件名存储在 sqlite 数据库中。

将其取回以在 Imageview 中显示。

任何帮助将不胜感激。

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

    试试

    mypath=new File(directory,System.currentTimeMillis()+"_profile.jpg");
    

    而不是

    mypath=new File(directory,"profile.jpg");
    

    System.currentTimeMillis() 将返回自 1970 年 1 月 1 日 00:00:00.0 UTC 以来的当前时间(以毫秒为单位)。所以每次都不一样

    【讨论】:

      【解决方案2】:

      您可以使用UUID

      new File(directory,"profile_" + UUID.randomUUID().toString() + ".jpg");
      

      应该是

      profile_e85c5115-eea6-4b0d-98e3-9e09c2d505b3.jpg

      【讨论】:

      • 你可以修剪它更友好,UUID.randomUUID().toString().subString(0,5);
      【解决方案3】:

      使用new Date().toString() 而不是"profile.jpg"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-21
        • 2011-08-13
        相关资源
        最近更新 更多