Search code examples
androidsharedpreferencessession-management

session management in android using sharedpreferences


hi i successfully develped one login form with mysql database via soap webservices.here i wish to make session management.but i can't able to develop.so please help me.when i fill in the username and password is successful means it is go to next activity.the next activity have to displayed username.also if i click logout button means it is move to login form.now i ll go back means it is redirect to login page only...didnot go to displayed username activity.please guide me.

my code is:

package com.androidlogin.ws;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

 public class AndroidLoginExampleActivity extends Activity {
 private final String NAMESPACE = "http://ws.userlogin.com";
 private final String URL = "http://111.223.128.10:8085/AndroidLogin/services/Login?wsdl";
 private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
 private final String METHOD_NAME = "authentication";
 /** Called when the activity is first created. */
 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button login = (Button) findViewById(R.id.btn_login);
    login.setOnClickListener(new View.OnClickListener() {

 public void onClick(View arg0) {
loginAction();

}
});
}

private void loginAction(){
 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    EditText userName = (EditText) findViewById(R.id.tf_userName);
    String user_Name = userName.getText().toString();
    EditText userPassword = (EditText) findViewById(R.id.tf_password);
    String user_Password = userPassword.getText().toString();

  //Pass value for userName variable of the web service
    PropertyInfo unameProp =new PropertyInfo();
    unameProp.setName("userName");//Define the variable name in the web service method
    unameProp.setValue(user_Name);//set value for userName variable
    unameProp.setType(String.class);//Define the type of the variable
    request.addProperty(unameProp);//Pass properties to the variable

  //Pass value for Password variable of the web service
    PropertyInfo passwordProp =new PropertyInfo();
    passwordProp.setName("password");
    passwordProp.setValue(user_Password);
    passwordProp.setType(String.class);
    request.addProperty(passwordProp);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try{
        androidHttpTransport.call(SOAP_ACTION, envelope);
           SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

           TextView result = (TextView) findViewById(R.id.tv_status);
           result.setText(response.toString());
       if(status.equals("Success!"))
               {

                   //   ADD  to save  and  read next time
                       String strUserName = userName.getText().toString().trim();
                       String strPassword = userPassword.getText().toString().trim();
                       if (null == strUserName || strUserName.length() == 0)
                                   {
                           //  showToast("Enter Your Name");
                         userName.setError( "username is required!" );
isUserValidated = false;
                       }
 if (null == strPassword || strPassword.length() == 0)
                                   {
                               //      showToast("Enter Your Password");
 isPasswordValidated = false;
                         userPassword.setError( "password is required!" );
                       } 
 if(isUserValidated = true && isPasswordValidated == true)
                                   {

                           if (chkRememberMe.isChecked())
                                           {
                               SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
                               loginPreferences.edit().putString(USERNAME, strUserName).putString(PASSWORD, strPassword).commit();
                           } else
                                           {
                               SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
                               loginPreferences.edit().clear().commit();
                                           }
        }

        if(isUserValidated && isPasswordValidated)
     {
               Intent intent = new Intent(Login.this,HomePage.class);
                  **intent.putExtra("username",userName.getText().toString());**
                  startActivity(intent);
         }
      else
       {
     // what ever you want to do if the data in the EditText is not validated.
    //Maybe restart the same intent ?    
      // Intent i = new Intent(getApplicationContext(), Login.class);    startActivity(i);


         }

                                   }

                       else
                          {
                           Intent i = new Intent(getApplicationContext(), Login.class);
                             startActivity(i);
                          }
                         }



    catch(Exception e){

    }
   }

  }

How is make session concepts using shared preferences in dis android login form application.

Thank You


Solution

  • You can easily implement this, if you use SharedPreferences and the Activities lifecycle.

    Let's say you have Activity A - the display loging Activity, and Activity B - the logout Activity + display username Activity.

    In Activity A, in your loginAction() method, put a boolean flag to track if the user is logged. If the user is valid, perform the login actions, set that flag to TRUE, than start your Activity B.

    In Activity B in the onResume() method, make a check each time, if the flag is TRUE or FALSE. If the flag is TRUE do nothing, if the flag is FALSE start Activity A (back to login screen). Something like:

    @Override
    protected void onResume() {
        super.onResume();
    
        boolean isLogged = <yourSharedPrefs>.getBoolean(IS_LOGGED, Boolean.FALSE);
    
        if (!isLogged) {
                        //here start your login Activity
            startActivity(new Intent(this, ActivityA.class));
        }
    
    }
    

    The logout button in Activity B, should set the flag to FALSE and than start Activity A.

    This way when you click the back button, your app will load Activity B, but the check in onResume() will detect that the user is not logged, and Activity A will be started.