如何避免NPE与android活动



我有我的应用程序,我从PHP网站执行登录功能,我能够获得登录功能完成。

现在创建用户会话我使用以下代码

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)

可以放在this.session = new SessionManager(this);之后的任何位置

最新更新