Slips
Code
Create a Application which shows Life Cycle of Activity.
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "LifecycleDemo";
// onCreate() is called when the activity is first created
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate() called");
}
// onStart() is called when the activity becomes visible to the user
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
// onResume() is called when the activity starts interacting with the user
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
// onPause() is called when the system is about to start resuming another activity
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
// onStop() is called when the activity is no longer visible to the user
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
// onRestart() is called when the activity is coming back to interact with the user
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart() called");
}
// onDestroy() is called before the activity is destroyed
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
Create an Android Application to accept two numbers to calculate it’s Power and Average. Create two buttons: Power and Average. Display the appropriate result on the next activity on Button click.
activity_main.xml:
-----------------------
<?xml version="1.0" encoding="utf-8"?>
<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="16dp">
<EditText
android:id="@+id/number1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter First Number"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/number2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Second Number"
android:inputType="numberDecimal" />
<Button
android:id="@+id/powerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Power"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/averageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate Average"
android:layout_marginTop="20dp" />
</LinearLayout>
MainActivity.java
----------------------
package com.example.calculator;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText number1EditText, number2EditText;
Button powerButton, averageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1EditText = findViewById(R.id.number1);
number2EditText = findViewById(R.id.number2);
powerButton = findViewById(R.id.powerButton);
averageButton = findViewById(R.id.averageButton);
powerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
calculatePower();
}
});
averageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
calculateAverage();
}
});
}
private void calculatePower() {
try {
double num1 = Double.parseDouble(number1EditText.getText().toString());
double num2 = Double.parseDouble(number2EditText.getText().toString());
double power = Math.pow(num1, num2);
// Pass result to ResultActivity
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
intent.putExtra("resultType", "Power");
intent.putExtra("result", power);
startActivity(intent);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Please enter valid numbers", Toast.LENGTH_SHORT).show();
}
}
private void calculateAverage() {
try {
double num1 = Double.parseDouble(number1EditText.getText().toString());
double num2 = Double.parseDouble(number2EditText.getText().toString());
double average = (num1 + num2) / 2;
// Pass result to ResultActivity
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
intent.putExtra("resultType", "Average");
intent.putExtra("result", average);
startActivity(intent);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Please enter valid numbers", Toast.LENGTH_SHORT).show();
}
}
}
activity_result.xml
-----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">
<TextView
android:id="@+id/resultTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
android:textSize="24sp"
android:layout_marginBottom="20dp"/>
<TextView
android:id="@+id/resultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result will be displayed here"
android:textSize="20sp" />
</LinearLayout>
ResultActivity.java
-----------------------
package com.example.calculator;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class ResultActivity extends AppCompatActivity {
TextView resultTitle, resultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
resultTitle = findViewById(R.id.resultTitle);
resultText = findViewById(R.id.resultText);
// Get the result and type from the Intent
String resultType = getIntent().getStringExtra("resultType");
double result = getIntent().getDoubleExtra("result", 0);
resultTitle.setText(resultType);
resultText.setText(String.valueOf(result));
}
}
Create application using JSON to provide Employee Information.
Create a folder named assets
inside the src/main
directory, and add the employee.json
file there.
assets/employee.json
[ { "name": "John Doe", "position": "Software Engineer", "salary": "70000" }, { "name": "Jane Smith", "position": "Product Manager", "salary": "80000" }, { "name": "Emily Johnson", "position": "Designer", "salary": "60000" }]
activity_main.xml-----------------<?xml version="1.0" encoding="utf-8"?><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="16dp">
<RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="16dp"/>
</LinearLayout>
item_employee.xml-----------------<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp" android:background="?android:attr/selectableItemBackground" android:layout_marginBottom="8dp">
<TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" />
<TextView android:id="@+id/position" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="16sp" android:textColor="#757575" />
<TextView android:id="@+id/salary" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="#4CAF50" android:layout_marginTop="8dp"/></LinearLayout>
Now we need to create the necessary Java classes to parse the JSON data and display it in the RecyclerView
.
Employee.java--------------package com.example.employeeinfo;
public class Employee { private String name; private String position; private String salary;
// Constructor public Employee(String name, String position, String salary) { this.name = name; this.position = position; this.salary = salary; }
// Getters public String getName() { return name; }
public String getPosition() { return position; }
public String getSalary() { return salary; }}
EmployeeAdapter.java--------------------
package com.example.employeeinfo;
import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView;import androidx.recyclerview.widget.RecyclerView;import java.util.List;
public class EmployeeAdapter extends RecyclerView.Adapter<EmployeeAdapter.EmployeeViewHolder> { private List<Employee> employeeList;
// Constructor public EmployeeAdapter(List<Employee> employeeList) { this.employeeList = employeeList; }
@Override public EmployeeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_employee, parent, false); return new EmployeeViewHolder(view); }
@Override public void onBindViewHolder(EmployeeViewHolder holder, int position) { Employee employee = employeeList.get(position); holder.nameTextView.setText(employee.getName()); holder.positionTextView.setText(employee.getPosition()); holder.salaryTextView.setText("Salary: $" + employee.getSalary()); }
@Override public int getItemCount() { return employeeList.size(); }
public static class EmployeeViewHolder extends RecyclerView.ViewHolder { TextView nameTextView, positionTextView, salaryTextView;
public EmployeeViewHolder(View itemView) { super(itemView); nameTextView = itemView.findViewById(R.id.name); positionTextView = itemView.findViewById(R.id.position); salaryTextView = itemView.findViewById(R.id.salary); } }}
MainActivity.java-----------------
package com.example.employeeinfo;
import android.content.res.AssetManager;import android.os.Bundle;import android.util.Log;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView;import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import java.io.BufferedReader;import java.io.InputStreamReader;import java.lang.reflect.Type;import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView; private EmployeeAdapter adapter; private List<Employee> employeeList;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this));
// Load employee data from JSON file loadEmployeeData(); }
private void loadEmployeeData() { try { // Load the JSON data from the assets folder AssetManager assetManager = getAssets(); BufferedReader reader = new BufferedReader(new InputStreamReader(assetManager.open("employee.json"))); StringBuilder stringBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } String jsonData = stringBuilder.toString();
// Parse the JSON data using Gson Gson gson = new Gson(); Type employeeListType = new TypeToken<List<Employee>>() {}.getType(); employeeList = gson.fromJson(jsonData, employeeListType);
// Set up RecyclerView with parsed data adapter = new EmployeeAdapter(employeeList); recyclerView.setAdapter(adapter);
} catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "Error loading employee data", Toast.LENGTH_SHORT).show(); } }}
Construct an Android application to accept a number and calculate Armstrong and Perfectnumber of a given number.activity_main.xml----------------------<?xml version="1.0" encoding="utf-8"?><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="16dp" android:gravity="center">
<EditText android:id="@+id/numberInput" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter a number" android:inputType="number" android:layout_marginBottom="20dp" />
<Button android:id="@+id/armstrongButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Check Armstrong Number" android:layout_marginBottom="10dp"/>
<Button android:id="@+id/perfectButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Check Perfect Number" android:layout_marginBottom="20dp"/>
<TextView android:id="@+id/resultText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" android:textSize="18sp" android:textColor="#FF0000"/></LinearLayout>
MainActivity.java----------------------package com.example.numbercheck;
import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText numberInput; Button armstrongButton, perfectButton; TextView resultText;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Initialize views numberInput = findViewById(R.id.numberInput); armstrongButton = findViewById(R.id.armstrongButton); perfectButton = findViewById(R.id.perfectButton); resultText = findViewById(R.id.resultText);
// Set listeners for buttons armstrongButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkArmstrongNumber(); } });
perfectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkPerfectNumber(); } }); }
// Method to check if the number is Armstrong private void checkArmstrongNumber() { String input = numberInput.getText().toString();
if (input.isEmpty()) { Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show(); return; }
int number = Integer.parseInt(input); int originalNumber = number; int sum = 0; int digits = String.valueOf(number).length();
while (number > 0) { int remainder = number % 10; sum += Math.pow(remainder, digits); // Raise each digit to the power of number of digits number /= 10; }
if (sum == originalNumber) { resultText.setText(originalNumber + " is an Armstrong Number."); } else { resultText.setText(originalNumber + " is not an Armstrong Number."); } }
// Method to check if the number is Perfect private void checkPerfectNumber() { String input = numberInput.getText().toString();
if (input.isEmpty()) { Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show(); return; }
int number = Integer.parseInt(input); int sum = 0;
// Find the divisors of the number for (int i = 1; i <= number / 2; i++) { if (number % i == 0) { sum += i; } }
if (sum == number) { resultText.setText(number + " is a Perfect Number."); } else { resultText.setText(number + " is not a Perfect Number."); } }}
Write a Java Android Program to Demonstrate List View Activity with all operationsSuch as: Insert, Delete, Search
activity_main.xml----------------------<?xml version="1.0" encoding="utf-8"?><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="16dp">
<!-- EditText to input item to be added --> <EditText android:id="@+id/editTextItem" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter item to add" android:inputType="text" />
<!-- Button to Insert item --> <Button android:id="@+id/btnInsert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Insert Item" android:layout_marginTop="10dp" />
<!-- EditText to search the ListView items --> <EditText android:id="@+id/editTextSearch" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Search items" android:layout_marginTop="20dp" />
<!-- ListView to show items --> <ListView android:id="@+id/listViewItems" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:layout_marginTop="20dp"/>
</LinearLayout>
MainActivity.java----------------------package com.example.listviewoperations;
import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.EditText;import android.widget.Button;import android.widget.ListView;import android.widget.Toast;import android.widget.TextView;import android.widget.Filter;import android.widget.Filterable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// Declare UI elements EditText editTextItem, editTextSearch; Button btnInsert; ListView listViewItems;
// Declare ArrayList to store the list items ArrayList<String> itemList; ArrayAdapter<String> adapter;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Initialize the UI elements editTextItem = findViewById(R.id.editTextItem); editTextSearch = findViewById(R.id.editTextSearch); btnInsert = findViewById(R.id.btnInsert); listViewItems = findViewById(R.id.listViewItems);
// Initialize the ArrayList and Adapter itemList = new ArrayList<>(); adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, itemList);
// Set the adapter for the ListView listViewItems.setAdapter(adapter);
// Insert item when Insert button is clicked btnInsert.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String item = editTextItem.getText().toString(); if (!item.isEmpty()) { itemList.add(item); // Add item to list adapter.notifyDataSetChanged(); // Refresh the ListView editTextItem.setText(""); // Clear the input field Toast.makeText(MainActivity.this, "Item Added", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Please enter an item", Toast.LENGTH_SHORT).show(); } } });
// Set an item click listener to delete an item when clicked listViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String item = itemList.get(position); itemList.remove(position); // Remove item from list adapter.notifyDataSetChanged(); // Refresh the ListView Toast.makeText(MainActivity.this, item + " Deleted", Toast.LENGTH_SHORT).show(); } });
// Implement search functionality editTextSearch.addTextChangedListener(new android.text.TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence charSequence, int start, int before, int count) { // Filter the list as the user types in the search box adapter.getFilter().filter(charSequence); }
@Override public void afterTextChanged(android.text.Editable editable) {} }); }}
Create an application to demonstrate login form with validation.LoginActivity.java------------------package com.example.loginvalidation;
import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {
EditText editTextUsername, editTextPassword; Button buttonLogin; TextView textViewError;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login);
// Initialize the views editTextUsername = findViewById(R.id.editTextUsername); editTextPassword = findViewById(R.id.editTextPassword); buttonLogin = findViewById(R.id.buttonLogin); textViewError = findViewById(R.id.textViewError);
// Set the login button's onClickListener buttonLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Validate login validateLogin(); } }); }
private void validateLogin() { String username = editTextUsername.getText().toString().trim(); String password = editTextPassword.getText().toString().trim();
// Simple validation: Check if fields are empty if (username.isEmpty() || password.isEmpty()) { textViewError.setText("Please enter both username and password."); } // Hardcoded correct credentials (just for simplicity) else if (username.equals("user") && password.equals("12345")) { // If login is successful, show a Toast message (or you can navigate to a new activity) Toast.makeText(LoginActivity.this, "Login Successful! Welcome " + username, Toast.LENGTH_SHORT).show(); } else { // Invalid credentials textViewError.setText("Invalid username or password."); } }}
activity_login.xml------------------<?xml version="1.0" encoding="utf-8"?><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="32dp" android:gravity="center">
<!-- EditText for Username --> <EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Username" android:inputType="text"/>
<!-- EditText for Password --> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" android:layout_marginTop="16dp"/>
<!-- Button for Login --> <Button android:id="@+id/buttonLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Login" android:layout_marginTop="32dp"/>
<!-- TextView to display error messages --> <TextView android:id="@+id/textViewError" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FF0000" android:layout_marginTop="16dp"/>
</LinearLayout>
AndroidManifest.xml-------------------<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.loginvalidation">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Login Validation" android:theme="@style/Theme.AppCompat.Light">
<activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
</application>
</manifest>
Write a Java Android Program to Demonstrate List View Activity with all operationsSuch as: Insert, Delete, Searchactivity_main.xml----------------------
<?xml version="1.0" encoding="utf-8"?><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="16dp">
<!-- EditText for user input --> <EditText android:id="@+id/editTextMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter greet message" />
<!-- Button to send message to the second activity --> <Button android:id="@+id/buttonSendMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send Message" />
</LinearLayout>
MainActivity.java-----------------package com.example.greetmessageapp;
import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText editTextMessage; private Button buttonSendMessage;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
editTextMessage = findViewById(R.id.editTextMessage); buttonSendMessage = findViewById(R.id.buttonSendMessage);
// Set OnClickListener to the button buttonSendMessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Get the message entered by the user String greetMessage = editTextMessage.getText().toString();
// Create an intent to start the second activity Intent intent = new Intent(MainActivity.this, SecondActivity.class);
// Pass the greet message to the second activity intent.putExtra("GREET_MESSAGE", greetMessage);
// Start the second activity startActivity(intent); } }); }}
activity_second.xml-------------------<?xml version="1.0" encoding="utf-8"?><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="16dp">
<!-- TextView to display the greet message --> <TextView android:id="@+id/textViewGreetMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Greet message will be displayed here" android:textSize="18sp" />
</LinearLayout>
SecondActivity.java--------------------package com.example.greetmessageapp;
import android.content.Intent;import android.os.Bundle;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;
public class SecondActivity extends AppCompatActivity {
private TextView textViewGreetMessage;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second);
textViewGreetMessage = findViewById(R.id.textViewGreetMessage);
// Get the greet message from the Intent Intent intent = getIntent(); String greetMessage = intent.getStringExtra("GREET_MESSAGE");
// Display the greet message textViewGreetMessage.setText(greetMessage); }}
AndroidManifest.xml-------------------<application ... > <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
<activity android:name=".SecondActivity" /></application>
Create an application to change Font Size, Color and Font Family of String.activity_main.xml------------------<?xml version="1.0" encoding="utf-8"?><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">
<!-- TextView to display the string --> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change My Style" android:textSize="18sp" android:layout_gravity="center" android:padding="20dp" android:textColor="#000000"/>
<!-- Button to change font size --> <Button android:id="@+id/btnChangeSize" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Font Size" android:layout_gravity="center" android:layout_marginTop="20dp"/>
<!-- Button to change text color --> <Button android:id="@+id/btnChangeColor" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Text Color" android:layout_gravity="center" android:layout_marginTop="20dp"/>
<!-- Button to change font family --> <Button android:id="@+id/btnChangeFamily" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Font Family" android:layout_gravity="center" android:layout_marginTop="20dp"/>
</LinearLayout>
MainActivity.java------------------package com.example.fontchanger;
import android.graphics.Color;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView textView; private Button btnChangeSize, btnChangeColor, btnChangeFamily;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Initialize the views textView = findViewById(R.id.textView); btnChangeSize = findViewById(R.id.btnChangeSize); btnChangeColor = findViewById(R.id.btnChangeColor); btnChangeFamily = findViewById(R.id.btnChangeFamily);
// Change Font Size on Button Click btnChangeSize.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setTextSize(30); // Change text size to 30sp } });
// Change Text Color on Button Click btnChangeColor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setTextColor(Color.RED); // Change text color to red } });
// Change Font Family on Button Click btnChangeFamily.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { textView.setTypeface(getResources().getFont(R.font.roboto_regular)); // Change to Roboto font family } }); }}
AndroidManifest.xml-------------------<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.fontchanger">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Font Changer" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.FontChanger">
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
</application>
</manifest>
Create an application for registration form given below. Also perform appropriate validation.activity_main.xml-----------------<?xml version="1.0" encoding="utf-8"?><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="16dp" android:gravity="center">
<!-- Name Field --> <EditText android:id="@+id/edtName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Name" android:inputType="textPersonName"/>
<!-- Email Field --> <EditText android:id="@+id/edtEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Email" android:inputType="textEmailAddress" android:layout_marginTop="10dp"/>
<!-- Password Field --> <EditText android:id="@+id/edtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Password" android:inputType="textPassword" android:layout_marginTop="10dp"/>
<!-- Age Field --> <EditText android:id="@+id/edtAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Age" android:inputType="number" android:layout_marginTop="10dp"/>
<!-- Mobile Number Field --> <EditText android:id="@+id/edtMobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Mobile Number" android:inputType="phone" android:layout_marginTop="10dp"/>
<!-- Register Button --> <Button android:id="@+id/btnRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register" android:layout_marginTop="20dp"/> </LinearLayout>
MainActivity.java-----------------package com.example.registrationform;
import android.os.Bundle;import android.text.TextUtils;import android.util.Patterns;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText edtName, edtEmail, edtPassword, edtAge, edtMobile; private Button btnRegister;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Initialize views edtName = findViewById(R.id.edtName); edtEmail = findViewById(R.id.edtEmail); edtPassword = findViewById(R.id.edtPassword); edtAge = findViewById(R.id.edtAge); edtMobile = findViewById(R.id.edtMobile); btnRegister = findViewById(R.id.btnRegister);
// Register button click listener btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Validate form fields if (validateForm()) { // If valid, show a success message Toast.makeText(MainActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show(); } } }); }
private boolean validateForm() { // Get user input values String name = edtName.getText().toString().trim(); String email = edtEmail.getText().toString().trim(); String password = edtPassword.getText().toString().trim(); String ageString = edtAge.getText().toString().trim(); String mobile = edtMobile.getText().toString().trim();
// Validate Name if (TextUtils.isEmpty(name)) { edtName.setError("Name is required"); edtName.requestFocus(); return false; }
// Validate Email if (TextUtils.isEmpty(email) || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) { edtEmail.setError("Enter a valid email address"); edtEmail.requestFocus(); return false; }
// Validate Password if (TextUtils.isEmpty(password) || password.length() < 6) { edtPassword.setError("Password must be at least 6 characters"); edtPassword.requestFocus(); return false; }
// Validate Age (Should be a valid number) if (TextUtils.isEmpty(ageString)) { edtAge.setError("Age is required"); edtAge.requestFocus(); return false; } else { try { int age = Integer.parseInt(ageString); if (age < 18) { edtAge.setError("You must be at least 18 years old"); edtAge.requestFocus(); return false; } } catch (NumberFormatException e) { edtAge.setError("Invalid age format"); edtAge.requestFocus(); return false; } }
// Validate Mobile Number if (TextUtils.isEmpty(mobile) || mobile.length() != 10) { edtMobile.setError("Enter a valid 10-digit mobile number"); edtMobile.requestFocus(); return false; }
return true; // If all validations pass }}
AndroidManifest.xml-------------------<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.registrationform">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Registration Form" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.RegistrationForm">
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
</application></manifest>
Create an application that Demonstrates List View and Onclick of List Display with ToastMessage.
activity_main.xml-----------------<?xml version="1.0" encoding="utf-8"?><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="16dp">
<!-- Registration Form Section --> <EditText android:id="@+id/edtName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Name" android:inputType="textPersonName" />
<EditText android:id="@+id/edtEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Email" android:inputType="textEmailAddress" android:layout_marginTop="10dp" />
<EditText android:id="@+id/edtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Password" android:inputType="textPassword" android:layout_marginTop="10dp" />
<EditText android:id="@+id/edtAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Age" android:inputType="number" android:layout_marginTop="10dp" />
<EditText android:id="@+id/edtMobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Mobile Number" android:inputType="phone" android:layout_marginTop="10dp" />
<Button android:id="@+id/btnRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register" android:layout_marginTop="20dp" />
<!-- ListView Section --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Click on List Item Below" android:textSize="18sp" android:layout_marginTop="30dp" />
<ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" />
</LinearLayout>
MainActivity.java-----------------package com.example.registrationlistview;
import android.os.Bundle;import android.text.TextUtils;import android.util.Patterns;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText edtName, edtEmail, edtPassword, edtAge, edtMobile; private Button btnRegister; private ListView listView;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
// Initialize views edtName = findViewById(R.id.edtName); edtEmail = findViewById(R.id.edtEmail); edtPassword = findViewById(R.id.edtPassword); edtAge = findViewById(R.id.edtAge); edtMobile = findViewById(R.id.edtMobile); btnRegister = findViewById(R.id.btnRegister); listView = findViewById(R.id.listView);
// Set up ListView with some items String[] items = {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}; ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items); listView.setAdapter(adapter);
// Set up ListView item click listener listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Show a Toast with the item clicked String item = (String) parent.getItemAtPosition(position); Toast.makeText(MainActivity.this, "You clicked: " + item, Toast.LENGTH_SHORT).show(); } });
// Register button click listener btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Validate the form and show success or error messages if (validateForm()) { Toast.makeText(MainActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show(); } } }); }
private boolean validateForm() { // Get user input values String name = edtName.getText().toString().trim(); String email = edtEmail.getText().toString().trim(); String password = edtPassword.getText().toString().trim(); String ageString = edtAge.getText().toString().trim(); String mobile = edtMobile.getText().toString().trim();
// Validate Name if (TextUtils.isEmpty(name)) { edtName.setError("Name is required"); edtName.requestFocus(); return false; }
// Validate Email if (TextUtils.isEmpty(email) || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) { edtEmail.setError("Enter a valid email address"); edtEmail.requestFocus(); return false; }
// Validate Password if (TextUtils.isEmpty(password) || password.length() < 6) { edtPassword.setError("Password must be at least 6 characters"); edtPassword.requestFocus(); return false; }
// Validate Age (Should be a valid number) if (TextUtils.isEmpty(ageString)) { edtAge.setError("Age is required"); edtAge.requestFocus(); return false; } else { try { int age = Integer.parseInt(ageString); if (age < 18) { edtAge.setError("You must be at least 18 years old"); edtAge.requestFocus(); return false; } } catch (NumberFormatException e) { edtAge.setError("Invalid age format"); edtAge.requestFocus(); return false; } }
// Validate Mobile Number if (TextUtils.isEmpty(mobile) || mobile.length() != 10) { edtMobile.setError("Enter a valid 10-digit mobile number"); edtMobile.requestFocus(); return false; }
return true; // If all validations pass }}
AndroidManifest.xml-------------------<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.registrationlistview">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="Registration and ListView" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.RegistrationListView">
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
</application></manifest>
Design an application for login activity. Write android code to check login credentials with
username = "mca" and password = "android". Display appropriate toast message to the user.
activity_login.xml
LoginActivity.java
------------------
Comments
Post a Comment