存储在内部存储器中时如何为图像生成随机名称?

Ram*_*amz 0 sqlite android

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

物品有图像,名称,价格等.

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

当用户单击"添加到购物车"选项时,将创建一个sqlite数据库,其中存储名称,价格和图像路径.

当点击添加到购物车并且只有图像路径存储在数据库中时,基本上Imgaes存储在内部存储器中.

问题:

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

SaveToMemory:

 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();

}
Run Code Online (Sandbox Code Playgroud)

LoadFromMemory:

private Bitmap loadImageFromStorage(String path)
{

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


    }
Run Code Online (Sandbox Code Playgroud)

如果我这样做,最新图像将被上一张图像覆盖.我无法在内存中存储多个图像.

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

目标

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

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

将其检索回以在Imageview中显示.

任何帮助都会非常感激.

Raj*_*esh 8

尝试

mypath=new File(directory,System.currentTimeMillis()+"_profile.jpg");
Run Code Online (Sandbox Code Playgroud)

代替

mypath=new File(directory,"profile.jpg");
Run Code Online (Sandbox Code Playgroud)

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


gio*_*gio 5

您可以使用UUID

new File(directory,"profile_" + UUID.randomUUID().toString() + ".jpg");
Run Code Online (Sandbox Code Playgroud)

这将是

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