SharedPreferences preferences;
SharedPreferences.Editor editor;
//初始化editor
preferences = getSharedPreferences("user", MODE_PRIVATE);
editor = preferences.edit();
//添加内容
editor.putInt("uid", jsonObj.getInt("uid"));
editor.commit();
如上代码,在一个Activity里写SharedPreferences,现在想要在另一个文件里读uid怎么搞?
就是一个普通的类,没有继承任何类,里面写了一些公用方法,我要通过这个uid调取用户信息,这个uid是服务器端返回的。
=========================================================
Thanks to all!
续:
根据各位的回答,自定义了一个ContextApplication,Manifest文件中已添加Contextapplication。
package cc.xxx.xxx.xx;
import android.app.Application;
import android.content.Context;
public class ContextApplication extends Application {
private static Context context;
public void onCreate() {
super.onCreate();
ContextApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return ContextApplication.context;
}
}
我在Activity外是这样调用的:
SharedPreferences preferences;
preferences = ContextApplication.getAppContext().getSharedPreferences("user", 0);
Integer uid = preferences.getInt("uid", 0);
Log.d(tag, "search>uid: " + uid);
程序执行到这段时,Log没有打印。LOGCAT中没有任何Error。
再请赐教,谢谢。
//9-23 22:48 结贴
全局Context要在AndroidManifest.xml的这里配置
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name=".application.ContextApplication" >
我自定义的文件位置:my_package_name/application/ContextApplication.java
像楼主那种写法的话,取数据方法:SharedPreferences preferences = getSharedPreferences("user", MODE_PRIVATE);
int uid = preferences.getInt("uid", "");
显然在普通类里行不通
你可以给你的类写一个构造器,初始化的时候就传入context参数,这是SharePreferences所必须的.
public class YourClass{
private SharedPreferences preferences;
public YourClass(Context context){
preferences=context.getSharedPreferences("user", 0);
}
public SharedPreferences getPreferences(){
return prefrences;
}
public void handleUid(){
int uid= preferences.getInt("uid","");//拿到你的uid
}
}
注意,每次在使用你这个类时,要传入context对象,比如在Activity中YourClass myClass = new YourClass(this);
无法为你验证以下做法:
在Application
中设置一个Context
成员,每次使用前通过公有方法获得,然后就应该可以使用getSharedPreferences
方法。
提供一个链接
http://stackoverflow.com/questions/2002288/static-way-to-get-context-on-android
题主的问题其实就是在Activity
之外拿Context
@idiot 的解决方法是可行的。不过我做的项目中用的是@Honwhy 的方法。
这里要更正一点的是,由于Application
就是继承至Context
的,所以直接获取Application
实例就行了。
public class GlobalApplication extends Application {
private static GlobalApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static GlobalApplication getInstance() {
if (instance == null)
instance = new GlobalApplication();
return instance;
}
}
然后把这个GlobalApplication
配置到AndroidManifest.xml
里
这个做法的好处是,项目里任何地方都可以随时拿到Context
。
坏处就是用GlobalApplication.getInstance()
来startActivity()
会生成一个新的Activity Task