如何在 SharedPreferences 中存储默认值 [英] How to store a default value in SharedPreferences

查看:63
本文介绍了如何在 SharedPreferences 中存储默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个餐厅应用程序,该应用程序由注册/登录系统的会员和非会员通过跳过注册/登录过程查看菜单组成.我的主屏幕有菜单(供非会员直接查看)、登录注册按钮(供会员注册/登录).我想将默认的 phoneId 和密码存储到 SharedPreference 中,让非会员"跳过登录/注册过程(p/s 仅非会员自动登录)来查看菜单.但是,我总是面临 nullPointerException 错误,并且无法让非会员在按下菜单按钮时查看.不知道哪里错了,因为我只是一个初学者和学习过程.

I am creating a restaurant app that consist of members to register/login into the system and non-members to view the menu by skipping registering/login process. My homescreen has menu (for non-members to view directly), sign-in and sign-up buttons (for members to register/login). I want to store a default phoneId and password into SharedPreference to let 'non-members' to view the menu by skipping login/registering process(p/s auto-login for only non-members). However, I always face nullPointerException error and failed to let non-members to view when they press the menu button. I do not know where is wrong because I am just a beginner and learning process.

常量.java

public class Constant {
public static final String DEFAULT_PHONE_ID = "9876543210";
public static final String DEFAULT_PASSWORD = "12345";
}

AppPreferences.java

AppPreferences.java

public class AppPreferences {

// Class variables
private Context context;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
public static final String PREF_NAME = "iMenuApp";
private int PRIVATE_MODE = 0;

// Define your preferences key
private static final String USER_PHONE = "9876543210";
private static final String USER_PASSWORD = "12345";

private AppPreferences(Context context)
{
    this.context = context;
    sharedPreferences = this.context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);

    if (sharedPreferences != null)
    {
        editor = sharedPreferences.edit();
    }
}

//Store user PhoneId


public void setUserPhoneId(String userId){
    String TAG = "AppPref:setUserId";
    try
    {
        editor.putString(USER_PHONE, userId);
        editor.commit();
    } catch (Exception e) {
        Log.e(TAG, String.valueOf(e));
    }
}

// Get userPhoneId
public String getUserPhoneId(){
    return sharedPreferences.getString(USER_PHONE,"default_phone");
}

//Store userPassword
public void setUserPassword(String userPassword){
    String TAG = "AppPref:setUserPassword";
    try
    {
        editor.putString(USER_PASSWORD, userPassword);
        editor.commit();
    } catch (Exception e) {
        Log.e(TAG, String.valueOf(e));
    }
}

// Get userPassword
public String getUserPassword(){
    return sharedPreferences.getString(USER_PASSWORD,"default_password");
}


}

MainActivity.java

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button btnSignIn, btnSignUp, btnMenu;
public AppPreferences appPreference;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnMenu = (Button)findViewById(R.id.btnMenu);
    btnSignUp = (Button)findViewById(R.id.btnSignUp);
    btnSignIn = (Button)findViewById(R.id.btnSignIn);



    btnMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent home = new Intent(MainActivity.this, Home.class);
            //Here save user info to preferences
            appPreference.setUserPhoneId(Constant.DEFAULT_PHONE_ID);
            appPreference.setUserPassword(Constant.DEFAULT_PASSWORD);
            startActivity(home);


        }
    });

    btnSignUp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent signUp = new Intent(MainActivity.this, SignUp.class);
            startActivity(signUp);
        }
    });

    btnSignIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent signIn = new Intent(MainActivity.this, SignIn.class);
            startActivity(signIn);
        }
    });
}
}

我需要跟踪非会员的交易订单,所以我需要为所有非会员设置一个默认的 phoneId 和密码.

I need to track the transaction orders for the non-members so i need to set all non-members under a default phoneId and password.

推荐答案

您需要在访问其方法和默认值之前初始化应用首选项对象,如果未找到键值,您可以从首选项返回.

You need to initialise the app preference object before accessing its method and default values you could return from preference if the key values not found.

 sharedPreferences.getString(USER_PHONE,"default_phone");

这篇关于如何在 SharedPreferences 中存储默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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