ANDROID APPLICATION SOLVED UE 22, 23.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

liaaaas

ANDROID APPLICATION
SOLVED
UE-2022, UE-2023.

R.F.Hyacent

manyumbaremmy@gmail.com
ANDROID APPLICATION SOLVED
UE-2022
QUESTION ONE

Differences between Implicit vs Explicit Intent:

Explicit Intent: It's used to start a specific component within the same application,
specifying the target component's class name. For example, starting a new activity
within the same app:

Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);

startActivity(intent);

Implicit Intent: It's used to invoke a system component or external application to


perform a specific action, without specifying the exact component. For example,
opening a web page:

Intent intent =
newIntent(Intent.ACTION_VIEW,Uri.parse("www.example.com"));

startActivity(intent);

b. Splash Screen:

A splash screen is a graphical control element consisting of a window containing an


image, logo, and current version of the software, presented to the user immediately
upon application launch. It serves as an introduction or branding for the
application while the main content loads in the background.

c. Permissions for SMS:

Two permissions needed for sending and receiving SMS messages:

<uses-permission android:name="android.permission.SEND_SMS"/>

<uses-permission android:name="android.permission.RECEIVE_SMS"/>

d. differences between onPause() vs onSaveInstanceState():

onPause(): Called when the activity is going into the background, but before it loses
focus. It's typically used to pause or adjust ongoing activities.
onSaveInstanceState(): Called before the activity is killed or destroyed, giving it a
chance to save its state data via a Bundle. It's primarily used to store transient data
that the activity will need if it is later recreated.

Qn 2. Brief Description of Android Project Resources:

a. res/mipmap:This directory contains your app's launcher icons. It is structured


similar to the res/drawable directory but is meant specifically for launcher icons.

b. Gradle: Gradle is an advanced build automation tool used primarily for Java
projects and Android development. It automates the process of building, testing,
publishing, and deploying software packages and other artifacts.

c. res/drawable: This directory holds drawable resources such as images, icons,


and XML files that describe shapes or graphics. These resources can be referenced
in the application code or XML layout files.

d. Menu: In Android, menus provide actions that affect the content of the activity.
They can be defined either statically in XML or dynamically in code. Menus typically
appear in the app bar or as a floating context menu.

e. Manifest: The AndroidManifest.xml file is a crucial part of an Android app. It


contains essential information about the app, such as its package name, version,
permissions required, components (activities, services, broadcast receivers), and
more. It serves as a blueprint for the Android system to understand and interact
with the app.

Qn 3. With examples, briefly provide the explanation of the following features:

a. String.xml: In Android development, strings.xml is a resource file used to store


string literals. It allows developers to externalize strings from their codebase,
making it easier to manage and localize applications. For example:

<resources>

<string name="app_name">MyApp</string>

<string name="hello_world">Hello, World!</string>

</resources>
b. Colors.xml: Similarly, colors.xml is a resource file used to store color values. It
centralizes color definitions, making it convenient to reuse and update colors across
an application. For example:

<resources>

<color name="primary_color">#6200EE</color>

<color name="accent_color">#03DAC5</color>

</resources>

c. Android Virtual Device (AVD): AVD is an emulator provided by the Android SDK
that allows developers to test their applications on various virtual device
configurations. Developers can create custom device configurations with specific
hardware profiles and system images. This helps in testing the application's
compatibility and performance across different Android devices.

d. TOAST: Toast is a small message that appears temporarily at the bottom of the
screen in Android applications. It is used to display brief notifications or feedback to
the user. For example:

Toast.makeText(context, "This is a toast message",Toast.LENGTH_SHORT).show();

e. View: In Android, a View is a fundamental building block of UI components. It


represents a rectangular area on the screen and is responsible for drawing and
handling user interactions. Views can include buttons, text fields, images, etc.

QN 4. You have been asked by the management of Dodoma Secondary School to


develop a mobile application that will store the information of the students. The app
should store name, region, age, gender and subjects of the student. The
management want to show the reports of how the student performs his/her
subjects (English, Mathematics, Physics, Chemistry and Biology). The management
also wants to show the dates of different events within the school. The management
suggests the following features to be used: radio button for gender, spinner for
region, and checkboxes for subjects. Use progress bar to show the performance of
the students and calendar to show the dates of the events. Based on the given
requirements, you found that the application has only two activities i.e. ActivityOne
and ActivityTwo.
a. Using the methods of Intent class show how you will send the student's data
to the second activity.

Answers.

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);

intent.putExtra("name", studentName);

intent.putExtra("region", selectedRegion);

intent.putExtra("age", studentAge);

intent.putExtra("gender", selectedGender);

intent.putExtra("subjects", selectedSubjects);

startActivity(intent);

b. Receiving student's data within the second activity using Intent:

Answer.

Intent intent = getIntent();

String name = intent.getStringExtra("name");

String region = intent.getStringExtra("region");

int age = intent.getIntExtra("age", 0);

String gender = intent.getStringExtra("gender");

ArrayList<String> subjects = intent.getStringArrayListExtra("subjects");


c. Saving student's details in a database using SQLiteOpenHelper class:

public class DBHelper extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;

private static final String DATABASE_NAME = "user.db";

private static final String TABLE_NAME = "student";

private static final String COLUMN_ID = "id";

private static final String COLUMN_NAME = "name";

private static final String COLUMN_REGION = "region";

private static final String COLUMN_AGE = "age";

private static final String COLUMN_GENDER = "gender";

private static final String COLUMN_SUBJECTS = "subjects";

public DBHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

public void onCreate(SQLiteDatabase db) {

String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("

+ COLUMN_ID + " INTEGER PRIMARY KEY,"

+ COLUMN_NAME + " TEXT,"

+ COLUMN_REGION + " TEXT,"

+ COLUMN_AGE + " INTEGER,"

+ COLUMN_GENDER + " TEXT,"

+ COLUMN_SUBJECTS + " TEXT"

+ ")";

db.execSQL(CREATE_TABLE);

}
@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

onCreate(db);

public void addStudent(Student student) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(COLUMN_NAME, student.getName());

values.put(COLUMN_REGION, student.getRegion());

values.put(COLUMN_AGE, student.getAge());

values.put(COLUMN_GENDER, student.getGender());

values.put(COLUMN_SUBJECTS, TextUtils.join(",", student.getSubjects()));

db.insert(TABLE_NAME, null, values);

db.close();

}
Qn5.The prime purpose of a content provider is to serve as a central repository of
data where users can store and can fetch the data. The access of this repository is
given to other applications also but in a safe manner in order to serve the different
requirements of the user. Write an application that will allow users store their
details such as name and phone numbers in a content provider. The application
should also allow other applications to retrieve the stored user's information. The
application has one activity called MainActivity, two edit texts for name and phone
number and two buttons for save data and view data. The ids for the views are
etName, etPhone Number, btnSave and btnView.

Answer

To achieve this functionality, you can follow these steps:

• Define a Content Provider to manage the storage and retrieval of user details.
• Implement the MainActivity with EditText fields for name and phone number,
and buttons to save and view data.
• Define necessary permissions in the AndroidManifest.xml file.
• Implement functionality to save and retrieve user details using the Content
Provider.

• //Define the Content Provider (UserContentProvider.java):

public class UserContentProvider extends ContentProvider {

public static final String AUTHORITY = "com.example.userprovider";

public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY +


"/users");

public static final String KEY_NAME = "name";

public static final String KEY_PHONE_NUMBER = "phone_number";

private static final int USERS = 1;

private static final int USER_ID = 2;

private static final UriMatcher uriMatcher;

static {

uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

uriMatcher.addURI(AUTHORITY, "users", USERS);

uriMatcher.addURI(AUTHORITY, "users/#", USER_ID);

}
private UserDbHelper dbHelper;

@Override

public boolean onCreate() {

dbHelper = new UserDbHelper(getContext());

return true;

@Nullable

@Override

public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable


String selection,

@Nullable String[] selectionArgs, @Nullable String sortOrder) {

SQLiteDatabase db = dbHelper.getReadableDatabase();

Cursor cursor;

switch (uriMatcher.match(uri)) {

case USERS:

cursor = db.query(UserContract.UserEntry.TABLE_NAME, projection, selection,


selectionArgs, null, null, sortOrder);

break;

default:

throw new IllegalArgumentException("Unknown URI: " + uri);

cursor.setNotificationUri(getContext().getContentResolver(), uri);

return cursor;

@Nullable

@Override

public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {


SQLiteDatabase db = dbHelper.getWritableDatabase();

long id;

switch (uriMatcher.match(uri)) {

case USERS:

id = db.insert(UserContract.UserEntry.TABLE_NAME, null, values);

break;

default:

throw new IllegalArgumentException("Unknown URI: " + uri);

getContext().getContentResolver().notifyChange(uri, null);

return Uri.parse(UserContract.UserEntry.TABLE_NAME + "/" + id);

• // Implement other necessary methods (update, delete, getType) based


on your requirements

@Nullable

@Override

public String getType(@NonNull Uri uri) {

return null;

• //Implement MainActivity.java:

public class MainActivity extends AppCompatActivity {

EditText etName, etPhoneNumber;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

etName = findViewById(R.id.etName);
etPhoneNumber = findViewById(R.id.etPhoneNumber);

public void onSaveButtonClick(View view) {

String name = etName.getText().toString();

String phoneNumber = etPhoneNumber.getText().toString();

ContentValues values = new ContentValues();

values.put(UserContentProvider.KEY_NAME, name);

values.put(UserContentProvider.KEY_PHONE_NUMBER, phoneNumber);

getContentResolver().insert(UserContentProvider.CONTENT_URI, values);

Toast.makeText(this, "Data successfully", Toast.LENGTH_SHORT).show();

public void onViewButtonClick(View view) {

Intent intent = new Intent(Intent.ACTION_VIEW,


UserContentProvider.CONTENT_URI);

startActivity(intent);

• //Define permissions and Content Provider in AndroidManifest.xml:

<manifest ...>

<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />

<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application ...>

<provider

android:name=".UserContentProvider"

android:authorities="com.example.userprovider"

android:exported="true" />

</application>

</manifest>
QN 6. Android Fragment represents a behavior or a portion of a user interface in an
activity. Multiple fragments can be combined in a single activity to build a multi-
panel User Interface (UI) and reuse a fragment in multiple activities. As a mobile
apps developer, you have been asked to develop an application with two fragments
named FragmentOne and FragmentTwo. When a user click on the specific
fragment, the description of the fragment displays on the fragment container in the
main activity which hosts the fragments. Assume the ids for FragmentOne and
Fragment Two are btnFragment_one and btnFragment_two respectively. Hint: use
linear layout to create a fragment container.

ANSWER

To achieve the functionality described, you need to follow these steps:

• Create layout files for FragmentOne and FragmentTwo.


• Implement the main activity layout with a fragment container.
• Implement FragmentOne and FragmentTwo classes.
• Handle clicks on the buttons in the main activity to display the respective
fragments.

Layout files for FragmentOne (fragment_one.xml) and FragmentTwo


(fragment_two.xml):

<TextView

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/text_fragment_one"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:text="Description of Fragment One"

android:textSize="20sp"

android:gravity="center"/>

fragment_two.xml:

<TextView

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/text_fragment_two"

android:layout_width="match_parent"
android:layout_height="match_parent"

android:text="Description of Fragment Two"

android:textSize="20sp"

android:gravity="center"/>

//Main activity layout (activity_main.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/fragment_container"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<Button

android:id="@+id/btnFragment_one"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Fragment One"

android:onClick="onClickFragmentOne"/>

<Button

android:id="@+id/btnFragment_two"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Fragment Two"

android:onClick="onClickFragmentTwo"/>

</LinearLayout>
//FragmentOne.java:

public class FragmentOne extends Fragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle


savedInstanceState) {

return inflater.inflate(R.layout.fragment_one, container, false);

//FragmentTwo.java:

public class FragmentTwo extends Fragment {

@Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle


savedInstanceState) {

return inflater.inflate(R.layout.fragment_two, container, false);

//MainActivity.java:

public class MainActivity extends AppCompatActivity {

LinearLayout fragmentContainer;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main)

fragmentContainer = findViewById(R.id.fragment_container);

public void onClickFragmentOne(View view) {

FragmentOne fragmentOne = new FragmentOne();

getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, fragmentOne)

.commit();

public void onClickFragmentTwo(View view) {

FragmentTwo fragmentTwo = new FragmentTwo();

getSupportFragmentManager().beginTransaction()

.replace(R.id.fragment_container, fragmentTwo)

.commit();

QN 8.There are tasks that do not really need to be visible to the user. A good
example is playing a music. You don't need to keep the player's screen for song to
play. Those kinds of applications/tasks runs in the background.

i. The kind of Android component that you can use to accomplish tasks that
run in the background without the need for a visible user interface is a
Service.
ii. Below is a Java class implementation of a Service for playing music:

import android.app.Service;

import android.content.Intent;

import android.media.MediaPlayer;

import android.net.Uri;

import android.os.IBinder;

public class MusicPlayerService extends Service {

private MediaPlayer mediaPlayer;

@Override

public void onCreate() {

super.onCreate();

mediaPlayer = new MediaPlayer();

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Uri defaultRingtoneUri = Settings.System.DEFAULT_RINGTONE_URI;

try {

mediaPlayer.setDataSource(getApplicationContext(), defaultRingtoneUri);

mediaPlayer.prepare();

mediaPlayer.start();

} catch (Exception e) {

e.printStackTrace();

return START_NOT_STICKY;

@Override

public void onDestroy() {

super.onDestroy();

if (mediaPlayer != null) {
mediaPlayer.stop();

mediaPlayer.release();

@Override

public IBinder onBind(Intent intent) {

return null;

IN JAVA CLASS

• onCreate(): Initializes the MediaPlayer object.


• onStartCommand(): Starts playing the music specified by the default
ringtone URI.
• onDestroy(): Stops and releases the MediaPlayer resources when the service
is destroyed.
• onBind(): Returns null since we don't need to bind to this service.

Remember to declare this service in the AndroidManifest.xml file:

<service android:name=".MusicPlayerService" />

You can start this service from any component like an Activity or another Service
using startService()
b). The management of CIVE cafeteria wants to implement an android system that
will manage its customers. The application has only one activity named
MainActivity with three edit texts and one button. One of the functionality of the
application is to store the customer's information such as name, email and phone
number. The customer's data are in small amount and are in key/value pairs. Write
an android application that will store the customer's information in a Shared
Preference. The ids for the edit texts and button are etName, etEmail,
etPhoneNumber and btnSave.

Here's how you can implement an Android application to store customer


information in SharedPreferences:

• //MainActivity layout (activity_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="16dp">

<EditText

android:id="@+id/etName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Name"

android:inputType="text" />

<EditText

android:id="@+id/etEmail"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/etName"

android:layout_marginTop="16dp"

android:hint="Email"

android:inputType="textEmailAddress" />
<EditText

android:id="@+id/etPhoneNumber"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_below="@id/etEmail"

android:layout_marginTop="16dp"

android:hint="Phone Number"

android:inputType="phone" />

<Button

android:id="@+id/btnSave"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_below="@id/etPhoneNumber"

android:layout_marginTop="16dp"

android:text="Save"

android:onClick="saveCustomerInfo" />

</RelativeLayout>

//MainActivity.java

import android.content.Context;

import android.content.SharedPreferences;

import 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 etName, etEmail, etPhoneNumber;

private SharedPreferences sharedPreferences;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

etName = findViewById(R.id.etName);

etEmail = findViewById(R.id.etEmail);

etPhoneNumber = findViewById(R.id.etPhoneNumber);

sharedPreferences = getSharedPreferences("customer_info",
Context.MODE_PRIVATE);

public void saveCustomerInfo(View view) {

String name = etName.getText().toString();

String email = etEmail.getText().toString();

String phoneNumber = etPhoneNumber.getText().toString();

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("name", name);

editor.putString("email", email);

editor.putString("phone_number", phoneNumber);

editor.apply();

Toast.makeText(this, "information saved", Toast.LENGTH_SHORT).show();

}
UE-2023
QUESTION ONE.

Choose the most correct answer and write its letter in the answer booklet provided.

(1 Mark Each)

i. All layout classes are the subclasses of: -

A. Android.widget

B. Android.view.View

C. Android.view.ViewGroup

D. Android.view. Widget

ii. What is manifest XML in android?

A. A file that contains all information about the layout of the android application.

B. A file that contains all the information about the android application.

C. A file that contains all the information about the activities of the android
application.

D. A file that contains all resources of the android application.

iii. What is the use of a content provider in Android?

A. For sharing data between one activity and another activity.

B. For storing data in a SQLite database.

D. For sending data from one application to another application.

D. For storing data in a shared preferences.

iv. While developing android application developers can test their apps on:-

A. Emulators in android SDK.

B. Android phone.

C. Third-party emulator.

D. All of the above.


V. The services in android can be stopped using which of the following method?

A. system.exit() and stopService().

B. stopSelf() and stopService().

C. finish() and end().

D. serviceStop() and endService().

vi. Identify among the following which is not a state in the service lifecycle.

A. Running.

B. Start.

C. Paused.

D. Destroyed.

vii. Identify the dialogue class in Android among the following.

A. DatePicker.

B. AlertDialog.

C. ProgressDialog.

D. All of the above.

viii. What is the life cycle of broadcast receivers in android?

A. send intent().

B. onReceive.

C. implicitBroadcast().

D. sendBroadcast(), sendSticky Broadcast(). sendOrderBroadcast().


ix. What runs in the background and doesn't have any UI components?

A. Intents.

B. Content Providers.

C. Services.

D. Applications.

Χ. Which one is not a nickname of a version of Android?

A. Cupcake.

B. Gingerbread.

C. Honeycomb.

D. Android.
QUESTION 2.

Write true if the statement is correct and false if the statement is incorrect.

(a) Mobile Apps On Both Android And IOS Platforms Should Not Perform Long
Lasting Tasks, Such As Network FALSE

(b) Android is built upon the Java Micro Edition (J2ME) version of java FALSE.

(c) Native libraries is one of the core component of the .apk in android TRUE.

(d) The code which is compiled to run the android application is always contained
within the xml layout file. FALSE.

(e) The xml file that contains all the texts that your application uses is called
text.xml FALSE.

(f) There is no guarantee that an activity will be stopped prior to being destroyed.
TRUE.

(g) In an explicit intent, the sender specifies the type of receiver. FALSE.

(h) There can be only one running activity in a given time. FALSE.

(i) Java is the only programming language used to make an android application.
FALSE.

(j) The only database that android application can work with is SQLite. FALSE.
QUESTION 3.

a) Assume you have a running application that is already running an Activity called
Activity1. ActivityIstarts another Activity called
Activity2. Name one Activity lifecycle method that will be called on Activity1 after
this point, but before Activity2 starts.

onPause() method will be called on Activity1 after this point, but before
Activity2 starts.

(b) Suppose you have an application that is running an Activity called Activity1.
Suppose that Activity1 executes and starts other Activities, but that the user never
quits or backs out of the Activity. How many times can Activityl's onCreate() method
get called?

Activity1's onCreate() method can be called multiple times, but only when the
system needs to create a new instance of Activity1 due to memory constraints
or configuration changes. It can be called several times during the lifetime of
the application.

(c) Suppose that there are two activities in an application named ActivityOne and
ActivityTwo. You want to invoke ActivityTwo from ActivityOne. What code you will
write?

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);

startActivity(intent);

(d) How will you reference a textbox control in java file, that is available in XML file
and the ID is txtName. (4 Marks)

EditText txtName = findViewById(R.id.txtName);


(e) Suppose that there are two activities in an application named FirstActivity and
SecondActivity. You want to send website name from ActivityOne to ActivityTwo.
What code you will write? Suppose that website name is www.udom.ac.tz. (5 Marks)

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);

intent.putExtra("websiteName", "www.udom.ac.tz");

startActivity(intent);

(f) How will you get the data in secondActivity? Refer to part (e)

Intent intent = getIntent();

String websiteName = intent.getStringExtra("www.udom.ac.tz");


QUESTION 4.(EXPECTED ROR 100%)

Many students now days fail to manage loan that they get from Higher Education
Students Loan Board (HESLB). Most of them finish the money even before the
period they are supposed to use. Based on the mentioned problem, HESLB wants a
mobile application called Budget Planner that will helps their beneficiaries to
manage their money. As a mobile apps developer, you have been consulted with
HESLB to develop the Budget Planner mobile app that will do the following: receive
the amount from the student (initial balance), the student will enter the number of
days that he/she supposed to use the money. Every time the student spends a
certain amount of money the app should deduct from the initial balance. Once the
student is about to finishes the money, the app should alert him/her. The app
should not allow the student to spend more than his/her initial balance.

Answer

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class BudgetPlannerActivity extends AppCompatActivity {

private double initialBalance;

private double remainingBalance;

private int daysLeft;

private EditText editTextInitialBalance;

private EditText editTextDaysLeft;

private EditText editTextSpending;

private TextView textViewRemainingBalance;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_budget_planner);

editTextInitialBalance = findViewById(R.id.editText_initial_balance);

editTextDaysLeft = findViewById(R.id.editText_days_left);

editTextSpending = findViewById(R.id.editText_spending);

textViewRemainingBalance = findViewById(R.id.textView_remaining_balance);

Button buttonSpend = findViewById(R.id.button_spend);

buttonSpend.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

spendMoney();

});

private void spendMoney() {

// Get initial balance and days left from user input

initialBalance =
Double.parseDouble(editTextInitialBalance.getText().toString());

daysLeft = Integer.parseInt(editTextDaysLeft.getText().toString());

// Calculate daily budget

double dailyBudget = initialBalance / daysLeft;

// Get spending amount from user input

double spending = Double.parseDouble(editTextSpending.getText().toString());

// Deduct spending amount from balance

if (spending <= remainingBalance) {

remainingBalance -= spending;

textViewRemainingBalance.setText("Remaining Balance: $" +


String.format("%.2f", remainingBalance));

} else {
showAlert("Insufficient funds!");

// Alert when balance is low

if (remainingBalance <= dailyBudget) {

showAlert("You are about to finish your budget!");

private void showAlert(String message) {

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage(message)

.setCancelable(false)

.setPositiveButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int id) {

dialog.dismiss();

});

AlertDialog alert = builder.create();

alert.show();

}
QUESTION 5.

Currently, UDOM SACCOS have no tool to automate its operations as a result there
is a delay in providing services to its customers. You have been asked by the
management of UDOOM SACCOS to develop a mobile application that will store the
information of its customers. The app should store name, college, age, gender and
monthly contribution of its customers. The management want to show the reports
of how customers are contributing monthly. The management also wants to show
the dates of different events within SACCOS such as the date of annual meeting etc.
The management suggests the following features to be used: radio button for gender
and spinner for college. Use progress bar to show the monthly contributions and
calendar to show the dates of the events. Based on the given requirements, you
found that the application has only two activities i.e. ActivityOne and Activity Two.

(a) To send the customer's data to the second activity using the Intent class, you
would use the putExtra() method to add the data to the Intent object before starting
the second activity. Here's how you can do it:

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);

intent.putExtra("name", customerName);

intent.putExtra("college", selectedCollege);

intent.putExtra("age", customerAge);

intent.putExtra("gender", selectedGender);

intent.putExtra("monthlyContribution", monthlyContribution);

startActivity(intent);
(b) To receive the customer's data within the second activity using the Intent
class, you would use the getIntent() method to retrieve the Intent object that
started the activity, and then use the getXXXExtra() methods to extract the data
from the Intent object. Here's how you can do it:

Intent intent = getIntent();

String name = intent.getStringExtra("name");

String college = intent.getStringExtra("college");

int age = intent.getIntExtra("age", 0); // assuming age is an integer

String gender = intent.getStringExtra("gender");

double monthlyContribution =
intent.getDoubleExtra("monthlyContribution", 0.0);

// assuming monthlyContribution is a double


(c) To save the customer's details in a database using SQLiteOpenHelper class,
you would create a subclass of SQLiteOpenHelper and override its onCreate()
and onUpgrade() methods. Then, you would execute SQL queries to create the
database and table, and insert the customer's details into the table. Here's how
you can do it:

public class CustomerDatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "user";

private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "customer";

private static final String COLUMN_NAME = "name";

private static final String COLUMN_COLLEGE = "college";

private static final String COLUMN_AGE = "age";

private static final String COLUMN_GENDER = "gender";

private static final String COLUMN_MONTHLY_CONTRIBUTION =


"monthly_contribution";

// SQL query to create the customer table

private static final String SQL_CREATE_CUSTOMER_TABLE = "CREATE


TABLE " + TABLE_NAME + " (" +

COLUMN_NAME + " TEXT," +

COLUMN_COLLEGE + " TEXT," +

COLUMN_AGE + " INTEGER," +

COLUMN_GENDER + " TEXT," +

COLUMN_MONTHLY_CONTRIBUTION + " REAL)";

public CustomerDatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

}
@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(SQL_CREATE_CUSTOMER_TABLE);

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// Implement if needed

public void addCustomer(String name, String college, int age, String gender, double
monthlyContribution) {

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(COLUMN_NAME, name);

values.put(COLUMN_COLLEGE, college);

values.put(COLUMN_AGE, age);

values.put(COLUMN_GENDER, gender);

values.put(COLUMN_MONTHLY_CONTRIBUTION, monthlyContribution);

db.insert(TABLE_NAME, null, values);

db.close();

Then, to save a customer's details:

CustomerDatabaseHelper dbHelper = new CustomerDatabaseHelper(this);

dbHelper.addCustomer(customerName, selectedCollege, customerAge,


selectedGender, monthlyContribution);

This will save the customer's details in the "customer" table of the "user"
database.
QUESTION SIX

The prime purpose of a content provider is to serve as a central repository of data


where users can store and can fetch the data. The access of this repository is given
to other applications also but in a safe manner in order to serve the different
requirements of the user. Write an application that will allow users store their
details such as name and phone numbers in a content provider. The application
should also allow other applications to retrieve the stored user's information. The
application has one activity called MainActivity, two edit texts for name and phone
number and two buttons for save data and view data. The ids for the views are
etName, etPhoneNumber, btnSave and btnView.

REFEER TO UE 2022 QN 5.

QUESTION SEVEN

Android Fragment represents a behavior or a portion of a user interface in an


activity. Multiple fragments can be combined in a single activity to build a multi-
panel User Interface (UI) and reuse a fragment in multiple activities. As a mobile
apps developer, you have been asked to develop an application with two fragments
named FragmentOne and FragmentTwo. When a user click on the specific
fragment, the description of the fragment displays on the fragment container in the
main activity which hosts the fragments. Assume the ids for FragmentOne and
Fragment Two are btnFragment_one and btnFragment_two respectively. Hint: use
linear layout to create a fragment container. (20 Marks)

REFEER TO UE 2022 QN 6.

You might also like