-2

Help me on android SharedPreferences, I have login activity when after login will set the SharedPreferences, but when set SharedPreferences always error null pointer. I try to show the value with toast and all variable have value. this my activity

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

        }
    }}

and this is my 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, "");
    }
}

help me for this error, sorry for bad english

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Drz
  • 55
  • 8

4 Answers4

1

NullPointerException is thrown when an application attempts to use an object reference that has the null value .

You should call this in your ONCREATE section .

  session=new SessionManager(LoginNewActivity.this);

Finally

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    session=new SessionManager(LoginNewActivity.this);
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0

Use mode private instead of private mode

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

It is flag provided by android itself you need not assign any other flag to it.

and you have not initialized session manager context is null.

santosh kumar
  • 2,952
  • 1
  • 15
  • 27
0

I guess you are not initializing your Shared Preference class.

SessionManager session  =  new SessionManager(this);

In case its true

Please try and make it a singleton class as a general practise

Something like 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;
    }

     }
MRX
  • 1,400
  • 3
  • 12
  • 32
0

You need to do the following in your Activity:

session = new SessionManager(LoginNewActivity.this);

You have not created the object of your SessionManager class, so its constructor never gets called and you get NPE.

gprathour
  • 14,813
  • 5
  • 66
  • 90