Android Programming LAB1&2
Android Programming LAB1&2
------------------------------------------------------
1. XML Layout (activity_main.xml)
This defines the UI of your application.
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:id="@+id/helloTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="24sp"
android:textColor="#4CAF50" />
</LinearLayout>
import [Link];
import [Link];
import [Link];
3. [Link]
This file registers the main activity and sets the application entry point.
xml
Copy code
<manifest xmlns:android="[Link]
package="[Link]">
<application
android:allowBackup="true"
android:label="HelloWorld"
android:theme="@style/[Link]">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>
Explanation:
1. XML Layout:
o Defines a LinearLayout with a TextView to display "Hello, World!".
2. Main Activity:
o The MainActivity class sets the content view to the activity_main layout and modifies
the TextView text.
3. Manifest:
o Registers MainActivity and specifies it as the launcher activity.
Compile and Run:
1. Open Android Studio.
2. Create a new project and paste the above code in their respective files.
3. Run the app on an emulator or physical device.
This basic app is a starting point for Android development.
why AppCompatActivity ?
AppCompatActivity is a base class in Android development that provides compatibility support for
modern Android features on older versions of the Android platform. It is part of the AndroidX library and
is a key component of the Jetpack suite.
Here’s why AppCompatActivity is commonly used:
3. Modern UI Components
• Grants access to Material Design components and themes (e.g., MaterialButton,
MaterialCardView).
• Ensures these components are styled and behave consistently, even on pre-Lollipop devices.
Alternative: Activity
• If you only need basic features and don’t care about backward compatibility or modern UI
components, you can use Activity.
• Activity is a lighter class but lacks the enhancements provided by AppCompatActivity.
In most cases, using AppCompatActivity is a best practice as it future-proofs your app and provides a
consistent user experience across devices.
why Bundle ?
In Android, a Bundle is a data structure used to pass data between various components of the app (like
activities, fragments, or services). It acts as a container for key-value pairs and supports a variety of data
types, including primitive types, objects, and arrays.
Here’s a detailed explanation of why Bundle is commonly used:
1. Storing State
• Bundle is used in the onSaveInstanceState() and onRestoreInstanceState() methods to save and
restore an activity’s or fragment's state during lifecycle changes (e.g., screen rotation).
• Example:
java
Copy code
@Override
protected void onSaveInstanceState(Bundle outState) {
[Link](outState);
[Link]("key", "value");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
[Link](savedInstanceState);
String value = [Link]("key");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
if (savedInstanceState != null) {
String message = [Link]("message");
Log.d("TAG", message); // Outputs: Hello, World!
}
}
Benefits Summary:
• Error Prevention: Ensures correct method overriding.
• Improved Code Clarity: Clearly shows intent to override.
• Avoids Bugs: Prevents accidental overloading or incorrect implementation.
• Compiler Assistance: Highlights errors during compilation.
In Android development, @Override is especially critical for lifecycle methods (onCreate(), onStart(),
etc.) and callback interfaces. It is a cornerstone of writing robust and maintainable code.
2. Initialize Components
• You typically initialize UI elements (like TextView, Button, etc.) and other components (like
adapters, listeners, and data) in onCreate().
Example:
java
Copy code
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
initializeDatabase();
setupNetworkClient();
}
Summary:
You override onCreate() to:
1. Set up the UI for the activity using setContentView().
2. Initialize components like views, listeners, and resources.
3. Restore saved state after configuration changes.
4. Execute custom initialization logic needed when the activity starts.
Without overriding onCreate(), your activity would be empty and uninitialized, rendering it unusable.
1. Controlled Access
• A protected method can be accessed by:
o The same class.
o Subclasses.
o Classes in the same package.
• This ensures that the method is accessible to activity subclasses (like MainActivity) while
restricting access from unrelated external classes.
• Prevents unintended or unauthorized calls from outside the class hierarchy.
4. Prevent Misuse
• If onCreate() were public, any external class could call it, potentially disrupting the activity
lifecycle and causing unintended behavior.
• Example of misuse if it were public:
java
Copy code
MainActivity activity = new MainActivity();
[Link](null); // This would disrupt the normal lifecycle
• By making it protected, such calls are discouraged and controlled.
5. Encapsulation
• Encapsulation is a core principle of object-oriented programming. Marking onCreate() as
protected encapsulates the lifecycle details of the activity, allowing only legitimate access by the
framework and subclasses.
Conclusion
The protected modifier strikes the right balance between:
• Allowing subclasses to override and extend the method.
• Restricting access to only those components (like the Android framework) that legitimately
manage the lifecycle.
By making onCreate() protected, Android ensures that the activity's lifecycle is both extensible and
secure.
can we use another naming for MainActivity ?
Yes, you can use any valid class name instead of MainActivity for your primary or other activities in an
Android project. The class name is not restricted to MainActivity; it's just a convention often used for the
main entry point of an app.
Things to Remember
1. Naming Conventions:
o Use meaningful names that describe the activity's purpose.
o Follow Java naming conventions (PascalCase).
2. Manifest Declaration:
o Every activity must be declared in the [Link] file.
3. References in Code:
o Update all references to MainActivity in your project (e.g., intents, navigation) to use the
new activity name.
Example:
java
Copy code
Intent intent = new Intent(this, [Link]);
startActivity(intent);
import [Link];
import [Link];
import [Link]
import [Link]
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to AbduActivity!" />
</LinearLayout>
Things to Remember
1. Follow Naming Conventions:
o Use PascalCase (AbduActivity), where the first letter of each word is capitalized.
2. Manifest Declaration:
o All activities must be declared in the [Link] file.
3. Unique Layout File:
o Use a unique and relevant layout file name, like activity_abdu.xml.
Conclusion
Yes, you can name your activity AbduActivity. It will work as long as it's properly defined and declared in
the manifest file, with corresponding logic and layout setup. It’s a good practice to choose a name that
reflects the activity's purpose, so if "Abdu" is meaningful to your app, it’s perfectly fine!
1. Minimal Functionality
• If you don't extend AppCompatActivity but extend Activity instead, your app will run, but you
won't have access to modern Android features like:
o Support for the ActionBar or Toolbar.
o Theme and UI compatibility for older Android versions (backward compatibility).
o Features from the AndroidX library, such as fragments, app navigation, and lifecycle-
aware components.
3. No Backward Compatibility
• AppCompatActivity ensures backward compatibility for features introduced in newer Android
versions, such as:
o Material Design components.
o Support for vector drawables on older devices.
o Day/Night themes.
• If you extend Activity directly, you need to handle backward compatibility manually, which is
challenging and time-consuming.
4. Lifecycle Differences
• Both Activity and AppCompatActivity have the same basic lifecycle (onCreate, onStart, etc.), but
AppCompatActivity enhances it with features like FragmentActivity support and modern
lifecycle-awareness.
Without AppCompatActivity, you cannot use lifecycle-aware components from AndroidX, such as
ViewModel or LiveData.
Conclusion
If you don't extend AppCompatActivity:
1. Your activity lacks modern UI features and backward compatibility.
2. You lose access to advanced features like Toolbar, Fragments, and lifecycle-aware components.
3. Your app might not look consistent across different Android versions.
For most modern apps, extending AppCompatActivity is highly recommended because it simplifies
development and ensures compatibility across a wide range of devices and Android versions.
android syntax
here is a basic syntax and structure overview for Android programming using Java:
1. Activity
An activity represents a single screen in an app.
java
Copy code
package [Link];
import [Link];
import [Link];
2. Layout (XML)
The layout defines the UI of an activity.
Example: res/layout/activity_main.xml
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
3. Event Handling
Handle user interactions like button clicks.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
4. Intents
Used for navigating between activities or passing data.
Start a New Activity:
java
Copy code
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
Pass Data Between Activities:
java
Copy code
Intent intent = new Intent([Link], [Link]);
[Link]("KEY", "Value");
startActivity(intent);
Retrieve Data:
java
Copy code
String value = getIntent().getStringExtra("KEY");
5. Permissions
Request permissions in the manifest.
Example: [Link]
xml
Copy code
<uses-permission android:name="[Link]" />
Runtime Permission (for Android 6.0 and above):
java
Copy code
if ([Link](this, [Link]) !=
PackageManager.PERMISSION_GRANTED) {
[Link](this, new String[]{[Link]}, 1);
}
7. Toasts (Notifications)
Quick notifications to users.
java
Copy code
[Link](this, "Hello, Android!", Toast.LENGTH_SHORT).show();
8. Logcat (Debugging)
Print logs for debugging.
java
Copy code
import [Link];
9. Async Task
Perform background tasks.
java
Copy code
private class MyTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
return "Background Task Completed";
}
@Override
protected void onPostExecute(String result) {
[Link]([Link], result, Toast.LENGTH_SHORT).show();
}
}
This is a foundational syntax for Android development. Each part can be expanded with more advanced
concepts as needed. Let me know if you'd like more details on any specific section!
1. Activity
An activity represents a single screen in an app.
java
Copy code
package [Link];
import [Link];
import [Link];
2. Layout (XML)
The layout defines the UI of an activity.
Example: res/layout/activity_main.xml
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
3. Event Handling
Handle user interactions like button clicks.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
4. Intents
Used for navigating between activities or passing data.
Start a New Activity:
java
Copy code
Intent intent = new Intent([Link], [Link]);
startActivity(intent);
Pass Data Between Activities:
java
Copy code
Intent intent = new Intent([Link], [Link]);
[Link]("KEY", "Value");
startActivity(intent);
Retrieve Data:
java
Copy code
String value = getIntent().getStringExtra("KEY");
5. Permissions
Request permissions in the manifest.
Example: [Link]
xml
Copy code
<uses-permission android:name="[Link]" />
Runtime Permission (for Android 6.0 and above):
java
Copy code
if ([Link](this, [Link]) !=
PackageManager.PERMISSION_GRANTED) {
[Link](this, new String[]{[Link]}, 1);
}
7. Toasts (Notifications)
Quick notifications to users.
java
Copy code
[Link](this, "Hello, Android!", Toast.LENGTH_SHORT).show();
8. Logcat (Debugging)
Print logs for debugging.
java
Copy code
import [Link];
9. Async Task
Perform background tasks.
java
Copy code
private class MyTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
return "Background Task Completed";
}
@Override
protected void onPostExecute(String result) {
[Link]([Link], result, Toast.LENGTH_SHORT).show();
}
}
You can download this content in a Word document using the link below:
Here's a simple Android code example that allows the user to add two numbers. This app will have two
input fields for entering the numbers, a button to perform the addition, and a text view to display the
result.
1. Layout (XML)
First, you need to create a layout for the app in activity_main.xml that contains two EditText views for
the input numbers, a Button to perform the addition, and a TextView to show the result.
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">
<EditText
android:id="@+id/firstNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="number" />
<EditText
android:id="@+id/secondNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="number" />
<Button
android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Numbers" />
<TextView
android:id="@+id/resultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result will be displayed here"
android:textSize="18sp"
android:layout_marginTop="20dp"/>
</LinearLayout>
2. Activity (Java Code)
Next, write the [Link] code to handle the addition logic.
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Initialize views
EditText firstNumber = findViewById([Link]);
EditText secondNumber = findViewById([Link]);
Button addButton = findViewById([Link]);
TextView resultText = findViewById([Link]);
if ([Link]() || [Link]()) {
// Show error if input is empty
[Link]([Link], "Please enter both numbers",
Toast.LENGTH_SHORT).show();
} else {
// Convert strings to integers
int firstNum = [Link](firstNumStr);
int secondNum = [Link](secondNumStr);
what is xmlns:android="[Link]
The xmlns:android="[Link] declaration is used in Android XML
files to define the XML namespace for Android attributes. Here's a detailed explanation:
What is a Namespace in XML?
In XML, a namespace is used to distinguish elements and attributes that belong to different vocabularies.
It prevents conflicts when multiple XML schemas are used in the same document. In the context of
Android, the xmlns:android is the XML namespace that identifies Android-specific attributes in layout
and resource XML files.
Why Do We Use xmlns:android?
• Unique Identification: Android's XML schema uses the android namespace to distinguish
Android-specific attributes (such as layout height, width, text size, etc.) from other possible XML
attributes.
• Defines Android's XML Vocabulary: The URL [Link] is a
reference to Android's XML schema. It tells the system that all attributes prefixed with android:
belong to Android's namespace and should be interpreted as Android attributes.
Syntax:
xml
Copy code
xmlns:android="[Link]
This declaration is usually found at the root of an XML layout file, such as activity_main.xml. It is required
for Android XML files that contain Android-specific attributes, and it typically appears in the first line of
the layout file.
Where Is It Used?
The xmlns:android declaration is required for all XML files used in Android development that reference
Android-specific attributes. For example, it is present in:
• Layout files (e.g., activity_main.xml)
• Drawable files (e.g., [Link])
• Menu files (e.g., menu_main.xml)
Example:
Here's how the namespace is used in a typical activity_main.xml layout file:
xml
Copy code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
Explanation of the Example:
• The xmlns:android="[Link] is declared in the
LinearLayout element.
• The android: prefix is used in attributes like android:layout_width, android:layout_height,
android:text, and android:id. These are all Android-specific attributes.
• Without this namespace declaration, the android: prefix would not be recognized, and Android
Studio or the Android system would not be able to interpret the attributes correctly.
Key Points:
• Namespace Declaration: xmlns:android="[Link] is
necessary to declare Android-specific attributes in XML.
• Prefix: The android: prefix is used for all attributes that are specific to Android, such as layout
properties, text, styles, etc.
• Required: This declaration is mandatory in Android XML files that use Android attributes.
Without it, the XML file will not work properly.
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
Is it Mandatory?
• Yes, the XML declaration is required in certain cases, especially when working with different
encodings or when you want to explicitly define the version of XML being used.
• No, it is not strictly required in every XML file, as XML parsers can assume version="1.0" and
encoding="UTF-8" by default if not explicitly specified. However, including it is a best practice to
avoid any ambiguity.
what is android:textSize="24sp"
the attribute android:textSize="24sp" is used in Android XML layout files to define the text size of a
TextView or any other UI component that displays text. Here's a detailed explanation:
1. android:textSize
• Purpose: This attribute controls the size of the text that will be displayed within a TextView,
Button, or other text-containing UI components in your Android app.
• It accepts a size value in either pixels or density-independent pixels (dp) or scale-independent
pixels (sp).
2. 24sp
• sp stands for Scale-independent Pixels, which is a unit used to define text size in Android.
Why sp and not dp or px?
• sp (Scale-independent Pixels) is preferred for text sizes because it takes into account the user's
preferred font size settings (which might be adjusted for accessibility reasons). The sp unit
ensures that text scales appropriately according to the device's display settings and the user's
preferences, especially if they have set a larger font size for better readability.
• dp (Density-independent Pixels) is used for defining general UI elements' sizes, but it doesn't
adjust based on the user's font size preference.
• px (Pixels) is the most basic unit and should be avoided for text size because it does not consider
screen density or user preferences. It is not scalable across devices with different screen sizes or
resolutions.
How does it work?
• When you define android:textSize="24sp", it tells Android to display the text with a size of 24
scale-independent pixels. This ensures that the text appears appropriately sized across different
screen densities and respects the user's font scaling preferences.
Example:
xml
Copy code
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="24sp" />
In this example:
• The text "Hello, World!" will be displayed with a text size of 24sp.
• The sp unit ensures that the text size will scale appropriately based on the user's settings, and
will appear consistent across various devices with different screen densities.
Key Takeaways:
• android:textSize="24sp" sets the text size to 24 scale-independent pixels.
• sp should be used for text size to ensure accessibility and proper scaling based on user
preferences and screen density.
Instructions:
1. Add the image to your project:
o Place your image file in the res/drawable directory (e.g.,
res/drawable/sample_image.png).
2. Create the XML layout: Define an ImageView in the res/layout/activity_main.xml file to display
the image:
xml
Copy code
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/image_description" />
</LinearLayout>
3. Update the Java code: Use the provided MainActivity code to set the image in your ImageView.
4. Run your application:
o Build and run the app on your Android device or emulator. The image from
[Link].sample_image will be displayed in the ImageView.
LOGIN
</LinearLayout>
[Link]
java
Copy code
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_login);
// Check credentials
if ([Link]("abdu") && [Link]("123")) {
[Link]([Link], "Success", Toast.LENGTH_SHORT).show();
} else {
[Link]([Link], "Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Steps to Complete:
1. Update the [Link]: Make sure your MainActivity is declared as the launcher
activity.
2. Run the App: Enter "abdu" as the username and "123" as the password to see the success
message. Any other credentials will result in a failure message.
Let me know if you'd like additional enhancements, such as transitioning to another activity on
successful login!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">
<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"
android:layout_marginTop="10dp" />
<Button
android:id="@+id/add_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add"
android:layout_marginTop="10dp" />
<Button
android:id="@+id/subtract_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Subtract"
android:layout_marginTop="10dp" />
<TextView
android:id="@+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result will be displayed here"
android:textSize="18sp"
android:layout_marginTop="20dp"
android:gravity="center" />
</LinearLayout>
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
// Initialize views
number1EditText = findViewById([Link].editTextNumber1);
number2EditText = findViewById([Link].editTextNumber2);
resultTextView = findViewById([Link]);