Android : Getting error “cannot resolve getSharedPreferences(java.lang.String, int)”

2018-01-24 00:02:21

I'm trying to access the SharedPreferences in a non-activity class but I always get this error cannot resolve getSharedPreferences(java.lang.String, int) . But when I use the getSharedPreferences in normal activity class I don't get this error.

错误代码:

 SharedPreferences prefs = getSharedPreferences("MyPrefs", context.MODE_PRIVATE);

解决办法:

 SharedPreferences prefs = context.getSharedPreferences("MyPrefs", context.MODE_PRIVATE);



或许在activity中不需要context,但是在fragement中需要getContext

  • 2020-11-17 09:50:32

    android开发怎样让悬浮Activity只是隐藏而不销毁

    android在mainfest中给Activity添加一个属性 android:theme="@android:style/Theme.Dialog",可以使Activity悬浮在其它窗口上面,在布局中可以设置activity的大小,当点击悬浮Activity边缘以外区域时,Activity会消失,观察消失时其生命周期会发现执行了finish()方法从而执行了onDestroy方法。有时我们只是需要将Activity隐藏,并不销毁,此时可以重写finish方法,如下:

  • 2020-11-17 09:56:02

    uni-app直接用webiew打开本地js资源

    如果再结合activity不销毁,隐藏的方法,像里面传递参数,来改变页面,不销毁webview,我发现这样比原生的都要快。这样又能用于app端,又能生成小程序,何乐而不为

  • 2020-11-17 09:59:05

    在线图片取色器工具

    不知道为啥,现在idea的取色工具怎么都不好使了,给开发人员反映过,都一年了有没修复咋地。 网上搜到一个取色工具,把图片传上去,就可以点击取色。不错。