Android App Developement Practicals Programs
Android App Developement Practicals Programs
SAVITRIBAI PHULE PUNE UNIVERSITY
M.Sc. (Computer Science) Sem-II
Practical Examination 2023 - 2024
SUBJECT: CS-555-MJP Lab Course on CS-552-MJ
Mobile App Development Technologies
Slip 1
1. Write an java android application to create a splash screen.
1. Design the Splash Screen Layout:
- Create a new layout file under
res/layout
folder. - Name it descriptively, like
activity_splash.xml
. - Design the layout using XML. You can include elements like
ImageView
for a logo,TextView
for app name, or a background image.
2. Create the Splash Activity:
- In the
java
folder of your project, right-click and create a new Java class. - Name it
SplashActivity.java
. - This class will extend
AppCompatActivity
.
3. Implement the Splash Screen Logic:
- In
SplashActivity.java
, override theonCreate
method. - Set the activity to fullscreen using
getWindow().setFlags(...)
. - Inflate the layout you created in step 1 using
setContentView(R.layout.activity_splash)
.
4. Navigate to Main Activity:
- Use a
Handler
to post a delayed task that starts your main activity after a desired delay (e.g., 2 seconds). - In the delayed task, create an
Intent
to launch your main activity class and callstartActivity
.
5. Configure the Manifest File:
- Open
AndroidManifest.xml
. - Set the
android:theme
attribute for your splash activity to a theme that hides the action bar (@style/Theme.AppCompat.Light.NoActionBar
). - Declare the splash activity in the
<activity>
tag with an intent filter with category set toandroid.intent.category.LAUNCHER
. This makes it the default launch activity.
Here's an example code for SplashActivity.java
:
public class SplashActivity extends AppCompatActivity {
private static final int SPLASH_SCREEN_TIME_OUT = 2000; // 2 seconds
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(() -> {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
startActivity(intent);
finish();
}, SPLASH_SCREEN_TIME_OUT);
}
}
2. Create table Student (roll_no, name, address, percentage). Create Application for performing the following operation on the table. (Using SQLite database). i] Insert record of 5 new student details. ii] Show all the student detail
1. Create the Database Helper Class:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "student.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "Student";
public static final String COLUMN_ROLL_NO = "roll_no";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ADDRESS = "address";
public static final String COLUMN_PERCENTAGE = "percentage";
private static final String CREATE_TABLE_STUDENT = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ROLL_NO + " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_ADDRESS + " TEXT,"
+ COLUMN_PERCENTAGE + " REAL" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_STUDENT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle database schema upgrades if needed
}
}
2. Create Methods for CRUD Operations (Create, Read, Update, Delete):
public class DatabaseHelper extends SQLiteOpenHelper {
// ... existing code ...
public void insertStudent(int rollNo, String name, String address, double percentage) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.COLUMN_ROLL_NO, rollNo);
values.put(DatabaseHelper.COLUMN_NAME, name);
values.put(DatabaseHelper.COLUMN_ADDRESS, address);
values.put(DatabaseHelper.COLUMN_PERCENTAGE, percentage);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
db.close();
}
public List<Student> getAllStudents() {
List<Student> students = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + DatabaseHelper.TABLE_NAME, null);
if (cursor.moveToFirst()) {
do {
int rollNo = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ROLL_NO));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));
String address = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_ADDRESS));
double percentage = cursor.getDouble(cursor.getColumnIndex(DatabaseHelper.COLUMN_PERCENTAGE));
students.add(new Student(rollNo, name, address, percentage));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return students;
}
// ... other CRUD methods as needed ...
}
public class Student {
private int rollNo;
private String name;
private String address;
private double percentage;
// ... constructors and getters/setters ...
}
3. Implement the Functionality in an Activity:
public class MainActivity extends AppCompatActivity {
private DatabaseHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DatabaseHelper(this);
// Insert sample data (replace with button or user input)
insertSampleData();
// Show all students (replace with button or UI element)
showStudentDetails();
}
private void insertSampleData() {
dbHelper.insertStudent(1, "John Doe", "Address 1", 85.5);
dbHelper.insertStudent(2, "Jane Smith", "Address 2", 92.0);
// ... add more student data ...
}
private void showStudentDetails() {
List<Student> students = dbHelper.getAllStudents();
for (Student student : students) {
// Display student information using TextViews or other UI elements
Log.d("Student Details", "Roll No: " + student.getRollNo() + ", Name: " + student.getName());
}
}
}
---------------------------------------------------------------------------------------
Slip 2
1. Create an application that allows the user to enter a number in the textbox. Check whether the number in the textbox is perfect number or not. Print the message using Toast control
1. Create the Activity Layout (activity_main.xml):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/number_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number" />
<Button
android:id="@+id/check_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Check Perfect Number" />
</LinearLayout>
2. Create the Activity Class (MainActivity.java):
public class MainActivity extends AppCompatActivity {
private EditText numberInput;
private Button checkButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberInput = findViewById(R.id.number_input);
checkButton = findViewById(R.id.check_button);
checkButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String inputString = numberInput.getText().toString().trim();
if (inputString.isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter a number", Toast.LENGTH_SHORT).show();
return;
}
int number;
try {
number = Integer.parseInt(inputString);
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Invalid number format", Toast.LENGTH_SHORT).show();
return;
}
if (isPerfectNumber(number)) {
Toast.makeText(MainActivity.this, number + " is a perfect number", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, number + " is not a perfect number", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isPerfectNumber(int number) {
if (number <= 1) {
return false;
}
int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
}
}
return sum == number;
}
}
Explanation:
- The layout file defines an
EditText
for user input and aButton
to trigger the check. - The activity class handles user interaction and logic.
- It retrieves the input from the
EditText
and validates it. - The
isPerfectNumber
method checks if the number is a perfect number by calculating the sum of its divisors (excluding itself). - Toast messages are displayed based on the result.
2.) Java Android Program to perform all arithmetic Operations using Calculator
1. Layout File (activity_main.xml):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/result_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="0"
android:textAlignment="textEnd" />
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="4">
<Button
android:id="@+id/button_7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7" />
<Button
android:id="@+id/button_8"
android:layout_width="wrap_content"
android.layout_height="wrap_content"
android:text="8" />
<Button
android:id="@+id/button_9"
android:layout_width="wrap_content"
android.layout_height="wrap_content"
android:text="9" />
<Button
android:id="@+id/button_divide"
android:layout_width="wrap_content"
android.layout_height="wrap_content"
android:text="/" />
</GridLayout>
</LinearLayout>
2. Activity Class (MainActivity.java):
public class MainActivity extends AppCompatActivity {
private TextView resultText;
private double firstNumber = Double.NaN; // To check if a number is entered
private char operator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = findViewById(R.id.result_text);
// Set click listeners for number buttons
findViewById(R.id.button_7).setOnClickListener(numberClickListener);
// ... add click listeners for other number buttons ...
// Set click listeners for operator buttons
findViewById(R.id.button_divide).setOnClickListener(operatorClickListener);
// ... add click listeners for other operator buttons ...
// Button to clear the display
findViewById(R.id.button_clear).setOnClickListener(v -> {
clearCalculator();
});
// Button to calculate the result
findViewById(R.id.button_equal).setOnClickListener(v -> {
calculateResult();
});
}
private View.OnClickListener numberClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
String number = ((Button) v).getText().toString();
appendNumberToResult(number);
}
};
private View.OnClickListener operatorClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
char op = ((Button) v).getText().toString().charAt(0);
setOperator(op);
}
};
private void appendNumberToResult(String number) {
String currentResult = resultText.getText().toString();
if (currentResult.equals("0") || firstNumber == Double.NaN) {
resultText.setText(number);
} else {
resultText.setText(currentResult + number);
}
firstNumber = Double.parseDouble(currentResult);
}
private void setOperator(char op) {
if (!Double.isNaN(firstNumber)) {
operator = op;
resultText.setText("0"); // Clear display for next number
}
}
private void calculateResult() {
if (!Double.isNaN(firstNumber)) {
double secondNumber = Double.parseDouble(resultText.getText().toString());
------------------------------------------------------------------------------
Slip 3
1.Create an application that allows the user to enter a number in the textbox. Check whether the number in the textbox is Armstrong or not. Print the message accordingly in the label control
1. Create the Activity Layout (activity_main.xml):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/number_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number" />
<Button
android:id="@+id/check_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Check Armstrong Number" />
<TextView
android:id="@+id/result_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
Explanation:
- The layout file defines an
EditText
for user input, aButton
to trigger the check, and aTextView
to display the result. - The activity class handles user interaction and logic.
- It retrieves the input from the
EditText
and validates it. - The
isArmstrongNumber
method checks if the number is an Armstrong number by calculating the sum of each digit raised to the power of the number of digits. - The result label is updated based on whether the number is Armstrong or not.
2.Create an Android application which examine a phone number entered by a user with the given format. • Area code should be one of the following: 040, 041, 050, 0400, 044 • There should 6 - 8 numbers in telephone number (+ area code).
2. Implement Phone Number Validation Method:
public class MainActivity extends AppCompatActivity {
private static final String[] VALID_AREA_CODES = {"040", "041", "050", "0400", "044"};
private boolean isValidPhoneNumber(String phoneNumber) {
if (phoneNumber == null || phoneNumber.isEmpty()) {
return false;
}
// Remove non-numeric characters
phoneNumber = phoneNumber.replaceAll("[^0-9]", "");
// Check length (6 to 8 digits)
int length = phoneNumber.length();
if (length < 6 || length > 8) {
return false;
}
// Check area code
String areaCode = phoneNumber.substring(0, Math.min(phoneNumber.length(), 4));
return Arrays.asList(VALID_AREA_CODES).contains(areaCode);
}
}
3. Create the Activity Layout (activity_main.xml):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/phone_number_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter phone number"
android:inputType="phone" />
<Button
android:id="@+id/check_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Check Phone Number" />
<TextView
android:id="@+id/result_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
4. Create the Activity Class (MainActivity.java):
public class MainActivity extends AppCompatActivity {
private static final String[] VALID_AREA_CODES = {"040", "041", "050", "0400", "044"};
private EditText phoneNumberInput;
private Button checkButton;
private TextView resultLabel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneNumberInput = findViewById(R.id.phone_number_input);
checkButton = findViewById(R.id.check_button);
resultLabel = findViewById(R.id.result_label);
checkButton.setOnClickListener(v -> {
String phoneNumber = phoneNumberInput.getText().toString().trim();
if (isValidPhoneNumber(phoneNumber)) {
resultLabel.setText(phoneNumber + " is a valid phone number");
} else {
resultLabel.setText(phoneNumber + " is not a valid phone number");
}
});
}
private boolean isValidPhoneNumber(String phoneNumber) {
// ... (implementation from step 2) ...
}
}
Explanation:
- The
VALID_AREA_CODES
array stores the allowed area codes. - The
isValidPhoneNumber
method checks:- If the phone number is empty or null.
- Removes non-numeric characters.
- Checks if the length is between 6 and 8 digits.
- Extracts the area code and verifies it's in the valid list.
- The layout file defines an
EditText
for phone number input, aButton
to trigger validation, and aTextView
to display the result. - The activity class handles user interaction and calls the
isValidPhoneNumber
method to check the format. It displays a message based on the validation result.
Note: This is a basic implementation. You can enhance
----------------------------------------------------------------------------------------------
Slip 4
1.) Construct image switcher using setFactory()
1. Image Switcher Component:
The ImageSwitcher
component provides a way to transition between images with animations. You can define it in your layout file (XML):
<ImageSwitcher
android:id="@+id/imageSwitcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
2. Setting the Factory:
The setFactory()
method of ImageSwitcher
allows you to specify a ViewFactory
that creates the ImageView
objects used for displaying images. This gives you control over the creation and configuration of each view.
Here's how to implement it:
ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
imageSwitcher.setFactory(new ViewFactory() {
@Override
public View makeView() {
ImageView imageView = new ImageView(getApplicationContext());
// You can set properties for the ImageView here (e.g., scale type)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
return imageView;
}
});
This code retrieves the ImageSwitcher
reference and sets a ViewFactory
that creates a new ImageView
with CENTER_CROP
scale type each time an image needs to be displayed.
3. Adding Animations (Optional):
You can enhance the image transition by setting in and out animations for the ImageSwitcher
:
Animation inAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_in_left);
Animation outAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_out_right);
imageSwitcher.setInAnimation(inAnimation);
imageSwitcher.setOutAnimation(outAnimation);
This code loads pre-defined animations (slide_in_left and slide_out_right) and sets them for the ImageSwitcher
.
4. Setting Images:
There are multiple ways to set images in the ImageSwitcher
:
- Using
setImageResource
:
imageSwitcher.setImageResource(R.drawable.image1);
- Using
setImageURI
:
Uri imageUri = Uri.parse("path/to/your/image.jpg");
imageSwitcher.setImageURI(imageUri);
5. User Interaction (Optional):
You can add buttons or gestures to switch between images by calling imageSwitcher.setImageNext()
or imageSwitcher.setImagePrevious()
.
Remember:
- Replace
R.anim.slide_in_left
andR.anim.slide_out_right
with your actual animation resource IDs. - Ensure you have the necessary animation files defined in your
res/anim
directory.
Slip 5
1.Java Android Program to Demonstrate Alert Dialog Box
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get reference to the button
Button showAlertButton = findViewById(R.id.showAlertButton);
// Set click listener for the button
showAlertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create AlertDialog builder
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
// Set title and message for AlertDialog
alertDialogBuilder.setTitle("Alert Dialog");
alertDialogBuilder.setMessage("This is an example of an Alert Dialog");
// Set positive button and its click listener
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do something when OK button is clicked
dialog.dismiss();
}
});
// Create and show AlertDialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}
- We create an AlertDialog.Builder object
alertDialogBuilder
. - We set the title and message for the AlertDialog using
setTitle()
andsetMessage()
. - We set the positive button for the AlertDialog using
setPositiveButton()
. When the user clicks this button, the dialog is dismissed. - We create the AlertDialog object by calling
create()
on the builder. - We call
show()
on the AlertDialog object to display the dialog to the user.
Make sure to have a layout file (e.g., activity_main.xml
) with a button (e.g., showAlertButton
) that triggers the display of the AlertDialog.
2. Create an Android application which will ask the user to input his / her name. A message should display the two items concatenated in a label. Change the format of the label using radio buttons and check boxes for selection. The user can make the label text bold, underlined or italic as well as change its color. Also include buttons to display the message in the label, clear the text boxes as well as label. Finally exit.
1. Layout File (activity_main.xml):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/user_name_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />
<TextView
android:id="@+id/greeting_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Formatting options:" />
<RadioGroup
android:id="@+id/format_radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Normal"
android:checked="true" />
<RadioButton
android:id="@+id/radio_bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bold" />
<RadioButton
android:id="@+id/radio_italic"
android:layout_width="wrap_content"
android.layout.height="wrap_content"
android:text="Italic" />
<RadioButton
android:id="@+id/radio_underline"
android:layout_width="wrap_content"
android.layout.height="wrap_content"
android:text="Underline" />
</RadioGroup>
<CheckBox
android:id="@+id/checkbox_color"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Color" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/button_show"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Show Message" />
<Button
android:id="@+id/button_clear"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Clear" />
<Button
android:id="@+id/button_exit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Exit" />
</LinearLayout>
</LinearLayout>
2. Activity Class (MainActivity.java):
public class MainActivity extends AppCompatActivity {
private EditText userNameInput;
private TextView greetingLabel;
private RadioGroup formatRadioGroup;
private CheckBox colorCheckbox;
private Button showButton, clearButton, exitButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userNameInput = findViewById(R.id.user_name_input);
greetingLabel = findViewById(R.id.greeting_label);
formatRadioGroup = findViewById(R.id.format_radio_group);
colorCheckbox = findViewById(R.id.checkbox_color);
showButton = findViewById(R.id.button_show);
clearButton = findViewById(R.id.button_clear);
exitButton = findViewById(R.id.button_exit);
showButton.setOnClickListener(v -> showMessage());
clearButton.setOnClickListener(v -> clearInput());
exitButton.set
Slip 6
write Java Android Program to demonstrate login form with validation
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private EditText emailEditText, passwordEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailEditText = findViewById(R.id.emailEditText);
passwordEditText = findViewById(R.id.passwordEditText);
Button loginButton = findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validateAndLogin();
}
});
}
private void validateAndLogin() {
String email = emailEditText.getText().toString().trim();
String password = passwordEditText.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter your email", Toast.LENGTH_SHORT).show();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Toast.makeText(this, "Please enter a valid email", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter your password", Toast.LENGTH_SHORT).show();
return;
}
// Here you can implement your login logic, such as sending a request to a server
// with the entered email and password and handling the response accordingly.
// For demonstration purposes, let's just display a toast message indicating successful login.
Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show();
}
}
Slip 7
] Java Android Program to Demonstrate ProgressBar.
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class ProgressBarActivity extends AppCompatActivity {
private ProgressBar progressBar;
private Button startButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_bar);
progressBar = findViewById(R.id.progressBar);
startButton = findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startProgress();
}
});
}
private void startProgress() {
// Set progress to 0 initially
progressBar.setProgress(0);
// Create a handler to update progress periodically
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
int progress = progressBar.getProgress();
if (progress < progressBar.getMax()) {
// Increment progress by 10
progressBar.setProgress(progress + 10);
// Repeat after 1 second (1000 milliseconds)
handler.postDelayed(this, 1000);
} else {
// When progress reaches max, reset progress bar and display completion message
progressBar.setProgress(0);
// Optionally, display a completion message
// Toast.makeText(ProgressBarActivity.this, "Progress completed!", Toast.LENGTH_SHORT).show();
}
}
}, 1000); // Start progress after 1 second
}
}
Slip 8
Create a Application which shows Life Cycle of Activity
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Activity created");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: Activity started");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: Activity resumed");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: Activity paused");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: Activity stopped");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: Activity destroyed");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: Activity restarted");
}
}
- Define the
Customer
table:
sqlCREATE TABLE Customer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
address TEXT,
ph_no TEXT
);
- Implement the Android application:
Certainly! Here's an Android application that allows you to perform CRUD operations on a SQLite database table named Customer
.
- Define the
Customer
table:
sqlCREATE TABLE Customer (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
address TEXT,
ph_no TEXT
);
- Implement the Android application:
Create an Android application with the following components:
- Layout XML files for UI design.
- Java code to handle database operations.
Here's a basic implementation:
- Layout XML file for the main activity (activity_main.xml):
xml<!-- activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnInsert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Insert Customer" />
<Button
android:id="@+id/btnShowAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show All Customers" />
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="" />
</LinearLayout>
- Java code for main activity (MainActivity.java):
javaimport android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create or open the database
CustomerDbHelper dbHelper = new CustomerDbHelper(this);
mDatabase = dbHelper.getWritableDatabase();
Button btnInsert = findViewById(R.id.btnInsert);
Button btnShowAll = findViewById(R.id.btnShowAll);
final TextView tvResult = findViewById(R.id.tvResult);
btnInsert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insertCustomer("John Doe", "123 Main St", "1234567890");
insertCustomer("Jane Smith", "456 Elm St", "9876543210");
insertCustomer("Alice Johnson", "789 Oak St", "5551234567");
insertCustomer("Bob Brown", "111 Pine St", "4449876543");
insertCustomer("Eva Garcia", "222 Maple St", "2223334444");
Toast.makeText(MainActivity.this, "Customers inserted successfully", Toast.LENGTH_SHORT).show();
}
});
btnShowAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Cursor cursor = mDatabase.rawQuery("SELECT * FROM Customer", null);
StringBuilder result = new StringBuilder();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String address = cursor.getString(cursor.getColumnIndex("address"));
String phone = cursor.getString(cursor.getColumnIndex("ph_no"));
result.append("ID: ").append(id).append(", Name: ").append(name).append(", Address: ").append(address).append(", Phone: ").append(phone).append("\n");
}
tvResult.setText(result.toString());
cursor.close();
}
});
}
private void insertCustomer(String name, String address, String phone) {
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("address", address);
contentValues.put("ph_no", phone);
mDatabase.insert("Customer", null, contentValues);
}
}
- Database helper class (CustomerDbHelper.java):
javaimport android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class CustomerDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Customer.db";
private static final int DATABASE_VERSION = 1;
public CustomerDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_CUSTOMER_TABLE = "CREATE TABLE Customer (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"address TEXT," +
"ph_no TEXT);";
db.execSQL(SQL_CREATE_CUSTOMER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Customer");
onCreate(db);
}
}
Slip 9
Create an application that allows the user to enter a number in the textbox named „getnum‟. Check whether the number in the textbox „getnum‟ is Palindrome or not. Print the message accordingly in the label when the user clicks on the button „Check‟.
Sure! Below is an example of an Android application that allows the user to enter a number in a EditText
named "getnum", checks whether the entered number is a palindrome or not, and displays the result in a TextView
when the user clicks on a Button
named "Check":
- Layout XML file (activity_main.xml):
xml<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/getnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"
app:layout_constraintBottom_toTopOf="@id/checkButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/checkButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
app:layout_constraintBottom_toTopOf="@id/resultTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/checkButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
- Java code for the main activity (MainActivity.java):
javaimport android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText getnum;
Button checkButton;
TextView resultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getnum = findViewById(R.id.getnum);
checkButton = findViewById(R.id.checkButton);
resultTextView = findViewById(R.id.resultTextView);
checkButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkPalindrome();
}
});
// Add a TextWatcher to check if the input changes
getnum.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Clear the result text view when the input changes
resultTextView.setText("");
}
@Override
public void afterTextChanged(Editable s) {}
});
}
private void checkPalindrome() {
String input = getnum.getText().toString().trim();
if (!TextUtils.isEmpty(input)) {
int number = Integer.parseInt(input);
if (isPalindrome(number)) {
resultTextView.setText(number + " is a palindrome");
} else {
resultTextView.setText(number + " is not a palindrome");
}
} else {
resultTextView.setText("Please enter a number");
}
}
// Function to check if a number is palindrome or not
private boolean isPalindrome(int num) {
int originalNum = num;
int reversedNum = 0;
while (num != 0) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}
return originalNum == reversedNum;
}
}
Java android program to create simple calculator
- Layout XML file (activity_main.xml):
xml<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/resultTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:gravity="end"
android:text=""
android:textSize="24sp"
app:layout_constraintBottom_toTopOf="@id/guideline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.4" />
<GridLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="16dp"
android:alignmentMode="alignMargins"
android:columnCount="4"
android:rowCount="5"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/guideline">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:onClick="onNumberClick" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:onClick="onNumberClick" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:onClick="onNumberClick" />
<Button
android:id="@+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:onClick="onOperatorClick" />
<!-- More buttons for numbers and operators -->
<Button
android:id="@+id/buttonEquals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:onClick="onEqualsClick"
android:layout_columnSpan="2" />
<Button
android:id="@+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
android:onClick="onClearClick" />
</GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
- Java code for the main activity (MainActivity.java):
javaimport 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 resultTextView;
private String currentNumber = "";
private double firstOperand = Double.NaN;
private String pendingOperator = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultTextView = findViewById(R.id.resultTextView);
}
public void onNumberClick(View view) {
String digit = ((Button) view).getText().toString();
currentNumber += digit;
updateResultTextView();
}
public void onOperatorClick(View view) {
String operator = ((Button) view).getText().toString();
if (!currentNumber.isEmpty()) {
if (!Double.isNaN(firstOperand)) {
calculateResult();
} else {
firstOperand = Double.parseDouble(currentNumber);
}
pendingOperator = operator;
currentNumber = "";
updateResultTextView();
}
}
public void onEqualsClick(View view) {
if (!currentNumber.isEmpty() && !Double.isNaN(firstOperand)) {
calculateResult();
pendingOperator = "";
}
}
public void onClearClick(View view) {
currentNumber = "";
firstOperand = Double.NaN;
pendingOperator = "";
updateResultTextView();
}
private void calculateResult() {
double secondOperand = Double.parseDouble(currentNumber);
double result = Double.NaN;
switch (pendingOperator) {
case "+":
result = firstOperand + secondOperand;
break;
// Add more cases for other operators
}
currentNumber = Double.toString(result);
firstOperand = result;
updateResultTextView();
}
private void updateResultTextView() {
resultTextView.setText(currentNumber);
}
}
Slip 10
Create an application that allows the user to enter a number in the textbox named getnum. Check whether the number in the textbox getnum is Armstrong or not. Print the message using Toast control when the user clicks on the button Check
- Layout XML file (activity_main.xml):
xml<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/getnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"
app:layout_constraintBottom_toTopOf="@id/checkButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/checkButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check"
app:layout_constraintBottom_toTopOf="@id/guideline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="16dp"
android:onClick="onCheckClick" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.4" />
</androidx.constraintlayout.widget.ConstraintLayout>
- Java code for the main activity (MainActivity.java):
javaimport android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText getnum;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getnum = findViewById(R.id.getnum);
}
public void onCheckClick(View view) {
String numberStr = getnum.getText().toString().trim();
if (numberStr.isEmpty()) {
Toast.makeText(this, "Please enter a number", Toast.LENGTH_SHORT).show();
return;
}
int number = Integer.parseInt(numberStr);
if (isArmstrong(number)) {
Toast.makeText(this, number + " is an Armstrong number", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, number + " is not an Armstrong number", Toast.LENGTH_SHORT).show();
}
}
private boolean isArmstrong(int number) {
int originalNumber, remainder, result = 0, n = 0;
originalNumber = number;
// Count number of digits
while (originalNumber != 0) {
originalNumber /= 10;
++n;
}
originalNumber = number;
// Calculate result
while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, n);
originalNumber /= 10;
}
return result == number;
}
}
This application checks whether the entered number in the EditText
named "getnum" is an Armstrong number or not when the user clicks on the Button
named "Check". A Toast
message is displayed to show the result.
Write a program to draw GUI by using Spinner, Buttons.
- Layout XML file (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/spinner_options" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2" />
<!-- Add more buttons or other views as needed -->
</LinearLayout>
- Array resource file (res/values/arrays.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="spinner_options">
<item>Option 1</item>
<item>Option 2</item>
<item>Option 3</item>
<!-- Add more options as needed -->
</string-array>
</resources>
- Java code for the main activity (MainActivity.java):
Slip 11
- Design the User Interface (XML Layout):
Create
activity_main.xml
layout file:
- Implement the Logic (Java Code):
Create
MainActivity.java
file:
- Create the Result Activity:
Create
ResultActivity.java
file:
- Create Result Activity Layout:
Create
activity_result.xml
layout file:
- Design the User Interface (XML Layout):
Create
activity_main.xml
layout file:
- Implement the Logic (Java Code):
Create
MainActivity.java
file:
- Run the Application: After creating the layout and the Java code, run the application on an emulator or a real device to see how it works. You should be able to enter a string, select an operation using radio buttons, and see the result displayed below.
This application allows users to input a string and select one of three operations (reverse string, convert to uppercase, or convert to lowercase) using radio buttons. It then displays the result of the selected operation.
Slip 12
Construct an Android app that toggles a light bulb ON and OFF when the user clicks on toggle button.
- Design the User Interface (XML Layout):
Create
activity_main.xml
layout file:
- Implement the Logic (Java Code):
Create
MainActivity.java
file:
- Design the User Interface (XML Layout):
Create
activity_main.xml
layout file:
- Implement the Logic (Java Code):
Create
MainActivity.java
file:
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText editTextName;
RadioGroup radioGroupFormat;
RadioButton radioButtonBold, radioButtonItalic, radioButtonUnderline;
CheckBox checkBoxColor;
Button buttonDisplayMessage, buttonClear, buttonExit;
TextView textViewMessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = findViewById(R.id.editTextName);
radioGroupFormat = findViewById(R.id.radioGroupFormat);
radioButtonBold = findViewById(R.id.radioButtonBold);
radioButtonItalic = findViewById(R.id.radioButtonItalic);
radioButtonUnderline = findViewById(R.id.radioButtonUnderline);
checkBoxColor = findViewById(R.id.checkBoxColor);
buttonDisplayMessage = findViewById(R.id.buttonDisplayMessage);
buttonClear = findViewById(R.id.buttonClear);
buttonExit = findViewById(R.id.buttonExit);
textViewMessage = findViewById(R.id.textViewMessage);
buttonDisplayMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
displayMessage();
}
});
buttonClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearInputs();
}
});
buttonExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish(); // Close the app
}
});
}
private void displayMessage() {
String name = editTextName.getText().toString();
SpannableString formattedText = new SpannableString(name);
// Apply formatting based on radio button selection
if (radioButtonBold.isChecked()) {
formattedText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (radioButtonItalic.isChecked()) {
formattedText.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (radioButtonUnderline.isChecked()) {
formattedText.setSpan(new UnderlineSpan(), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
// Apply color if checkbox is checked
if (checkBoxColor.isChecked()) {
formattedText.setSpan(new ForegroundColorSpan(Color.RED), 0, name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
textViewMessage.setText(formattedText);
}
private void clearInputs() {
editTextName.getText().clear();
textViewMessage.setText("");
}
}
Slip 13
Java android program to demonstrate Registration form with validation
- Design the User Interface (XML Layout):
Create
activity_registration.xml
layout file:
- Implement the Logic (Java Code):
Create
RegistrationActivity.java
file:
- Create the Layout (XML):
Create
activity_main.xml
layout file:
- Create the Adapter:
We'll need a custom ArrayAdapter to bind data to the ListView. Create a new Java class named
CustomAdapter.java
:
- Create the Item Row Layout:
Create
item_row.xml
layout file under theres/layout
directory:
- Implement the Logic:
Now, in your
MainActivity.java
, you can implement the logic for adding, deleting, and searching items:
Slip 14
Construct an Android application to accept a number and calculate and display Factorial of a given number in TextView.
- Design the User Interface (XML Layout):
Create
activity_main.xml
layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter a number"
android:inputType="number"/>
<Button
android:id="@+id/buttonCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Calculate Factorial"/>
<TextView
android:id="@+id/textViewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonCalculate"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:textSize="18sp"/>
</RelativeLayout>
- Implement the Logic (Java Code):
Create
MainActivity.java
file:
- Design the User Interface (XML Layout):
Create
activity_main.xml
layout file:
- Implement the Logic (Java Code):
Create
MainActivity.java
file:
Slip 15
Slip 16
Slip 17
Slip 18
Slip 19
Slip 20
Slip 21
Slip 22
Slip 23
Slip 24
Slip 25
Slip 26
Slip 27
Slip 28
Slip 29
Slip 30
Comments
Post a Comment
hey