如何从共享首选项中获取值并使用if

时间:2017-02-06 06:00:18

标签: android android-studio

您好我正在使用用户登录屏幕。我正在使用共享首选项来存储用户详细信息并存储用户是否登录。我正在使用启动画面,在该启动活动中,我检查了共享首选项中的值,以了解用户是否已登录。如果用户已登录,则在启动后它将转到仪表板,否则将转到登录屏幕。但我得到空指针错误。请帮助我。

我的共享优先级是:

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

    }


}

我的闪屏幕是:

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

我的错误是:

        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)

4 个答案:

答案 0 :(得分:2)

确保在查询之前初始化您的共享首选项。放一个断点并调试。

答案 1 :(得分:2)

您正在直接使用Userloginsession.isuserLoggedIn() 像这样使用它

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

问题是您没有初始化共享首选项。 IE浏览器。 Userloginsession未初始化。为此,您需要提供活动上下文

整体课程应该是

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

答案 2 :(得分:2)

user_details共享偏好为空..

你的Splash活动中的

将其初始化为:

Userloginsession session = new Userloginsession(Splashscreen.this);
if (session.isuserLoggedIn()) {

答案 3 :(得分:0)

首先创建一个单独的Preference类

PrefManager.java

package name;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import java.util.HashMap;

/**
 * Created by Ravi on 08/07/15.
 */
public class PrefManager {
    // Shared Preferences
    SharedPreferences pref;

    // Editor for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "MegaInfomatix";

    // All Shared Preferences Keys
    private static final String KEY_IS_WAITING_FOR_SMS = "IsWaitingForSms";
    private static final String KEY_MOBILE_NUMBER = "mobile_number";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
    private static final String KEY_NAME = "name";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_MOBILE = "mobile";

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }

    public void setIsWaitingForSms(boolean isWaiting) {
        editor.putBoolean(KEY_IS_WAITING_FOR_SMS, isWaiting);
        editor.commit();
    }

    public boolean isWaitingForSms() {
        return pref.getBoolean(KEY_IS_WAITING_FOR_SMS, false);
    }

    public void setMobileNumber(String mobileNumber) {
        editor.putString(KEY_MOBILE_NUMBER, mobileNumber);
        editor.commit();
    }

    public String getMobileNumber() {
        return pref.getString(KEY_MOBILE_NUMBER, null);
    }

    public void createLogin(String name, String email, String mobile) {
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_EMAIL, email);
        editor.putString(KEY_MOBILE, mobile);
        editor.putBoolean(KEY_IS_LOGGED_IN, true);
        editor.commit();
    }

    public boolean isLoggedIn() {
        return pref.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public void clearSession() {
        editor.clear();
        editor.commit();
    }

    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> profile = new HashMap<>();
        profile.put("name", pref.getString(KEY_NAME, null));
        profile.put("email", pref.getString(KEY_EMAIL, null));
        profile.put("mobile", pref.getString(KEY_MOBILE, null));
        return profile;
    }
}

在LoginActivity类和onCreate方法中执行此操作 在onCreate方法之前创建首选项类对象

Preference pref;
pref = new PrefManager(this);

if (pref.isLoggedIn()) {
            Intent intent = new Intent(SmsActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

            finish();
        }