2015-12-24 111 views
0

我正在登錄屏幕上工作,我必須輸入電子郵件ID和密碼。登錄成功後,我想將電子郵件ID存儲在Shared Preference中,以便下次登錄時,不得不輸入電子郵件Id.I使用SessionManager類來執行此操作。Android中的會話管理

1.SessionMAnager.java

public class SessionManager { 
SharedPreferences pref; 
SharedPreferences.Editor editor; 
Context context; 
//Shared Preferences file name 
private static final String PREFERENCE_NAME = "SessionManager"; 
// Shared Preferences Keys 
private static final String IS_USER_LOGIN = "IsUserLoggedIn"; 
//Email Address 
public static final String KEY_EMAIL = "email"; 

//Constructor 
public SessionManager(Context context) { 
    this.context = context; 
    pref = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_MULTI_PROCESS); 
    editor = pref.edit(); 
} 

//Create Login session 
public void createUserLoginSession(String email) { 

    // Storing login value as TRUE 
    editor.putBoolean(IS_USER_LOGIN, true); 
    //Storing email in pref 
    editor.putString(KEY_EMAIL, email); 
    //editor.putBoolean(IS_USER_LOGIN,true); 
    editor.commit(); 
} 

/** 
* Check login method will check user login status 
* If false it will redirect user to login page 
* Else do anything 
*/ 

public boolean checkLogin() { 
    // Check login status 
    if (!this.isUserLoggedIn()) { 

     // user is not logged in redirect him to Login Activity 
     Intent i = new Intent(context, Activity_LogInScreen.class); 

     // Staring Login Activity 
     context.startActivity(i); 

     return true; 
    } 
    return false; 
} 

/** 
* Get stored session data 
*/ 
public HashMap<String, String> getUserDetails() { 

    //Use hashmap to store user credentials 
    HashMap<String, String> user = new HashMap<String, String>(); 

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

    // return user 
    return user; 
} 

/** 
* Clear session details 
*/ 
public void logoutUser() { 

    // Clearing all user data from Shared Preferences 
    editor.clear(); 
    editor.commit(); 

    // After logout redirect user to Login Activity 
    Intent i = new Intent(context, Activity_LogInScreen.class); 

    // Staring Login Activity 
    context.startActivity(i); 
} 

// Check for login 
public boolean isUserLoggedIn() { 
    return pref.getBoolean(IS_USER_LOGIN, false); 
} 

}

2.Activity_LoginScreen.java

public class Activity_LogInScreen extends Activity implements OnClickListener { 

private EditText editText; 
private EditText editTextpassword; 

private Button btn_SignUp; 
private Button btn_LogIn; 

public String get_User, get_Password; 
private CheckConnectionInternet obj; 
private TransparentProgressDialog dialog; 
private SharedPreferences prefs; 
JSONObject jsonObj; 
public Model_LoginDetails objLoginDetails; 
private ArrayList<Model_LoginDetails> arr_LogInUserDetails = new ArrayList<Model_LoginDetails>(); 
AlmabayDatabase almabayDatabase; 
SQLiteDatabase sqLiteDatabase; 
//SessionManager class 
SessionManager sessionManager; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    setContentView(R.layout.activity_loginscreen); 

    sessionManager = new SessionManager(this); 
    dialog = new TransparentProgressDialog(Activity_LogInScreen.this, R.drawable.loader); 
    prefs = this.getSharedPreferences(Prefs_Registration.pacakgename, Context.MODE_PRIVATE); 
    obj = new CheckConnectionInternet(); 
    almabayDatabase = new AlmabayDatabase(this); 
    editText = (EditText) findViewById(R.id.edt_useremailId); 
    editTextpassword = (EditText) findViewById(R.id.edt_userpassword); 
    editText.getBackground().setColorFilter(Color.parseColor("#ffffff"), 
      PorterDuff.Mode.SRC_ATOP); 
    editTextpassword.getBackground().setColorFilter(
      Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_ATOP); 
    // Checking whether database contains the emailID or not 
    /* if (almabayDatabase.getEmailFromAccessTAble() != null) { 
     get_User = almabayDatabase.getEmailFromAccessTAble(); 
     editText.setText(get_User); 
    }*/ 
Boolean userLoogein = sessionManager.isUserLoggedIn(); 
    Log.e("IslOOgedIn", String.valueOf(userLoogein)); 

    // get user data from session 
    HashMap<String, String> user = sessionManager.getUserDetails(); 
    // get email 
    String email = user.get(SessionManager.KEY_EMAIL); 
    Log.e("email",email); 


    btn_SignUp = (Button) findViewById(R.id.btn_SignUp); 
    btn_LogIn = (Button) findViewById(R.id.btn_login); 
    btn_SignUp.setOnClickListener(this); 
    btn_LogIn.setOnClickListener(this); 
} 

@Override 
public void onClick(View arg0) { 
    switch (arg0.getId()) { 
     case R.id.btn_login: 
      get_User = editText.getText().toString(); 
      get_Password = editTextpassword.getText().toString(); 

      if ((get_User.equals("")) || (get_Password.equals(""))) { 
       Toast.makeText(Activity_LogInScreen.this, "Fill Empty Field", Toast.LENGTH_LONG).show(); 
      } else { 
       if (obj.isOnline(Activity_LogInScreen.this) == true) { 
        JARLogIn jar_Login = new JARLogIn(Activity_LogInScreen.this) { 

         private String status_Login; 

         @Override 
         public void result(String object) { 
          Log.e("Respose", object); 
          dialog.show(); 
          try { 
           jsonObj = new JSONObject(object); 
           status_Login = jsonObj.getString("statusCode"); 
          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 
if (status_Login.equals("200")) { 

           String user_Id; 
           String access_token; 
           try { 
            JSONObject detailsObject = jsonObj.getJSONObject("detail"); 
            String get_Id = detailsObject.getString("id"); 
            String get_AccsToken = detailsObject.getString("access_token"); 
            String userId = detailsObject.getString("user_id"); 
            JSONObject jsonUserInfo = detailsObject.getJSONObject("userInfo"); 
            JSONObject jsonuser = jsonUserInfo.getJSONObject("userInfo"); 

            //user 
            JSONObject Json_user = jsonuser.getJSONObject("user"); 

            String str_thumbnail_url = Json_user.getString("thumbnail_url"); 
            String str_Name = Json_user.getString("name"); 
            String str_userSkills = Json_user.getString("userSkills"); 

            //create user's login session 
            sessionManager.createUserLoginSession(get_User); 

            // Delete the existing entries of AccessToken table 
            almabayDatabase.deleteAllFromAccessTable(); 

            // Inserting UserID,emailID and access token in the database 
            almabayDatabase.insertIntoAccessTable(Integer.parseInt(get_Id), get_User, get_AccsToken); 

            objLoginDetails = new Model_LoginDetails(detailsObject.getString("id"), detailsObject.getString("user_id"), detailsObject.getString("access_token"), str_thumbnail_url, str_Name, str_userSkills); 
            arr_LogInUserDetails.add(objLoginDetails); 

            save_ValueSession(userId, get_AccsToken, get_User, str_Name, arr_LogInUserDetails, str_thumbnail_url); 
            fun_empty_EditTextFields(); 
           } catch (JSONException e) { 
            e.printStackTrace(); 
           } 

          } else { 

           fun_empty_EditTextFields(); 
           Toast.makeText(Activity_LogInScreen.this, "User not found", Toast.LENGTH_LONG).show(); 

          } 
         } 
private void fun_empty_EditTextFields() { 
          dialog.cancel(); 
          editText.setText(""); 
          editTextpassword.setText(""); 
         } 
        }; 
        jar_Login.execute(get_User, get_Password); 
       } else { 
        Toast.makeText(Activity_LogInScreen.this, 
          "Connection Error", Toast.LENGTH_LONG).show(); 
       } 
      } 

      break; 

     case R.id.btn_SignUp: 
      fun_Intent(Activity_Registeration.class); 
      break; 

     default: 
      break; 
    } 
} 

在Activity_LoginScreen,我使用存儲EMAILID在共享偏好會話管理器類

//create user's login session 
            sessionManager.createUserLoginSession(get_User); 

這裏我得到NullPointerException.I知道把值它。但是,如果我使用它正在爲me.Please數據庫幫我解決這個問題之前,我正在訪問共享偏好。

+0

你能提供堆棧跟蹤嗎? –

+0

請提供可以更好理解的Stacktrace? – Ajinkya

回答

-1

在你的情況發生的問題可能是JSONObject可能工作的東西是null。 如果你提到你的堆棧跟蹤,可以說更多。

+0

這不提供問題的答案。一旦你有足夠的[聲譽](https://stackoverflow.com/help/whats-reputation),你將可以[對任何帖子發表評論](https://stackoverflow.com/help/privileges/comment);相反,[提供不需要提問者澄清的答案](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-c​​an- I-DO-代替)。 - [來自評論](/評論/低質量/職位/ 17216016) –

+0

好吧,謝謝你停止我的聲譽,然後降低它。所以那些可能知道這些概念但可能沒有足夠信譽的人最終只會查找。一個很好的方式來擴大社區,但仍然愚蠢 –

+0

順便說一句:我不是低調的選民。我希望很快你會有足夠的評論聲譽。 –