how to avoid NPE with android activity
<p>i have my application where i am performing the log in functionality from the php site,i am able to getting login functionality done.</p>

<p>now to create user session i am using following code</p>

<pre><code>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&lt;String, String&gt; getUserDetails(){
        HashMap&lt;String, String&gt; user = new HashMap&lt;String, String&gt;();
        // 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);
    }
}
</code></pre>

<p>now my login activity is like</p>

<pre><code>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() &gt; 0 &amp;&amp; password.trim().length() &gt; 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--&gt;", "after httpclient");

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

            List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            Log.e("Responce--&gt;", "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--&gt;", "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();
        }

    }
}
</code></pre>

<p>my question is that where to put the below line so that it works correctly</p>

<pre><code>session.createLoginSession("dealnowsp", username)
</code></pre>
