Complex Problems - MAD - With Example and Hint

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Department of CSE III Year

Course Title: - Mobile Application Development with Lab


Course Code(s): - 21CSH-355/21ITH-355

Complex Problems

Problem-1: Custom View:

Statement: Create a custom view that displays a complex shape or chart. Override
onDraw() to handle custom drawing.

Note -To create a simple custom view that draws a pie chart.
In Your example, the custom view will take an array of data representing the percentage
of each slice in the pie chart.
For Example:-You can then include this custom view in your layout XML file or
dynamically add it to your view hierarchy in your activity.

Input XML Code:-


<com.example.PieChartView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"/>

Problem-2: AsyncTask and Networking:

Implement an AsyncTask to perform network operations (e.g., fetching data from a


server) and update the UI accordingly.

Note -AsyncTask is a class in Android that allows you to perform background


operations and publish results on the UI thread without having to manipulate threads and
handlers directly. It is commonly used for tasks such as network operations. However,
as of Android API level 30, AsyncTask has been deprecated, and other alternatives like
Executor, AsyncTaskLoader, or third-party libraries like RxJava or Coroutine are
recommended. I'll provide an example using AsyncTask for educational purposes, but
keep in mind that you should consider alternative approaches.

AsyncTask for Network Operations:


Example of an AsyncTask that performs a network operation, such as fetching data from
a URL and updating the UI with the result.

Note: In a real-world application, consider using more advanced networking libraries,


error handling, and potentially moving away from AsyncTask to more modern
alternatives, such as Retrofit with RxJava or Coroutines.
XML Code:-
<uses-permission android:name="android.permission.INTERNET" />
Problem- Multithreading and Handlers:

Statement: Use multiple threads to perform time-consuming tasks. Communicate


between threads using Handlers to update the UI.

Note: We create a new thread (BackgroundThread) to simulate a time- consuming task


(e.g., background processing or network request).
Inside the thread, we use a Handler (uiHandler) associated with the UI thread to
communicate back to the UI thread.
The Background Thread updates the progress and sends a message to the Ui Handler
using send Message.
The uiHandler receives the message and updates the UI accordingly.
For example, it uses a simple progress update and message handling to demonstrate
communication between the background thread and the UI thread. In a real-world
scenario, you would replace the simulated task with your actual time-consuming task.
Also, consider using modern concurrency approaches like AsyncTask,
ThreadPoolExecutor, or Kotlin coroutines for more robust threading solutions.
XML code:-

Example (As Input)


(activity_multithreading.xml) for the mentioned MultithreadingActivity. This XML
layout includes a ProgressBar, a TextView for displaying results, and a Button to trigger
the background task.
<!-- res/layout/activity_multithreading.xml -->
<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=".MultithreadingActivity">

<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_margin="16dp"
android:visibility="visible" />

<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/progressBar"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Result will appear here"
android:textSize="18sp" />

<Button
android:id="@+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/resultTextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Start Background Task" />

</RelativeLayout>

Problem-4 Custom Animation:

Statement: Create a custom animation (e.g., property animation) to enhance the user
interface. Apply animations to views and provide interactive elements.

Note
XML Layout (activity_main.xml):
<!-- res/layout/activity_main.xml -->
<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">

<Button
android:id="@+id/animatedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click Me" />

</RelativeLayout>
Example:
The XML layout contains a Button with the ID animatedButton.
In the MainActivity, we find the Button by its ID and set a click listener on it.
When the button is clicked, the animateButtonScale method is called, which uses
ObjectAnimator to scale the button in the X and Y directions.
You can customize the animation by adjusting the properties and duration as per your
requirements. Property animations offer a wide range of possibilities to enhance the user
interface and create interactive elements
Problem-5 Firebase Integration:

Statement:
Integrate Firebase Authentication and Realtime Database into your app. Implement
features like user registration, login, and data synchronization.

Note:
Step 1: Add Firebase to your Android project
Go to the Firebase Console.
Create a new project or select an existing one.
Click on "Add App" and follow the setup instructions to add Firebase to your Android
app.
Download the google-services.json file and place it in the app directory of your Android
project.
Step 2: Add Firebase Authentication and Realtime Database dependencies
Open your app-level build.gradle file and add the following dependencies:
implementation 'com.google.firebase:firebase-auth:22.0.0' // Use the latest version
implementation 'com.google.firebase:firebase-database:22.0.0' // Use the latest version

Sync your project with the updated Gradle


files. Step 3: Design XML layout
(activity_main.xml) XML code:-
<!-- res/layout/activity_main.xml -->
<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/emailEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:inputType="textEmailAddress"
android:layout_margin="16dp"/>

<EditText
android:id="@+id/passwordEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:layout_below="@id/emailEditText"
android:layout_margin="16dp"/>

<Button
android:id="@+id/registerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register"
android:layout_below="@id/passwordEditText"
android:layout_margin="16dp"/><Button
android:id="@+id/loginButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/registerButton"
android:layout_margin="16dp"/>

</RelativeLayout>

Step 4: Implement Firebase Authentication and Realtime Database in


Java (MainActivity.java)

Problem-6: Camera API:

Utilize the camera API to capture photos or record videos. Save the media to storage and
display it in your app.

Note: The Android Camera API has been deprecated in recent versions of Android
in favor of the CameraX library. However, if you still want to use the deprecated
Camera API, you can do so for older devices. Below is a simple example of
capturing photos using the deprecated Camera API.
Note: For new projects or if you are targeting recent Android versions, consider
using CameraX or another modern camera library.

XML Layout (activity_main.xml):


<!-- res/layout/activity_main.xml -->
<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">

<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<Button
android:id="@+id/captureButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp" />

</RelativeLayout>
Example:
The MainActivity includes a SurfaceView to display the camera preview and a Button to
capture photos.
The Camera API is used to open the camera, set the preview display, and capture
photos.
The surfaceCreated, surfaceChanged, and surfaceDestroyed methods handle the camera
lifecycle events.
The capturePhoto method initiates the photo capture process when the capture button is
clicked.
The pictureCallback saves the captured photo to external storage.
Keep in mind that the Camera API is deprecated, and for modern applications, you
should consider using CameraX or other camera libraries.

Problem-7 Dependency Injection with Dagger 2:

Statement:
Learn and implement Dagger 2 for dependency injection. Use it to manage dependencies
in a complex 8. Android application.

Note: -Dagger 2 is a popular dependency injection framework in Android. It helps


manage and simplify the dependency injection process in complex Android applications.
Below, I'll provide you with a basic example of using Dagger 2 for dependency injection
in an Android application.

Step 1: Add Dagger 2 Dependencies


Step 2: Create Dagger Components and Modules
AppModule.java code:-
Step 3: Initialize Dagger in the Application
class Step 4: Inject Dependencies in Activity
Step 5: AndroidManifest.xml
Ensure that you declare your custom application class in the AndroidManifest.xml
file:
<application
android:name=".MyApplication"
<!-- other attributes -->
>
<!-- other components -->
</application>

Example:
AppModule provides a Context instance.
AppComponent is a Dagger component that defines the injection methods.
MyApplication initializes Dagger and provides access to the Dagger component.
MainActivity injects the dependencies using Dagger.
This is a basic setup, and in a real-world scenario, you might have more complex
dependency structures. Dagger 2 allows you to create scopes, handle singletons, and
manage different lifecycles. Adjust the example according to your application's needs.
Problem 8- Sensor Integration:
Statement:

Utilize sensors like accelerometer or gyroscope. Implement features based on sensor


data, such as shaking the device to trigger an action.
Note: Create an example that utilizes the accelerometer sensor to detect device
shaking and trigger an action. In this example, we'll create a simple app that changes
the background color when the device is shaken.
XML Layout (activity_main.xml):
<!-- res/layout/activity_main.xml -->
<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">

<TextView
android:id="@+id/shakeInfoTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Shake the device!"
android:textSize="18sp" />

</RelativeLayout>

Example:
The SensorManager is used to access the device's sensor service.
The accelerometer sensor is registered in the onResume method and unregistered in the
onPause method to save power when the app is not in the foreground.
The onSensorChanged method is called when sensor values change. We use it to detect
device shaking based on accelerometer data.
The changeBackgroundColor method is called when the device is shaken to change the
background color randomly.
The getRandomColor method generates a random color.

Remember to request the necessary permissions in your AndroidManifest.xml file:

<uses-feature android:name="android.hardware.sensor.accelerometer"
android:required="true" />
Problem -9 Room Database with LiveData:

Statement:
Implement a Room database with LiveData to store and retrieve data. Design and
implement a complex database schema.
Note - Implementing a Room database with LiveData involves creating an entity, a data
access object (DAO), a Room database, and using LiveData to observe changes in the
data. Below is an example demonstrating a simple To-Do list application with a complex
database schema using Room and LiveData.

Step 1: Add Room


Dependencies Step 2: Create
Entity Classes Task.java
Category.java
Step 3: Create Data Access Objects (DAO)
TaskDao.java
CategoryDao.java
import androidx.room.Dao;

Step 4: Create Room Database


AppDatabase.java

Step 5: Initialize Room Database in Application Class


MyApplication.java

Step 6: Use LiveData in ViewModel


TaskViewModel.java
CategoryViewModel.java

Step 7: Observe LiveData in Activity


MainActivity.java
XML Code:-
You have a simple entity User and a corresponding ViewModel UserViewModel to
retrieve data from the Room database. In this example, we'll use a RecyclerView to
display a list of users in an XML layout.
Step 1: XML Layout (activity_main.xml)
<!-- res/layout/activity_main.xml -->
<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">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:clipToPadding="false"
android:scrollbars="vertical" />

</RelativeLayout>
Step 2: RecyclerView Item Layout (item_user.xml)
<!-- res/layout/item_user.xml -->
<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="8dp">

<TextView
android:id="@+id/usernameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />

<!-- Add more TextViews for other user details if needed -->

</LinearLayout>

Example:
activity_main.xml defines the layout for the main activity, which includes a
RecyclerView.
item_user.xml is the layout for each item in the RecyclerView.
UserAdapter is a custom adapter for the RecyclerView to bind data to the
views. MainActivity sets up the RecyclerView, creates an instance of
UserAdapter, and observes the LiveData list of users to update the UI when the
data changes.
Problem: 10 Google Maps Integration:

Integrate Google Maps API into your app. Display maps, markers, and implement
features like geolocation and route plotting.
Note: To integrate Google Maps API into your Android app, you need to obtain an API
key from the Google Cloud Platform and include the necessary permissions in your
AndroidManifest.xml file. Below is an example that shows how to display a map, add
markers, and implement geolocation with route plotting.

Step 1: Get Google Maps API Key


Visit the Google Cloud Console, create a new project, enable the "Maps SDK for
Android" API, and generate an API key.

Step 2: Add Permissions and API Key to AndroidManifest.xml


XML Code:-
<!-- Add these permissions inside the <manifest> tag -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- Add this metadata element inside the <application> tag -->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY" />
Replace "YOUR_API_KEY" with the API key you obtained.

Step 3: XML Layout (activity_maps.xml)


<!-- res/layout/activity_maps.xml -->
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mapFragment"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
Step 4: Java Code (MapsActivity.java)
Example:
activity_maps.xml contains a SupportMapFragment to display the map.
MapsActivity.java is the main activity that implements OnMapReadyCallback and
handles the map-related functionality.
The app requests permission to access the user's location and displays the map with a
marker at a specific location.
The user's current location is obtained and displayed on the map, and the camera is
moved to focus on the current location.
Note: Make sure to replace "YOUR_API_KEY" with your actual Google Maps API key
in the AndroidManifest.xml file.

You might also like