【发布时间】:2018-09-23 10:48:41
【问题描述】:
我是安卓新手。我使用名为“MyPref”的共享首选项来存储和检索值。代码逻辑是,“MyPref”存储了userid、usertype(客户、司机)。在我的SplashActivity 中,我编写了以下代码。如果用户 ID 不为空且用户类型等于客户或司机,则活动应相应导航。但我收到以下错误:请帮助
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
SplashActivity:
public class SplashActivity extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context context;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
pref = context.getSharedPreferences("MyPref", 0);
editor = pref.edit();
String userid=pref.getString("userid","");
Log.e("userid",userid);
if(userid!=null)
{
String usertype=pref.getString("usertype1","");
if(usertype.equals("customer"))
{
Intent customer=new Intent(SplashActivity.this, HomeFragment.class);
startActivity(customer);
}
else
{
Intent driver=new Intent(SplashActivity.this, DriverDashboardFragment.class);
startActivity(driver);
}
}
else
{
Intent walk=new Intent(SplashActivity.this,WalkThroughActivity.class);
startActivity(walk);
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
}
}, 2000);
}
@Override
protected void onResume() {
super.onResume();
}
}
【问题讨论】:
标签: android nullpointerexception sharedpreferences