检索存储在另一个活动的共享首选项中的值

时间:2016-01-25 08:28:13

标签: android sharedpreferences android-logcat

我正在编写一个Android应用程序,当我登录登录活动时,我在共享首选项中保存名称和电子邮件。在另一个活动中,我想检索另一个用法的电子邮件地址和名称。但我得到空指针异常。 这是我的会话管理器代码:

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

这是我的登录活动:

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

这是我想在以下位置使用共享偏好数据的活动:

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

最后这是我的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)

我的问题不重复,因为没有答案对我有效。

2 个答案:

答案 0 :(得分:1)

这是我的决议,我可以成功使用它:

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

答案 1 :(得分:0)

您正在向SessionManager发送空上下文。

在&#34; getContext()

的位置尝试getActivity().getContext()getApplicationContext()PointCalculator.this"
  

示例:

SessionManager session =new SessionManager(getContext());

其次,删除该字段!!没有必要对&#34; session&#34;进行冗余实例化。变量