Android 中的共享首选项? [英] Shared Preferences in Android?

查看:38
本文介绍了Android 中的共享首选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名 Android 开发新手,目前正在努力构建登录屏幕.

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

我需要找到将用户名和密码存储在 1 个类中并从另一个类中检索它的最简单方法.看谷歌提供了几种方式:http://developer.android.com/guide/topics/data/data-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

哪种编码最高效、最容易?

which one is the most efficient and easy to code?

谢谢!

推荐答案

对于登录屏幕任务,例如存储用户名和密码,您可以使用共享首选项.在这里,我制作了使用共享首选项的自定义方法.调用 savePreferences() 方法并放置您的 Key 和 Value(因为 savePreferences() 基于 XML),同样使用您的 Key 调用 Load.最后不要忘记在注销时调用 deletePreferences().

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.

这篇关于Android 中的共享首选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆