Practical No 28 Deepak
Practical No 28 Deepak
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:padding="20dp">
<EditText
android:id="@+id/editUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />
<EditText
android:id="@+id/editPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword" />
<Button
android:id="@+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>
MainActivity.java
package com.example.pr28;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText editUsername, editPassword;
Button btnLogin;
int loginAttempts = 3;
final String CORRECT_USERNAME = "Deepak";
final String CORRECT_PASSWORD = "0399";
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editUsername = findViewById(R.id.editUsername);
editPassword = findViewById(R.id.editPassword);
btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(v -> {
String username = editUsername.getText().toString().trim();
String password = editPassword.getText().toString().trim();
// Check credentials
if (username.equals(CORRECT_USERNAME) &&
password.equals(CORRECT_PASSWORD))
{
Toast.makeText(this, "Login Successful",
Toast.LENGTH_SHORT).show();
loginAttempts = 3; // reset attempts if needed
} else {
loginAttempts--;
if (loginAttempts > 0) {
Toast.makeText(this, "Login Unsuccessful. Attempts
left: " + loginAttempts,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Login Failed! No attempts left.",
Toast.LENGTH_LONG).show();
btnLogin.setEnabled(false); // disable button after 3
failures
}
}
});
}
}
Output: