How to store a default value in SharedPreferences

怎甘沉沦 提交于 2020-01-07 09:30:08

问题


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.

Constant.java

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

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

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);
        }
    });
}
}

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.


回答1:


You never initialized appPreference in your MainActivity.

Do that under onCreate():

appPreference = new AppPreferences(this);



回答2:


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");


来源:https://stackoverflow.com/questions/52688785/how-to-store-a-default-value-in-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!