2013-05-12 57 views
0

我有我的應用程序,我在執行登錄功能從PHP網站,我能夠獲得登錄功能完成。如何避免NPE與Android活動

立即創建我使用下面的代碼的用戶會話

sessionmanager.java 
public class SessionManager { 
    // Shared Preferences 
    SharedPreferences pref; 

    // Editor for Shared preferences 
    Editor editor; 

    // Context 
    Context _context; 

    // Shared pref mode 
    int PRIVATE_MODE = 0; 

    // Sharedpref file name 
    private static final String PREF_NAME = "dealnowsp"; 

    // All Shared Preferences Keys 
    private static final String IS_LOGIN = "IsLoggedIn"; 

    // User name (make variable public to access from outside) 
    public static final String KEY_NAME = "name"; 

    // Email address (make variable public to access from outside) 
    public static final String KEY_EMAIL = "email"; 

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

    /** 
    * Create login session 
    * */ 
    public void createLoginSession(String name, String userid){ 
     // Storing login value as TRUE 
     editor.putBoolean(IS_LOGIN, true); 

     // Storing email in pref 
     editor.putString(KEY_EMAIL, userid); 

     // commit changes 
     editor.commit(); 
    } 

    /** 
    * Check login method wil check user login status 
    * If false it will redirect user to login page 
    * Else won't do anything 
    * */ 
    public void checkLogin(){ 
     // Check login status 
     if(!this.isLoggedIn()){ 
      Intent i = new Intent(_context, Login.class); 
      i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

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

    } 



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

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

     // return user 
     return user; 
    } 

    /** 
    * Clear session details 
    * */ 
    public void logoutUser(){ 
     // Clearing all data from Shared Preferences 
     editor.clear(); 
     editor.commit(); 

     Intent i = new Intent(_context, MainActivity.class); 
     // Closing all the Activities 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     // Add new Flag to start new Activity 
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

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

    /** 
    * Quick check for login 
    * **/ 
    // Get Login State 
    public boolean isLoggedIn(){ 
     return pref.getBoolean(IS_LOGIN, false); 
    } 
} 

現在我的登錄活動就像是

public class Login extends Activity { 

    Button home,login; 
    EditText uname,pword; 
    Context context; 
    SessionManager session; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 
     getActionBar().setDisplayHomeAsUpEnabled(true); 

     uname = (EditText) findViewById(R.id.txtuserid); 
     pword = (EditText) findViewById(R.id.txtuserpass); 

     addListenerOnHome(); 
     addListenerOnBtnlogin(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_login, menu); 
     return true; 
    } 


    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case android.R.id.home: 
       NavUtils.navigateUpFromSameTask(this); 
       return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    public void addListenerOnHome() { 
     final Context context = this; 
     home = (Button)findViewById(R.id.btnhome); 
     home.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent intent = new Intent(context,MainActivity.class); 
       startActivity(intent); 
      } 
     }); 
    } 

    public void addListenerOnBtnlogin() { 
     context = this; 
     login = (Button)findViewById(R.id.btnlogin); 
     login.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       final String username = uname.getText().toString();   
       final String password = pword.getText().toString(); 
       if(username.trim().length() > 0 && password.trim().length() > 0){ 
        Thread t = new Thread() { 
        public void run() { 
         postLoginData(username,password); 
        } 
       }; 
       t.start(); 
       } 
       else{ 
        Toast.makeText(context, "username or password empty", Toast.LENGTH_SHORT).show(); 
       } 
       } 
     }); 
    } 

    private void postLoginData(String username,String password) { 

     try { 
      // Create a new HttpClient and Post Header 
      HttpClient httpclient = new DefaultHttpClient(); 
      Log.e("Response-->", "after httpclient"); 

      HttpPost httppost = new HttpPost("http://10.0.2.2/dealnow/login.php"); 
      Log.e("Response-->", "after httppost"); 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("username", username)); 
      nameValuePairs.add(new BasicNameValuePair("password", password)); 

      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      Log.e("Responce-->", "after using the list name pair"); 

      // Execute HTTP Post Request 
      Log.w("SENCIDE", "Execute HTTP Post Request"); 
      HttpResponse response = httpclient.execute(httppost); 
      Log.e("Responce-->", "after execute the http response"); 
      String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8); 

      if (str.toString().equalsIgnoreCase("true")) { 
       session.createLoginSession("dealnowsp", username); //here is where i am getting NPE even if i declare username variable at class level 
       runOnUiThread(new Runnable() { 
        public void run() { 

         Toast.makeText(context, "Login Successful...!", Toast.LENGTH_SHORT).show(); 
         Intent intent = new Intent(context,MainActivity.class); 
         startActivity(intent); 

        } 
       }); 


      } else { 
       session.logoutUser(); 
       runOnUiThread(new Runnable() { 
        public void run() { 
         Toast.makeText(context, "Incorrect username or password", Toast.LENGTH_SHORT).show(); 

        } 
       }); 
      } 

     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 
} 

我的問題是,哪裏放下面的行,以便它能夠正常工作

session.createLoginSession("dealnowsp", username) 
+0

爲什麼一個活動應該有一個名爲'context'的字段指向自己? – Sulthan 2013-05-12 12:46:52

回答

1

你可以把它放在this.session = new SessionManager(this);之後的任何地方。

+0

你能告訴我把activity放在我的activity.java的哪裏嗎? – 2013-05-12 12:50:17

+0

sry class登錄 – 2013-05-12 12:51:41

+0

@KaranMer你應該能夠自己想象...... okey,'onCreate'是一種可能性。或'onStarted'。 – Sulthan 2013-05-12 12:58:27