2017-06-30 104 views
-2

幫我關於android SharedPreferences,我登錄後登錄活動時會設置爲SharedPreferences,但是當設置爲SharedPreferences時總是出錯的空指針。我試着用吐司來表明價值,所有變量都有價值。這是我的活動Android SharedPreferences空指針

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

幫我這個錯誤,對不起,英語不好

+0

你不會創建'session',只能使用它。 –

回答

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

使用模式私人,而不是私模

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

它是由android本身提供的標誌,您不需要爲其分配任何其他標誌。

並且您尚未初始化會話管理器上下文爲空。

0

我想你並沒有初始化你的Shared Preference類。

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

    } 
0

你需要做以下的Activity

session = new SessionManager(LoginNewActivity.this); 

您尚未創建SessionManager類的對象,所以它的構造函數永遠不會打電話,你會得到NPE。