I'm new to android. I use Shared Preferences named "MyPref" to store and retrieve values. The code logic is, "MyPref" stores userid, usertype (customer, driver). In my SplashActivity
I have written the following code. If user id is not null and user type equals either customer or driver the activity should navigate accordingly. But I get the following error: Kindly help
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();
}
}