I am developing an android app for the first time and I wanted to make the sessions for login and logout. I saw that most of the people suggested using SharedPreferences. But how can I check if the user logged out? If the user does not and clicks on my app, then the sign in page won't show up! The user can immediately go to the main page.

Here is my java class file where the user id and password would be asked...

package example.hiitattendance;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class LoginPage extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);



        final EditText et = (EditText) findViewById(R.id.editText1);
        final EditText et2 = (EditText) findViewById(R.id.editText2);
        Button b = (Button) findViewById(R.id.button1);
        final TextView tv = (TextView) findViewById(R.id.textView3);

        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            String username = String.valueOf(et.getText());
            String password = String.valueOf(et2.getText());



            if(username.equals("Junaid") && password.equals("hiit")){

                Intent intent = new Intent(LoginPage.this, JunaidHashmani.class);
                startActivity(intent);
            }
            else if(username.equals("Fahad")&& password.equals("director")){

                Intent intent = new Intent(LoginPage.this, FahadAzim.class);
                startActivity(intent);
            }
            else if(username.equals("Adnan")&& password.equals("hiit")){

                Intent intent = new Intent(LoginPage.this, AdnanSiddiqui.class);
                startActivity(intent);
            }
            else if(username.equals("Shams")&& password.equals("hiit")){

                Intent intent = new Intent(LoginPage.this, ShamsUlArfeen.class);
                startActivity(intent);
            }
            else if(username.equals("Abdul Haseeb")&& password.equals("labtrainer")){

                Intent intent = new Intent(LoginPage.this, AbdulHaseeb.class);
                startActivity(intent);
            }
            else {

                    tv.setText("Error Logging in");
            }   
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login_page, menu);
        return true;
    }

}

Now the code below will be the logged in page, where the user will be redirected after logging in.

package example.hiitattendance;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class FahadAzim extends ListActivity implements OnItemClickListener {

    public static final String PREFS_NAME = "LoginPrefs";
    ListView lv1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fahadazim);


        lv1 = (ListView) findViewById(android.R.id.list);
        lv1.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                getResources().getStringArray(R.array.fCourses)));


        lv1.setOnItemClickListener(this);



    }
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Intent intent;
        switch (arg2) {
            case 0:
                intent= new Intent(this,Bee_form.class);
                startActivity(intent);
                break;
            case 1:
                intent= new Intent(this,SNS_Form.class);
                startActivity(intent);
                break;
    }



}
}

Kindly help me out...
i am a learner...
Need a well described answer from u mates:)

Dani AI

Generated

Treat login as an app state, not just a screen. After a successful server authentication, persist only a session token (never the password), and decide which screen to show at app start based on whether a valid token exists. Also enforce the check on every protected Activity to guard against deep links or back navigation.

Example session helper and flow:

public final class SessionManager {
  private static final String PREF = "session";
  private static final String KEY_TOKEN = "auth_token";

  public static boolean isLoggedIn(Context c) {
    return c.getSharedPreferences(PREF, Context.MODE_PRIVATE)
            .contains(KEY_TOKEN);
  }

  public static void saveToken(Context c, String token) {
    c.getSharedPreferences(PREF, Context.MODE_PRIVATE)
      .edit().putString(KEY_TOKEN, token).apply();
  }

  public static void logout(Activity a) {
    a.getSharedPreferences(PREF, Context.MODE_PRIVATE).edit().clear().apply();
    Intent i = new Intent(a, LoginActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    a.startActivity(i);
  }
}
  • In your launcher (Splash) Activity onCreate: if SessionManager.isLoggedIn(this) start MainActivity, else start LoginActivity, then finish().
  • After a successful login: call SessionManager.saveToken(...), start MainActivity with FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK to prevent returning to login.
  • In each protected Activity onStart: if not logged in, call SessionManager.logout(this).

Notes:

  • Do not hardcode credentials; authenticate against your backend and use HTTPS.
  • Prefer encrypted storage for tokens (EncryptedSharedPreferences).
  • Consider migrating to Jetpack DataStore for preferences (DataStore).
  • Clear tokens on logout and handle server-side expiry.

Docs: SharedPreferences, Intent flags.

Recommended Answers

All 6 Replies

People may have suggested SharedPreferences because

A. You may want to keep login credentials for future logins, so whenever user encounters login form this will get populated by them and user then only need to press login button to trigger login process of validation and verification
B. You may want to store a token that identifies you as valid logged user, so for future communication with remote service you can safely communicate

PS: Would be also nice of you in future close some topics and give creadit where due example here

i have closed that topic.

what code is this.PK T~‹H^Æ2' ' mimetypeapplication/vnd.oasis.opendocument.textPK T~‹H
ÙK\ b meta.xml”ÍŽÂ €_ÅôÞbõ¢ÄêÍÓzÛ} ªdùi€ÚîÛ/ЭAW“¹ôÐù¾™É

what code is this, its a text on a smart phone.PK T~‹H^Æ2' ' mimetypeapplication/vnd.oasis.opendocument.textPK T~‹H
ÙK\ b meta.xml”ÍŽÂ €_ÅôÞbõ¢ÄêÍÓzÛ} ªdùi€ÚîÛ/ЭAW“¹ôÐù¾™É

average

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.