Elkin Jose 0 Newbie Poster

Hello , i am new in adroid programing , and i need some help and info D:
I create an activity with a log in "user" and "pass" and takes the user to the welcome activity, the log in works perfect but when i close the app , and re enter again i need to put again "user" and "pass" .

So what i want to do is when someone log in , it stay logged , even if the app is closed , so when the user opens again the app , will take him directly to the welcome activity
As i say i am a rooki , and i will really appreciate any help , plz help me with any example or info u can give me , thanks in advance :D
Thanks again and sorry for my bad english :p

Here is the code of my log in activity

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

public class LogInActivity extends Activity {

    EditText et1, et2;
    Button btn1;



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

        TextView tv1 = (TextView) findViewById(R.id.log_in_title);
        et1 = (EditText) findViewById(R.id.log_in_et1);
        et2 = (EditText) findViewById(R.id.log_in_et2);
        Button btn1 = (Button) findViewById(R.id.log_in_btn1);

        String font_path = "font/test_font.otf";
        Typeface TF = Typeface.createFromAsset(getAssets(), font_path);

        tv1.setTypeface(TF);
        et1.setTypeface(TF);
        et2.setTypeface(TF);
        btn1.setTypeface(TF);


            }



            public void LogIn(View v) {

                AsyncHttpClient client = new AsyncHttpClient();
                String url = "http://www.test.com/myapp/app/login.php";
                RequestParams requestParams = new RequestParams();

                requestParams.add("user", et1.getText().toString());
                requestParams.add("pass", et2.getText().toString());


                RequestHandle post = client.post(url, requestParams, new AsyncHttpResponseHandler() {
                    String usuario = null;

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        if (statusCode == 200) {

                            try {
                                JSONObject o = new JSONObject(new String(responseBody));
                                usuario = o.getString("user");
                                if (!TextUtils.isEmpty(usuario)) {
                                    Aplicacion app = (Aplicacion) getApplicationContext();
                                    app.setUsuario(usuario);

                                    startActivity(new Intent(LogInActivity.this, WelcomeActivity.class));
                                } else {
                                    Toast.makeText(LogInActivity.this, "Usuario y/o contraseña incorrectos", Toast.LENGTH_LONG).show();
                                }

                            } catch (JSONException e) {
                                Toast.makeText(LogInActivity.this, "Error", Toast.LENGTH_LONG).show();
                            }

                        }


                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Toast.makeText(LogInActivity.this, "Fallo enviando los datos", Toast.LENGTH_LONG).show();
                    }
                });


            }

        }

Dani AI

Generated

— quick diagnosis: the username in your app is only being kept in the Application object, which lives only while the process runs. When Android kills the process (app closed or backgrounded for a while) that object is lost, so the app “forgets” the login. Persist the login state to disk and check it at startup.

A simple, safe flow:

  • Have the server return an auth token (preferred) or a session id after successful login.
  • Save that token (not the raw password) in persistent storage.
  • On app launch check the stored token and, if present, go straight to WelcomeActivity.
  • On logout clear the stored token.

Example: saving the token after successful login

SharedPreferences prefs = getSharedPreferences("myapp_prefs", MODE_PRIVATE);
prefs.edit()
     .putString("auth_token", token)    // server token — do NOT store the plain password
     .putString("username", username)
     .putBoolean("logged_in", true)
     .apply();

startActivity(new Intent(this, WelcomeActivity.class));
finish();

Example: check at startup (place in your launcher activity or LogInActivity.onCreate)

SharedPreferences prefs = getSharedPreferences("myapp_prefs", MODE_PRIVATE);
boolean logged = prefs.getBoolean("logged_in", false);
String token = prefs.getString("auth_token", null);

if (logged && token != null) {
    // optional: validate token with server before proceeding
    startActivity(new Intent(this, WelcomeActivity.class));
    finish();
}

Example: logout (clear stored state)

SharedPreferences prefs = getSharedPreferences("myapp_prefs", MODE_PRIVATE);
prefs.edit().clear().apply();
startActivity(new Intent(this, LogInActivity.class));
finish();

Security notes and best practices: always use HTTPS; prefer a short-lived server token and validate it server-side; do not store raw passwords. For sensitive tokens use AndroidX Jetpack Security’s EncryptedSharedPreferences (or AccountManager / an auth provider like Firebase Auth) instead of plain SharedPreferences. Also handle token expiry and add a server-side “refresh” or re-login flow rather than silently trusting a never-expiring value.

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.