JavaAuthenticationPart3

JavaAuthenticationPart3

Mobile Applications

Using Android

LoginActivity.java

In the LoginActivity class for an Android application, the login method retrieves the entered username and password, checks them against hardcoded values, and if valid, starts the MainActivity and finishes the current LoginActivity. If the credentials are invalid, it shows a toast message. The logout method starts the LoginActivity and finishes the current activity, effectively logging the user out.

 

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

 

public class LoginActivity extends AppCompatActivity {

    private EditText usernameField;

    private EditText passwordField;

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_login);

        usernameField = findViewById(R.id.username);

        passwordField = findViewById(R.id.password);

    }

 

    public void login(View view) {

        String username = usernameField.getText().toString();

        String password = passwordField.getText().toString();

 

        if ("admin".equals(username) && "password".equals(password)) {

            Intent intent = new Intent(this, MainActivity.class);

            startActivity(intent);

            finish();

        }else {

           Toast.makeText(this, "Invalid credentials", Toast.LENGTH_SHORT).show();

        }

    }

 

    public void logout(View view) {

        Intent intent = new Intent(this, LoginActivity.class);

       startActivity(intent);

        finish();

    }

}

 

For more details find part 4 in the blog,next week.

Sumit Malhotra

Article by Sumit Malhotra

Published 17 Dec 2023