lucky lucky - 4 years ago 104
Android Question

How to get values from shared preference and check it using if

I am using user login screen. In that I am using shared preferences to store the user details and store whether the user is logged in or not. I am using splash screen and in that splash activity I checked a value from

SharedPreference
to know whether the user is already logged in or not. If the user logged in, then after splash it will go to dashboard otherwise it goes to login screen. But I am getting NullPointerException. please help me. My shared preference class is

public class Userloginsession {

public static final String IS_User_login = "isuserloggedin";
// {"did":"1","drivername":"arul ji","dusername":"PIKDRIVER01","logid":"79"}
//Driver Login details
//From DRIVER
public static final String IS_SNO = "sno";
public static final String IS_USERNAME = "userloginname";
public static final String IS_USERPASSWORD = "userloginpassword";
//
public static final String IS_EMP_ID = "emp_id";
//
//From Json Driver
public static final String IS_FIRST_NAME = "first_name";
public static final String IS_LAST_NAME = "last_name";
public static final String IS_IMAGE = "image";

static SharedPreferences user_details;
// Editor Reference for sharedpref
SharedPreferences.Editor user_details_editor;

public Userloginsession(final Context applicationContext) {

// create sharedpreff file "driverSession" for DRIVERLOGINACTIVITY
user_details = applicationContext.getSharedPreferences("usersession",0);

//Edit pfeff file
user_details_editor = user_details.edit();
user_details_editor.apply();


}
public static boolean isuserLoggedIn() {
return user_details.getBoolean(IS_User_login, false);
}
public void createuserLogin(String passwordp, String username, String SNO, final String EMP_ID, final String FIRST_NAME, final String LAST_NAME, final String Image) {
user_details_editor.putBoolean(IS_User_login, true);
user_details_editor.putString(IS_USERNAME, username);
user_details_editor.putString(IS_USERPASSWORD, passwordp);
user_details_editor.putString(IS_SNO, SNO);
user_details_editor.putString(IS_EMP_ID, EMP_ID);
user_details_editor.putString(IS_FIRST_NAME, FIRST_NAME);
user_details_editor.putString(IS_LAST_NAME, LAST_NAME);
user_details_editor.putString(IS_IMAGE, Image);
user_details_editor.commit();
}

public HashMap<String, String> isGetuserDetails() {
// Use hashmap to store user credentials
final HashMap<String, String> userdetailsmap = new HashMap<>();

// Driv pass
userdetailsmap.put(IS_USERNAME, user_details.getString(IS_USERNAME, null)); // Driv Pass

// Driver user name
userdetailsmap.put(IS_USERPASSWORD, user_details.getString(IS_USERPASSWORD, null));

// Driver ID
userdetailsmap.put(IS_SNO, user_details.getString(IS_SNO, null));

//Driver Name
userdetailsmap.put(IS_EMP_ID, user_details.getString(IS_EMP_ID, null));
userdetailsmap.put(IS_FIRST_NAME, user_details.getString(IS_FIRST_NAME, null));
userdetailsmap.put(IS_LAST_NAME, user_details.getString(IS_LAST_NAME, null));
userdetailsmap.put(IS_IMAGE, user_details.getString(IS_IMAGE, null));

return userdetailsmap;
}

public void clearAllvalues() {

user_details_editor = user_details.edit();
user_details_editor.clear();
user_details_editor.apply();

}


}


my splashscreen acticty is :

public class Splashscreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;

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

new Handler().postDelayed(new Runnable() {

/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/

@Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity

if (Userloginsession.isuserLoggedIn()) {
// startActivity(new Intent(MainActivity.this, RideHistry.class));
startActivity(new Intent(Splashscreen.this, Dashboard.class));
/*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
finish();


} else {
// if driver not login go to DriverLogin Activity
startActivity(new Intent(Splashscreen.this, MainActivity.class));

finish();
}
/*} else {
startActivity(new Intent(Splashscreen.this, MainActivity.class));

finish();
}*/
}
}, SPLASH_TIME_OUT);
}
}


My error is:

Process: com.example.notebook.dptextiles, PID: 214
java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.content.SharedPreferences.getBoolean(java.lang.String, boolean)' on a null object reference at com.example.notebook.dptextiles.fragments.Userloginsession.isuserLoggedIn(Userloginsession.java:45
at com.example.notebook.dptextiles.Splashscreen$1.run(Splashscreen at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

Answer Source

You are using Userloginsession.isuserLoggedIn() directly use it like this

Userloginsession login=new Userloginsession(getApplicationContext());
if (login.isuserLoggedIn())

The problem is your are not initializing the sharedpreference

the overall class should be

public class Splashscreen extends AppCompatActivity {
    private static int SPLASH_TIME_OUT = 3000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splashscreen2);
        Userloginsession login=new Userloginsession(getApplicationContext());
        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity

                    if (login.isuserLoggedIn()) {
//                        startActivity(new Intent(MainActivity.this, RideHistry.class));
                        startActivity(new Intent(Splashscreen.this, Dashboard.class));
                    /*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
                        finish();


                    } else {
                        //   if driver not login go to DriverLogin Activity
                        startActivity(new Intent(Splashscreen.this, MainActivity.class));

                        finish();
                    }
                /*} else {
                    startActivity(new Intent(Splashscreen.this, MainActivity.class));

                    finish();
                }*/
            }
        }, SPLASH_TIME_OUT);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download