Android SharedPreferences空指针

时间:2017-06-30 05:43:28

标签: android nullpointerexception sharedpreferences

帮我解决android SharedPreferences,登录后我有登录活动设置SharedPreferences,但设置SharedPreferences时总是错误空指针。我尝试用toast显示值,所有变量都有值。这是我的活动

public class LoginNewActivity extends Activity {

    public SessionManager session;

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

        TextView toRegister = (TextView) findViewById(R.id.link_to_register);
        toRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(i);
            }
        });

        final EditText etUsnm = (EditText) findViewById(R.id.tuserid);
        final EditText etPswd = (EditText) findViewById(R.id.tpasswd);
        Button bLogin = (Button) findViewById(R.id.btnLogin);
        bLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String username = etUsnm.getText().toString();
                String password = etPswd.getText().toString();
                new UserLoginTask().execute(username, password);
            }
        });
    }

    public class UserLoginTask extends AsyncTask<String, String, JSONObject> {

        ProgressDialog pdLoading = new ProgressDialog(LoginNewActivity.this);
        HttpURLConnection conn;
        URL url = null;
        JSONParser jsonParser = new JSONParser();

        private static final String TAG_MESSAGE = "message";
        private static final String TAG_NAMA = "nama_user";
        private static final String TAG_USERNAME = "username";
        private static final String TAG_HAKAKSES = "role";
        private static final String TAG_ERROR = "error";
        private static final String LOGIN_URL = "http://192.168.1.101/mlls/getLoginNew.php";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected JSONObject doInBackground(String... args) {
            try {

                HashMap<String, String> params = new HashMap<>();
                params.put("username", args[0]);
                params.put("password", args[1]);

                Log.d("request", "starting");

                JSONObject json = jsonParser.makeHttpRequest(
                        LOGIN_URL, "POST", params);

                if (json != null) {
                    Log.d("JSON result", json.toString());

                    return json;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(JSONObject json) {
            String nama = "";
            int iduser = 0;
            String email = "";
            String hakakses = "";
            int error_message = 0;


            if (json != null) {
                //Toast.makeText(LoginActivity.this, json.toString(),
                //Toast.LENGTH_LONG).show();

                try {
                    nama = json.getString(TAG_NAMA);
                    email = json.getString(TAG_USERNAME);
                    hakakses = json.getString(TAG_HAKAKSES);
                    error_message = json.getInt(TAG_ERROR);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
            if(error_message == 1) {
                pdLoading.dismiss();
                session.setLogin(true);
                session.setStatus(hakakses);
                session.setNama(nama);
                session.setUsername(email);
                session.setId(iduser);

                Toast.makeText(LoginNewActivity.this, hakakses,
                Toast.LENGTH_LONG).show();

                    //Intent intent = new Intent(LoginNewActivity.this, LessonListActivity.class);
                    //intent.putExtra("nama", nama);
                    //intent.putExtra("email", email);
                    //intent.putExtra("hakakses", hakakses);
                    //startActivity(intent);
                    //LoginNewActivity.this.finish();
            }else{
                Toast.makeText(getApplicationContext(), "User ID atau Password anda salah.", Toast.LENGTH_LONG).show();
            }

        }
    }}

这是我的sharedPreferences

public class SessionManager {
    private static String TAG = SessionManager.class.getSimpleName();

    SharedPreferences pref;

    Editor editor;
    Context _context;

    int PRIVATE_MODE = 0;

    private static final String PREF_NAME = "Hlls";
    private static final String KEY_IS_LOGGEDIN = "isLoggenIn";
    private static final String KEY_IS_USER = "isStatus";
    private static final String KEY_IS_NAMA = "isNama";
    private static final String KEY_IS_USERNAME = "isUsername";
    private static final String KEY_IS_IDUSER = "isIdUser";

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

    public void setLogin(boolean isLoggedIn){
        editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
        editor.commit();
        Log.d(TAG, "User login session modified");
    }

    public void setId(int isIdUser){
        editor.putInt(KEY_IS_IDUSER, isIdUser);
        editor.commit();
        Log.d(TAG, "ID User akses session modified");
    }

    public void setStatus(String isStatus){
        editor.putString(KEY_IS_USER, isStatus);
        editor.commit();
        Log.d(TAG, "User akses session modified");
    }

    public void setNama(String isNama){
        editor.putString(KEY_IS_NAMA, isNama);
        editor.commit();
        Log.d(TAG, "Username session modified");
    }

    public void setUsername(String isUsername){
        editor.putString(KEY_IS_USERNAME, isUsername);
        editor.commit();
        Log.d(TAG, "Username session modified");
    }

    public String isNama(){
        return pref.getString(KEY_IS_NAMA, "");
    }

    public int isId(){
        return pref.getInt(KEY_IS_IDUSER, 0);
    }

    public String isUsername(){
        return pref.getString(KEY_IS_USERNAME, "");
    }


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

    public String isStatus(){
        return pref.getString(KEY_IS_USER, "");
    }
}

帮我解决这个错误,抱歉英文不好

4 个答案:

答案 0 :(得分:1)

  

当应用程序尝试使用时抛出NullPointerException   具有空值的对象引用。

您应该在 ONCREATE 部分调用此内容。

  session=new SessionManager(LoginNewActivity.this);

<强>最后

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    session=new SessionManager(LoginNewActivity.this);

答案 1 :(得分:0)

使用私人模式而非私人模式

pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

它是android自己提供的标志,你不需要为它分配任何其他标志。

并且您尚未初始化会话管理器上下文为null。

答案 2 :(得分:0)

我猜你没有初始化你的共享偏好课程。

SessionManager session  =  new SessionManager(this);

如果是真的

请尝试将其作为一般练习使其成为单身课程

像这样的东西

     public final class PreferenceManager {

 private static SharedPreferences preferences;

    /**
     * Private constructor to restrict the instantiation of class.
     */
    private PreferenceManager() {
        throw new AssertionError();
    }
         public static SharedPreferences getInstance(Context context) {
        if (preferences == null && context != null) {
            preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
           }
        return preferences;
    }

     }

答案 3 :(得分:0)

您需要在Activity中执行以下操作:

session = new SessionManager(LoginNewActivity.this);

你还没有创建SessionManager类的对象,所以它的构造函数永远不会被调用,你得到了NPE。