Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:像个人资料图片一样永久保存图片,并共享偏好_Android_Xamarin_Xamarin.android_Sharedpreferences - Fatal编程技术网

Android:像个人资料图片一样永久保存图片,并共享偏好

Android:像个人资料图片一样永久保存图片,并共享偏好,android,xamarin,xamarin.android,sharedpreferences,Android,Xamarin,Xamarin.android,Sharedpreferences,在我的Xamarin.Android应用程序中,我想要一张封面图片,它会在应用程序第一次启动时保存。用户可以通过单击示例图片进行更改 到目前为止还不错,但当我关闭应用程序并再次启动时,图片不会显示出来 我从Android.Net.Uri中获得了这张图片,但是如何将其设置为SharedReferences,以及如何在OnCreate()中显示它?将图像Uri存储到共享首选项中 SharedPreferences sharedpreferences = getSharedPreferences(My

在我的Xamarin.Android应用程序中,我想要一张封面图片,它会在应用程序第一次启动时保存。用户可以通过单击示例图片进行更改

到目前为止还不错,但当我关闭应用程序并再次启动时,图片不会显示出来


我从Android.Net.Uri中获得了这张图片,但是如何将其设置为
SharedReferences
,以及如何在
OnCreate()
中显示它?

将图像Uri存储到共享首选项中

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);    
Editor editor = sharedpreferences.edit();
editor.putString("key_uri", "uri_value");
editor.commit();
当您在onCreate()中打开应用程序时将其存储后,请检查此字符串

SharedPreferences prefs= getSharedPreferences(MyPREFERENCES, 0);
String image_uri= settings.getString("key_uri", "null");
然后将图像uri(字符串)转换为uri

Uri uri = Uri.parse(image_uri);

然后使用此图像作为图像放置和显示

我认为您不能直接将图像存储在共享pref中。您可以将图像的绝对路径存储在图像的存储器或url中,也可以将图像位图转换为字节数组,并将字节数组(字符串)存储在共享的prefs中

这里有两种选择

  • 存储绝对路径或URI

        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("isSetImage", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("isSet", "true");
        editor.putString("absolutePath",filePath);
        editor.commit();
    
    您必须在“filepath”中提供绝对路径或URI

  • ByteArray已转换为base64

Write方法将位图编码为字符串base64并从位图返回base64字符串

            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("isSetImage", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("isSet", "true");
        editor.putString("absolutePath",BitmapToBase64(mBitmap));
        editor.commit();
要检查图像是否已设置,请执行以下操作:

        SharedPreferences sharedPreferences1 = getActivity().getSharedPreferences("isSetImage", Context.MODE_PRIVATE);
    String isSet = sharedPreferences1.getString("isSet", "");
    String absPath = sharedPreferences1.getString("absolutePath", "");
    if(isSet.equalsIgnoreCase("true"))
    {
        if(absPath!=null){
            previewMedia(absPath);
        }
    }
注意:这是我的一个android studio项目的代码。像Xamarin.Android一样使用起来并不困难


快乐编码\、/

但我如何才能找回Uri?您正在将其转换为字符串,但我希望它作为Uri