我有一個問題,我的共享首選項不工作在類文件中。我很困惑,無法解決它。以下是我的文件globalfile,其中保存數據如下。共享首選項不起作用
public class globalfile extends Activity {
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Pwd = "pwdKey";
public static final String Email = "emailKey";
private static String global_username = "null/", global_pwd = "null/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
}
public String getusername() {
global_username = sharedpreferences.getString(Email, "");
return global_username;
}
public String getuserpwd() {
global_pwd = sharedpreferences.getString(Pwd, "");
return global_pwd;
}
public void setusername(String someVariable) {
global_username = someVariable;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Email,global_username);
editor.commit();
}
public void setuserpwd(String someVariable) {
global_pwd = someVariable;
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Pwd,global_pwd);
editor.commit();
}
}
我第一被叫setuserpwd()& setusername()然後,使用類globalfile.But的對象總是返回null.although如果我使用這個代碼,無需共享pref.it getuserpwd()& getusername()從另一個活動做工精緻
你在哪裏調用'setusername()'和'setuserpwd()'? – Lal
如果'globalfile'是實用類,那麼爲什麼要擴展Activity? –