2

i am writing an android app and i am saving name and email in shared preferences when login in the login activity. in another activity i want to retrieve the email address and name for another usage. but i get null pointer exception. this is my session manager code:

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

    // Shared Preferences
    SharedPreferences pref;

    Editor editor;
    Context _context;

    // Shared pref mode
    int PRIVATE_MODE = 0;

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

    private static final String KEY_IS_LOGGEDIN = "isLoggedIn";

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

    public void setLogin(boolean isLoggedIn, String name, String email)
    {

        editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
        editor.putString("name", name);
        editor.putString("email", email);
        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

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

    /**
     * Get stored session data
     * */
    public HashMap<String, String> getUserDetails(){
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put("name", pref.getString("name", null));

        // user email id
        user.put("email", pref.getString("email", null));

        // return user
        return user;
    }

this is my login activity :

 JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String totalpoints = user.getString("totalpoints");
                    String digipoints = user.getString("digipoints");
                    String created_at = user.getString("created_at");
                    session.setLogin(true, name, email);

and this is the activity which i want to use shared preferences data in :

    public class Pointcalculator extends AppCompatActivity
{
    //  public SQLiteHandler db;

    // public HashMap<String, String> user = db.getUserDetails();

    //read the value from server
    public SessionManager session =new SessionManager(Pointcalculator.this);
    public  int totalpoints;
    public  int digipoints;
    public String ttlp;
    public String cp;
    private SharedPreferences mSharedPreferences;
    public   String email ;
    private SQLiteHandler db;

    //  String email = user.get("email");
    public ProgressDialog pD;
    private static final String TAG = Pointcalculator.class.getSimpleName();

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


    }
    public  void  digicalculator()
    {

         SessionManager session =new SessionManager(Pointcalculator.this);
        Log.d("hereeeeeeeeeeeeee","hereee");
       // db = new SQLiteHandler(getApplicationContext());
        HashMap<String, String> user = session.getUserDetails();
        email = user.get("email");
        Log.d("emailllll", email);

        fetchPoints(50, 1);

        // return digipoints;
    }

and finally this is my logcat :

    01-25 03:24:33.446  18091-18091/com.example.neshat.bluedot E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.neshat.bluedot, PID: 18091
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.neshat.bluedot/com.example.neshat.bluedot.Existedpoints}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
 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
        at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:169)
        at com.example.neshat.bluedot.helper.SessionManager.<init>(SessionManager.java:32)
        at com.example.neshat.bluedot.Pointcalculator.<init>(Pointcalculator.java:32)
        at com.example.neshat.bluedot.Existedpoints.<init>(Existedpoints.java:20)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at java.lang.Class.newInstance(Class.java:1572)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

my question is not duplicate because non of the answers worked for me.

user3696174
  • 123
  • 9

2 Answers2

1

This is my resolution,I can use it successfully:

 public class Shared {

    public static void putUInfo(Context context, String name, String passwd) {
        SharedPreferences settings = context.getSharedPreferences(
                StaticVar.UINFO, 0); // 首先获取一个 SharedPreferences 对象
        settings.edit().putString("UNAME", name).putString("PASSWD", passwd)
                .commit();
    }

    public static String getUName(Context context) {
        SharedPreferences settings = context.getSharedPreferences(StaticVar.UINFO, 0); // 获取一个
                                                                                // SharedPreferences
                                                                                // 对象
        return settings.getString("UNAME", ""); // 取出保存的 NAME
    }

    public static String getPasswd(Context context) {
        SharedPreferences settings = context.getSharedPreferences(StaticVar.UINFO, 0); // 获取一个
                                                                                // SharedPreferences
                                                                                // 对象
        return settings.getString("PASSWD", ""); // 取出保存的 NAME
    }
}
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
hongbochen
  • 123
  • 6
  • and how you call shared functions in another activity? – user3696174 Jan 25 '16 at 08:49
  • ok i have done all of this, I wrote exactly the code that is written in the link you ve mentioned but still i am getting this: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.neshat.bluedot.helper.PreferenceData.getStringFromPreference(java.lang.String)' on a null object reference – user3696174 Jan 25 '16 at 11:47
0

You are sending a null context to the SessionManager.

Try getContext(), getActivity().getContext() or getApplicationContext()in the place of "PointCalculator.this"

Example:

SessionManager session =new SessionManager(getContext());

Secondly, remove the field!! There is no need to have redundant instantiation of the "session" variable.

TejjD
  • 2,571
  • 1
  • 17
  • 37