在Android的共享preferences?Android、preferences

2023-09-12 22:33:35 作者:疯的很理智

我是一个新手,Android开发者谁正在努力营造一个登录界面。

I'm a novice Android developer who are currently trying hard to build a Login Screen.

我需要找到存储的用户名和密码在1类和其他类检索它的最简单方法。看看谷歌已经提供了几个方法: http://developer.android.com/导/主题/数据/数据​​storage.html

I need to find the easiest way to store the username and password in 1 class and retrieve it from another class. See Google has provided several ways: http://developer.android.com/guide/topics/data/data-storage.html

哪一个是最有效且易于code?

which one is the most efficient and easy to code?

谢谢!

推荐答案

有关登录屏幕任务,如存储用户名和密码,您可以使用共享preferences。在这里,我做了自定义的方法使用共享preferences。呼叫节省preferences()方法,并把你的重点和值(节省preferences()是一种基于XML),同样呼叫负载与你的密钥。而最后不要忘了叫删除preferences()在注销。

For Login screen tasks like storing username and password you can use Shared Preferences. Here I had made custom methods for using shared preferences. Call savePreferences() method and put your Key and Value(as savePreferences() is based on XML), similarly call Load with your Key. And lastly don't forgot to call deletePreferences() on LOGOUT.

/**
 *   Method used to get Shared Preferences */

public SharedPreferences getPreferences() 
{
    return getSharedPreferences(<PREFRENCE_FILE_NAME>, MODE_PRIVATE);
}
/**
 *  Method used to save Preferences */
public void savePreferences(String key, String value) 
{
    SharedPreferences sharedPreferences = getPreferences();
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
}
/**
 *  Method used to load Preferences */
public String loadPreferences(String key) 
{
    try {
        SharedPreferences sharedPreferences = getPreferences();
        String strSavedMemo = sharedPreferences.getString(key, "");
        return strSavedMemo;
    } catch (NullPointerException nullPointerException) 
    {
        Log.e("Error caused at  TelaSketchUtin loadPreferences method",
                ">======>" + nullPointerException);
        return null;
    }
}
/**
 *  Method used to delete Preferences */
public boolean deletePreferences(String key)
{
    SharedPreferences.Editor editor=getPreferences().edit();
    editor.remove(key).commit();
    return false;
}

希望这会帮助你。不要忘记做+1。

Hope this should help you. Don't Forget to do +1.