Search code examples
javaandroidsessionsharedpreferencessession-management

Having trouble in Session management


i m working on an application and i want to make user login only when he/she logouts his previous session but i m unable to do it. whenever i close my program and re-open it. it directs to Homepage again even if i had'nt logout. plz

  package in.co.medimap.www.medimap;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;

import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import static in.co.medimap.www.medimap.R.layout.login;

/**
 * Created by sony on 28-04-2016.
 */
public class login extends Activity {
TextView signup_text;
Button login_button;
EditText PHONE_NO,PASSWORD;
AlertDialog.Builder builder;
public static final String MyPREFERENCE ="Myprefs";
public static final String PHONE="phone";
public static final String PASS="password";
SharedPreferences sharedPreferences;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);



    setContentView(R.layout.login);
    signup_text=(TextView)findViewById(R.id.sign_up);
    signup_text.setOnClickListener(new View.OnClickListener(){

                                       @Override
                                       public void onClick(View v) {
                                           startActivity(new Intent(login.this,register.class));
                                       }
                                   });
    PHONE_NO=(EditText)findViewById(R.id.phone_no);
    PASSWORD=(EditText)findViewById(R.id.password);
    login_button=(Button)findViewById(R.id.login_button);

    login_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             String ph = PHONE_NO.getText().toString();
            String p=PASSWORD.getText().toString();


            if (ph.equals("")||p.equals("")) {

                builder = new AlertDialog.Builder(login.this);
                builder.setTitle("Something went wrong...");
                builder.setMessage("Please fill all the fields...");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();


                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
            else
            {
  //see from here
                sharedPreferences = getSharedPreferences(MyPREFERENCE,Context.MODE_PRIVATE );
                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putString(PHONE, ph);
                editor.putString(PASS, p);
                editor.commit();

                BackgroundTask backgroundTask = new BackgroundTask(login.this);
                backgroundTask.execute("login",ph,p);

            }







}
});
    }
} 

this is my homeactivity where after logging user goes and i want that if i hadn't logout then whenever i open my app it should start from here

package in.co.medimap.www.medimap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HomeActivity extends Activity {

Button Logout = null;

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Logout = (Button) findViewById(R.id.Logout);
    textView = (TextView) findViewById(R.id.welcome_txt);
    String message = getIntent().getStringExtra("message");
    textView.setText(message);

    Logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.clear();
            editor.commit();
            Intent intent = new Intent(HomeActivity.this,MainActivity.class);
            startActivity(intent);



        }
    });




}
}

Solution

  • If you want logout to happen each time user leaves the application, why don't you just do it manually?

    you've already set Logout buttons setOnClickListener so just do this:

    @Override
    protected void onPause() {
        super.onPause();
        if(Logout != null) {
            Logout.callOnClick();
        }
    }
    

    This means every time user leaves this activity it will logout.
    make sure you handle cases where if they leave activity but go to a different activity on your page, it doesn't log out.

    =========== EDIT ===========

    I'm guessing your login activity is the main activity that starts when application opens so just put this in onCreate before you perform any other tasks. right after setContentView, you should do this.

    SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
    
    String phone = sharedPreferences.getString(PHONE, "");
    String pass = sharedPreferences.getString(PASS, "");
    
    if(!phone.isEmpty() && !pass.isEmpty()) {
        // this means ID and passwords are already saved so just start your home activity here
        startActivity(new Intent(context, MainActivity.class));
        finish();
    }
    

    In your MainActivity:

    Just read the values from SharedPreferences and login if you have to.

    Hope this helps.

    ========== EDIT 2

    Also, your Logout should look like this. Don't use commmit or clear. put empty values and use apply

    Logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences sharedPreferences = getSharedPreferences(login.MyPREFERENCE, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(PHONE, "");
            editor.putString(PASS, "");
            editor.apply();
            Intent intent = new Intent(HomeActivity.this,MainActivity.class);
            startActivity(intent);
        }
    });