0% found this document useful (0 votes)
9 views77 pages

Piyush - Mobile Architecture & Programming Lab (1)

The document outlines a practical record for the Mobile Architecture & Programming Lab (ETCT 452) submitted by a student named Anupam. It includes a detailed index of experiments focused on mobile app development, covering topics such as setting up the development environment, user interface design, database integration, and app deployment. Each experiment provides specific aims, procedures, and example code for Android and iOS applications.

Uploaded by

Sahil Sadhwani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views77 pages

Piyush - Mobile Architecture & Programming Lab (1)

The document outlines a practical record for the Mobile Architecture & Programming Lab (ETCT 452) submitted by a student named Anupam. It includes a detailed index of experiments focused on mobile app development, covering topics such as setting up the development environment, user interface design, database integration, and app deployment. Each experiment provides specific aims, procedures, and example code for Android and iOS applications.

Uploaded by

Sahil Sadhwani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Mobile Architecture & Programming Lab

[ ETCT 452 ]

SUBMITTED TO: SUBMITTED BY:

Ashish Sharma Anupam

01114812720

8CST1

DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

MAHARAJA AGRASEN INSTITUTE OF TECHNOLOGY


Plot No 1 Rohini, Plot No 1, CH Bhim Singh Nambardar Marg,
Sector 22, PSP Area, Delhi, 110086
PRACTICAL RECORD

Paper Code : ETCT 452

Name of the Student : Anupam

University Roll No. : 01114812720

Branch : Computer Science and Technology

Group : 8CST1

INDEX
S. Experiment Name Date of R1 R2 R3 R4 R5 Total Remarks Signature
No. Performing (3) (3) (3) (3) (3) Marks
(15)
1. Setting up the Development
Environment
● Install Android Studio and
set up the Android
development environment.
● Create a basic "Hello
World" app for Android and
iOS platform

2. User Interface Design and


Development
● Design a simple user
interface using XML for an
Android app.
● Implement navigation
between multiple screens in
both Android apps.
3. Database Integration in
Mobile Apps
● Create a SQLite database
and perform basic CRUD
operations in an Android app.
● Implement Core Data
framework for data storage in
an iOS app.

4. Web Services and API


Consumption
● Retrieve data from a
RESTful API and display it in
an Android app.
● Consume a web service and
display data in an iOS app
using URLSession.

5. Location-Based Services and


Mapping
● Implement location tracking
and display user location on a
map in an Android app using
Google Maps API.
● Integrate MapKit
framework in an iOS app to
show user location and add
annotations
on the map.
6. Cross-Platform App
Development with React
Native or Flutter
● Develop a simple mobile
app using React Native,
utilizing components and
navigation.
● Create a mobile app using
Flutter, implementing UI
elements and handling user
input.
7. Testing and Debugging
● Perform unit testing on key
functionalities of an Android
app using JUnit and
Android Testing frameworks.
● Debug and test an iOS app
using Xcode debugger and
XCTest framework.

8. App Deployment and


Performance Optimization
● Package and deploy an
Android app to Google Play
Store.
● Package and deploy an iOS
app to the App Store.
● Optimize app performance
by analyzing and improving
resource usage, network
efficiency, and
responsiveness.
9. Augmented Reality (AR)
Integration
● Integrate AR features into
an Android app using ARCore
or ARKit for iOS

.
EXPERIMENT - 1

Aim: : Setting up the Development Environment


● Install Android Studio and set up the Android development environment.
● Create a basic "Hello World" app for Android and iOS platforms

Procedure : Install Android Studio and set up the Android development environment.

Step 1 - System Requirements The required tools to develop Android applications are open
source and can be downloaded from the Web. Following is the list of software's you will need
before you start your Android application programming.
● Java JDK5 or later version
● Java Runtime Environment (JRE) 6
● Android Studio

Step 2 - Setup Android Studio Android Studio is the official IDE for android application development.It
works based on IntelliJ IDEA, You can download the latest version of android studio from Android
Studio 2.2 Download, If you are new to installing Android Studio on windows,you will find a file, which
is named as android-studio-bundle-143.3101438-windows.exe.So just download and run on windows
machine according to android studio wizard guideline. If you are installing Android Studio on Mac or
Linux, You can download the latest version from Android Studio Mac Download,or Android Studio
Linux Download, check the instructions provided along with the downloaded file for Mac OS and Linux.
This tutorial will consider that you are going to set up your environment on a Windows machine having
Windows 8.1 operating system. Installation So let's launch Android Studio.exe,Make sure before
launching Android Studio, Our Machine should require installed Java JDK. To install Java JDK,take
references of Android environment setup.

Once you launch Android Studio, it's time to mention JDK7 path or later version in android studio
installer.
Below the image initiating JDK to android SDK

Need to check the components, which are required to create applications, below the image has selected
Android Studio, Android SDK, Android Virtual Machine and performance(Intel chip).
Need to specify the location of the local machine path for Android studio and Android SDK, below the
image has taken default location of windows 8.1 x64 bit architecture.

Need to specify the ram space for Android emulator by default it would take 512MB of local machine
RAM.
At the final stage, it would extract SDK packages into our local machine, it would take a while to finish
the task and would take 2626 MB of Hard disk space.

After done all above steps perfectly, you must get finish button and it gonna be open android studio
project with Welcome to android studio message as shown below
You can start your application development by calling start a new android studio project. in a new
installation frame should ask Application name, package information and location of the project.

After entered application name, it going to be called select the form factors your application runs on, here
need to specify Minimum SDK, in our tutorial, I have declared as API23: Android 6.0(Marshmallow)

Create a basic "Hello World" app for Android and iOS platforms

First step is to create a simple Android Application using Android studio. When you click on
Android studio icon, it will show screen as shown below -
You can start your application development by calling start a new android studio project. in a new
installation frame should ask Application name, package information and location of the project.−

Configure the Hello World Project Details We'll finish creating the project by configuring some details
about its name, location, and the API version.
Change the name of the application. Change the default Project location to your preferred
directory or just leave it as the default location.
On the minimum API level, ensure that API 15: Android 4.0.3 IceCreamSandwich is set as the
Minimum SDK. This ensures that your application runs on almost all devices.

The next level of installation should contain selecting the activity to mobile, it specifies the default layout
for Applications.
SOURCE CODE :
The Main Activity File
The main activity code is a Java file MainActivity.java. This is the actual application file which
ultimately gets converted to a Dalvik executable and runs your application

package com.example.helloworldapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

The Layout File


The activity_main.xml is a layout file available in res/layout directory, that is referenced by your
application when building its interface. You will modify this file very frequently to change the
layout of your application. For your "Hello World!" application, this file will have following content
related to default layout −

<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" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />

Running app on Phone:

Connect your Phone to Computer Plug in your device to your computer with a USB cable. If you're
developing on Windows, you might need to install this universal ADB USB driver or find your specific
USB driver for your device.

Enable USB Debugging :

The next step is to enable USB debugging so your phone can interact with your computer in a developer
mode

The following steps are needed:


1. (Windows Only) Install this ADB Driver
2. Plug-in your Android Device to Computer via USB
3. Open the "Settings" App on the Device
4. Scroll down to bottom to find "About phone" item
5. Scroll down to bottom to find "Build number" section
6. Tap on "Build Number" 7 times in quick succession
7. You should see the message "You are now a developer!"
8. Go back to main "Settings" page
9. Scroll down bottom to find "Developer options" item
10. Turn on "USB Debugging" switch and hit "OK"
11. Unplug and re-plug the device
12. Dialog appears "Allow USB Debugging?"
13. Check "Always allow from this computer" and then hit "OK"

Running your App

Now, we can launch apps from Android Studio onto our device:

1. Select one of your projects and click "Run" from the toolbar.
2. In the "Choose Device" window that appears, select the "Choose a running device" radio
button, select the device, and click OK.

Running app on Emulator(AVD)

To run the app from Android studio, open one of your project's activity files and click Run icon
from the toolbar. Android studio installs the app on your AVD and starts it and if everything is
fine with your set-up and application, it will display following Emulator window −Once Gradle
finishes building, Android Studio should install the app on your connected device and start it.
Result :
EXPERIMENT - 2

Aim: : User Interface Design and Development


● Design a simple user interface using XML for an Android app.
● Implement navigation between multiple screens in both Android apps.

Procedure : Design a simple user interface using XML for an Android app.
Code for MainActivity.java
package com.example.akshay.mrcet;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText editName, editPassword;
TextView result;
Button buttonSubmit, buttonReset;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editName = (EditText) findViewById(R.id.editName);
editPassword = (EditText) findViewById(R.id.editPassword);
result = (TextView) findViewById(R.id.tvResult);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
buttonReset = (Button) findViewById(R.id.buttonReset);
/*
Submit Button
*/
buttonSubmit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
String name = editName.getText().toString();
String password = editPassword.getText().toString();
result.setText("Name:\t" + name + "\nPassword:\t" + password );
}
});
/*
Reset Button
*/
buttonReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editName.setText("");
editPassword.setText("");
result.setText("");
editName.requestFocus();
}
});
}
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#FFFF8D"
tools:context="com.example.akshay.mrcet.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="NAME"
android:textSize="20sp"
android:layout_margin="20dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="PASSWORD"
android:layout_marginTop="38dp"
android:layout_below="@+id/textView"
android:layout_alignLeft="@+id/textView"
android:layout_alignStart="@+id/textView" />
<EditText
android:id="@+id/editName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter Name"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="@+id/editPassword"
android:layout_alignStart="@+id/editPassword" />
<EditText
android:id="@+id/editPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Password"
android:inputType="textPassword"
android:layout_alignBottom="@+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="18dp"
android:layout_marginEnd="18dp" />
<Button
android:id="@+id/buttonSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/textView2"
android:layout_marginTop="20dp"
android:text="SUBMIT" />
<Button
android:id="@+id/buttonReset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RESET"
android:layout_alignBaseline="@+id/buttonSubmit"
android:layout_alignBottom="@+id/buttonSubmit"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="143dp"
android:textSize="30sp" />

Implement navigation between multiple screens in both Android apps.

MainActivity.java
package com.example.sms;
import android.os.Bundle;
import android.app.Activity;
import android.telephony.gsm.SmsManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt=(Button)findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
SmsManager sms=SmsManager.getDefault();
sms.sendTextMessage("5554", null, "hai", null, null);
}
});
}
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

MainActivity.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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="54dp"
android:layout_marginTop="166dp"
android:text="send" />
</RelativeLayout>
EXPERIMENT - 3

Aim: : Database Integration in Mobile Apps


● Create a SQLite database and perform basic CRUD operations in an Android app.
● Implement Core Data framework for data storage in an iOS app.

Procedure :
Database Table structure:
Table Name: Country

Step 1 : Creating Project


Create an android application project named “SQLiteDatabaseCRUDExample”.

Step 2: Creating Layout


Change res ->layout -> activity_main.xml as below:

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.java2blog.sqlitedatabasecrudexample.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Country"
android:id="@+id/btnSubmit"
/>
<ListView
android:id="@+id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnSubmit"
/>
</RelativeLayout>

You will see below screen in design view.

Step 3: Create Country class


Create a country class which will correspond to the Country table in SQLite database.

package com.java2blog.sqlitedatabasecrudexample;
/*
* This is our model class and it corresponds to Country table in database
*/

import static android.R.attr.name;

public class Country{

int id;
String countryName;
long population;
public Country() {
super();
}
public Country(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}

// constructor
public Country(String countryName, long population){
this.countryName = countryName;
this.population = population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}

Step 4: Create SQLiteDatabaseHandler for defining database operations.


We will create a class called SQLiteDatabaseHandler which will extend SQLiteOpenHelper and
override onCreate and OnUpdate methods. We will also add some CRUD methods.
addCountry
getCountry
getAllCountries
updateCountry
deleteCountry
delelteAllCountries
All above methods will interact with SQLite database and perform CRUD operations.

package com.java2blog.sqlitedatabasecrudexample;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class SQLiteDatabaseHandler extends SQLiteOpenHelper {

// All Static variables


// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "countryData";

// Country table name


private static final String TABLE_COUNTRY= "Country";

// Country Table Columns names


private static final String KEY_ID = "id";
private static final String COUNTRY_NAME = "CountryName";
private static final String POPULATION = "Population";

public SQLiteDatabaseHandler(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_COUNTRY_TABLE = "CREATE TABLE " + TABLE_COUNTRY + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + COUNTRY_NAME + " TEXT,"
+ COUNTRY_NAME + " LONG" + ")";
db.execSQL(CREATE_COUNTRY_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COUNTRY);
// Create tables again
onCreate(db);
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/

// Adding new country


void addCountry(Country country) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();


values.put(COUNTRY_NAME, country.getCountryName()); // Country Name
values.put(POPULATION, country.getPopulation()); // Country Population

// Inserting Row
db.insert(TABLE_COUNTRY, null, values);
db.close(); // Closing database connection
}

// Getting single country


Country getCountry(int id) {
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_COUNTRY, new String[] { KEY_ID,


COUNTRY_NAME, POPULATION }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Country country = new Country(Integer.parseInt(cursor.getString(0)),


cursor.getString(1), cursor.getLong(2));
// return country
return country;
}

// Getting All Countries


public List getAllCountries() {
List countryList = new ArrayList();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_COUNTRY;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list


if (cursor.moveToFirst()) {
do {
Country country = new Country();
country.setId(Integer.parseInt(cursor.getString(0)));
country.setCountryName(cursor.getString(1));
country.setPopulation(cursor.getLong(2));
// Adding country to list
countryList.add(country);
} while (cursor.moveToNext());
}

// return country list


return countryList;
}

// Updating single country


public int updateCountry(Country country) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COUNTRY_NAME, country.getCountryName());
values.put(POPULATION, country.getPopulation());

// updating row
return db.update(TABLE_COUNTRY, values, KEY_ID + " = ?",
new String[] { String.valueOf(country.getId()) });
}

// Deleting single country


public void deleteCountry(Country country) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_COUNTRY, KEY_ID + " = ?",
new String[] { String.valueOf(country.getId()) });
db.close();
}

// Deleting all countries


public void deleteAllCountries() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_COUNTRY,null,null);
db.close();
}

// Getting countries Count


public int getCountriesCount() {
String countQuery = "SELECT * FROM " + TABLE_COUNTRY;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}
}

Step 5: Creating layout for Row


As We have declared a ListView widget in activity_main.xml. Now we need to provide a layout
for individual rows.
Go to res -> layout
right click on layout
Click on New -> File.
Create a file named “row_item.xml” and paste below code in row_item.xml.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="30dp"
android:textColor="#1E90FF"
android:id="@+id/textViewId"
android:layout_row="0"
android:layout_column="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:textColor="#4B0082"
android:layout_below="@+id/textViewId"
android:id="@+id/textViewCountry"
android:layout_row="1"
android:layout_column="1" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginLeft="10dp"
android:textSize="20dp"
android:textColor="#4B0082"
android:layout_below="@+id/textViewCountry"
android:id="@+id/textViewPopulation"
android:layout_row="1"
android:layout_column="2" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="100dp"
android:layout_marginTop="30dp"
android:id="@+id/edit"
android:text="Edit"
android:layout_toRightOf="@+id/textViewId"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnWeight="1"
android:layout_marginRight="10dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="10dp"
android:id="@+id/delete"
android:text="Delete"
android:layout_toRightOf="@+id/edit"
/>
</RelativeLayout>

Step 6: Creating ArrayAdapter for ListView


Before creating MainActivity, we need to create a CustomCountryList class for a custom
ListView row.

package com.java2blog.sqlitedatabasecrudexample;

import android.app.Activity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;

public class CustomCountryList extends BaseAdapter {


private Activity context;
ArrayList countries;
private PopupWindow pwindo;
SQLiteDatabaseHandler db;
BaseAdapter ba;

public CustomCountryList(Activity context, ArrayList countries,SQLiteDatabaseHandler db)


{
this.context = context;
this.countries=countries;
this.db=db;
}

public static class ViewHolder


{
TextView textViewId;
TextView textViewCountry;
TextView textViewPopulation;
Button editButton;
Button deleteButton;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = context.getLayoutInflater();
ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
row = inflater.inflate(R.layout.row_item, null, true);

vh.textViewId = (TextView) row.findViewById(R.id.textViewId);


vh.textViewCountry = (TextView) row.findViewById(R.id.textViewCountry);
vh.textViewPopulation = (TextView)
row.findViewById(R.id.textViewPopulation);
vh.editButton = (Button) row.findViewById(R.id.edit);
vh.deleteButton = (Button) row.findViewById(R.id.delete);

// store the holder with the view.


row.setTag(vh);
} else {

vh = (ViewHolder) convertView.getTag();

vh.textViewCountry.setText(countries.get(position).getCountryName());
vh.textViewId.setText("" + countries.get(position).getId());
vh.textViewPopulation.setText("" + countries.get(position).getPopulation());
final int positionPopup = position;
vh.editButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

Log.d("Save: ", "" + positionPopup);


editPopup(positionPopup);

}
});
vh.deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("Last Index", "" + positionPopup);
// Integer index = (Integer) view.getTag();
db.deleteCountry(countries.get(positionPopup));

// countries.remove(index.intValue());
countries = (ArrayList) db.getAllCountries();
Log.d("Country size", "" + countries.size());
notifyDataSetChanged();
}
});
return row;
}

public long getItemId(int position) {


return position;
}

public Object getItem(int position) {


return position;
}

public int getCount() {


return countries.size();
}

public void editPopup(final int positionPopup)


{
LayoutInflater inflater = context.getLayoutInflater();
View layout = inflater.inflate(R.layout.edit_popup,
(ViewGroup) context.findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 600, 670, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);
countryEdit.setText(countries.get(positionPopup).getCountryName());
populationEdit.setText("" + countries.get(positionPopup).getPopulation());
Log.d("Name: ", "" + countries.get(positionPopup).getPopulation());
Button save = (Button) layout.findViewById(R.id.save_popup);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String countryStr = countryEdit.getText().toString();
String population = populationEdit.getText().toString();
Country country = countries.get(positionPopup);
country.setCountryName(countryStr);
country.setPopulation(Long.parseLong(population));
db.updateCountry(country);
countries = (ArrayList) db.getAllCountries();
notifyDataSetChanged();
for (Country country1 : countries) {
String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + "
,Population: " + country1.getPopulation();
// Writing Countries to log
Log.d("Name: ", log);
}
pwindo.dismiss();
}
});
}
}

This class is used to populate data for ListVIew. the getView method is called for drawing each
row. When you click on edit, you will see a popup to edit country Name and population. If you
click on delete, the country will be deleted from listview and SQLite database.

Step 7: Creating MainActivity


Change src/main/packageName/MainActivity.java as below:

package com.java2blog.sqlitedatabasecrudexample;

import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

ArrayList countries;
SQLiteDatabaseHandler db;
Button btnSubmit;
PopupWindow pwindo;
Activity activity;
ListView listView;
CustomCountryList customCountryList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity=this;
db= new SQLiteDatabaseHandler(this);
listView = (ListView) findViewById(android.R.id.list);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addPopUp();
}
});
Log.d("MainActivity: ", "Before reading mainactivity");
countries = (ArrayList) db.getAllCountries();

for (Country country : countries) {


String log = "Id: " + country.getId() + " ,Name: " + country.getCountryName() + "
,Population: " + country.getPopulation();
// Writing Countries to log
Log.d("Name: ", log);
}

CustomCountryList customCountryList = new CustomCountryList(this, countries, db);


listView.setAdapter(customCountryList);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long l) {
Toast.makeText(getApplicationContext(), "You Selected " +
countries.get(position).getCountryName() + " as Country", Toast.LENGTH_SHORT).show();
}
});
}

public void addPopUp() {


LayoutInflater inflater = activity.getLayoutInflater();
View layout = inflater.inflate(R.layout.edit_popup,
(ViewGroup) activity.findViewById(R.id.popup_element));
pwindo = new PopupWindow(layout, 600, 670, true);
pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
final EditText countryEdit = (EditText) layout.findViewById(R.id.editTextCountry);
final EditText populationEdit = (EditText) layout.findViewById(R.id.editTextPopulation);

Button save = (Button) layout.findViewById(R.id.save_popup);


save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String countryStr = countryEdit.getText().toString();
String population = populationEdit.getText().toString();
Country country = new Country(countryStr, Long.parseLong(population));
db.addCountry(country);
if(customCountryList==null)
{
customCountryList = new CustomCountryList(activity, countries, db);
listView.setAdapter(customCountryList);
}
customCountryList.countries = (ArrayList) db.getAllCountries();
((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
for (Country country1 : countries) {
String log = "Id: " + country1.getId() + " ,Name: " + country1.getCountryName() + "
,Population: " + country1.getPopulation();
// Writing Countries to log
Log.d("Name: ", log);
}
pwindo.dismiss();
}
});
}
}
When you click on the “Add Country” button, you will get a popup.You put Country name and
population and Country will be added to the list.

Step 8: Running the app


When you run the app, you will get below screen:

Click on the “Add Country” button and you will get the screen below. I have put Country Name
as India and Population as 10000.
When you click on save, India will be saved to the database. You can similarly add China,
Bhutan, and Nepal. You will get the screen below.

Let’s edit the population of China to 20000 to 30000.


When you click on save, China’s population will be changed to 30000. Let’s delete Bhutan from
the list, click on delete corresponding to Bhutan row. When you click on delete, you will get
below screen.
EXPERIMENT - 5

Aim: : Location-Based Services and Mapping


● Implement location tracking and display user location on a map in an Android app using
Google Maps API.
● Integrate MapKit framework in an iOS app to show user location and add annotations
on the map.

Procedure :
First, get Google maps API key from this by following instructions from their page. After getting
the key and enabling billing, you have to enable maps API with any additional APIs you might
need like Places API.

Create your project from Android Studio. Navigate to gradle.properties and add this line at the
end, ensure you have added your API key.

# Project-wide Gradle settings.


# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
#
http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official

ApiKeyMap="Insert Google Maps Key Here"

Open build.gradle(Module: app) file and these dependencies.

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.computingforgeeks.trucksend"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
buildConfigField 'String', "ApiKeyMap", ApiKeyMap
resValue 'string', "api_key_map", ApiKeyMap
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
'proguard-rules.pro'
buildConfigField 'String', "ApiKeyMap", ApiKeyMap
resValue 'string', "api_key_map", ApiKeyMap
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

implementation 'com.google.android.material:material:1.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.android.gms:play-services-maps:17.0.0'

implementation "com.karumi:dexter:5.0.0"

testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

Click on Sync Now at the top right to sync the dependencies.

Open your manifest file and add the following:

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.computingforgeeks.trucksend">

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


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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/api_key_map" />
</application>

</manifest>

Open your activity and start adding the required functions:

private lateinit var googleMap: GoogleMap


private lateinit var fusedLocationProviderClient: FusedLocationProviderClient

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)

val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as


SupportMapFragment?
mapFragment!!.getMapAsync(this)
fusedLocationProviderClient = FusedLocationProviderClient(this)
}

We initiate the Google map and we use the FusedLocationProviderClient to fetch the user’s
current location or last known location. Note that my activity will now extend the
onMapReady(). This is necessary so that the activity knows when Google maps is ready to
display.

We have to ask the user for permission to access their location. We will use the Dexter
permissions library to do this. First, we check if the user has given permission to the location.

private fun isPermissionGiven(): Boolean{


return ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
}

If permission is not granted we call the method givePermission to ask for permission.

private fun givePermission() {


Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(this)
.check()
}

After permissions have been granted, call the getCurrentLocation function that uses the
FusedLocationProviderClient to fetch the current user location or last known location. We use
locationRequest to refresh the current user location at some interval for high accuracy so that
we are always updated.

private fun getCurrentLocation() {

val locationRequest = LocationRequest()


locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = (10 * 1000).toLong()
locationRequest.fastestInterval = 2000

val builder = LocationSettingsRequest.Builder()


builder.addLocationRequest(locationRequest)
val locationSettingsRequest = builder.build()

val result =
LocationServices.getSettingsClient(this).checkLocationSettings(locationSettingsRequest)
result.addOnCompleteListener { task ->
try {
val response = task.getResult(ApiException::class.java)
if (response!!.locationSettingsStates.isLocationPresent){
getLastLocation()
}
} catch (exception: ApiException) {
when (exception.statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
val resolvable = exception as ResolvableApiException
resolvable.startResolutionForResult(this, REQUEST_CHECK_SETTINGS)
} catch (e: IntentSender.SendIntentException) {
} catch (e: ClassCastException) {
}

LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> { }
}
}
}
}

Geocoder Bonus

As a bonus, I have added a Gecoder method to try getting the address for the location given! I
have also added a custom pin marker.

private fun getLastLocation() {


fusedLocationProviderClient.lastLocation
.addOnCompleteListener(this) { task ->
if (task.isSuccessful && task.result != null) {
val mLastLocation = task.result
var address = "No known address"

val gcd = Geocoder(this, Locale.getDefault())


val addresses: List<Address>
try {
addresses = gcd.getFromLocation(mLastLocation!!.latitude,
mLastLocation.longitude, 1)
if (addresses.isNotEmpty()) {
address = addresses[0].getAddressLine(0)
}
} catch (e: IOException) {
e.printStackTrace()
}

val icon =
BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.resources,
R.drawable.ic_pickup))
googleMap.addMarker(
MarkerOptions()
.position(LatLng(mLastLocation!!.latitude, mLastLocation.longitude))
.title("Current Location")
.snippet(address)
.icon(icon)
)

val cameraPosition = CameraPosition.Builder()


.target(LatLng(mLastLocation.latitude, mLastLocation.longitude))
.zoom(17f)
.build()

googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
} else {
Toast.makeText(this, "No current location found", Toast.LENGTH_LONG).show()
}
}
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

when (requestCode) {
REQUEST_CHECK_SETTINGS -> {
if (resultCode == Activity.RESULT_OK) {
getCurrentLocation()
}
}
}
super.onActivityResult(requestCode, resultCode, data)

The final activity looks like this:

package com.computingforgeeks.trucksend

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.core.app.ActivityCompat
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.common.api.ResolvableApiException
import com.google.android.gms.location.*
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.karumi.dexter.Dexter
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.PermissionDeniedResponse
import com.karumi.dexter.listener.PermissionGrantedResponse
import com.karumi.dexter.listener.PermissionRequest
import com.karumi.dexter.listener.single.PermissionListener

import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException
import java.util.*

class MainActivity : AppCompatActivity(), OnMapReadyCallback, PermissionListener {

companion object {
const val REQUEST_CHECK_SETTINGS = 43
}

private lateinit var googleMap: GoogleMap


private lateinit var fusedLocationProviderClient: FusedLocationProviderClient

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)

val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as


SupportMapFragment?
mapFragment!!.getMapAsync(this)
fusedLocationProviderClient = FusedLocationProviderClient(this)

override fun onMapReady(map: GoogleMap?) {


googleMap = map?: return
if (isPermissionGiven()){
googleMap.isMyLocationEnabled = true
googleMap.uiSettings.isMyLocationButtonEnabled = true
googleMap.uiSettings.isZoomControlsEnabled = true
getCurrentLocation()
} else {
givePermission()
}
}

private fun isPermissionGiven(): Boolean{


return ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED
}

private fun givePermission() {


Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(this)
.check()
}

override fun onPermissionGranted(response: PermissionGrantedResponse?) {


getCurrentLocation()
}

override fun onPermissionRationaleShouldBeShown(


permission: PermissionRequest?,
token: PermissionToken?
){
token!!.continuePermissionRequest()
}

override fun onPermissionDenied(response: PermissionDeniedResponse?) {


Toast.makeText(this, "Permission required for showing location",
Toast.LENGTH_LONG).show()
finish()
}

private fun getCurrentLocation() {

val locationRequest = LocationRequest()


locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = (10 * 1000).toLong()
locationRequest.fastestInterval = 2000
val builder = LocationSettingsRequest.Builder()
builder.addLocationRequest(locationRequest)
val locationSettingsRequest = builder.build()

val result =
LocationServices.getSettingsClient(this).checkLocationSettings(locationSettingsRequest)
result.addOnCompleteListener { task ->
try {
val response = task.getResult(ApiException::class.java)
if (response!!.locationSettingsStates.isLocationPresent){
getLastLocation()
}
} catch (exception: ApiException) {
when (exception.statusCode) {
LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> try {
val resolvable = exception as ResolvableApiException
resolvable.startResolutionForResult(this, REQUEST_CHECK_SETTINGS)
} catch (e: IntentSender.SendIntentException) {
} catch (e: ClassCastException) {
}

LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> { }
}
}
}
}

private fun getLastLocation() {


fusedLocationProviderClient.lastLocation
.addOnCompleteListener(this) { task ->
if (task.isSuccessful && task.result != null) {
val mLastLocation = task.result

var address = "No known address"

val gcd = Geocoder(this, Locale.getDefault())


val addresses: List<Address>
try {
addresses = gcd.getFromLocation(mLastLocation!!.latitude,
mLastLocation.longitude, 1)
if (addresses.isNotEmpty()) {
address = addresses[0].getAddressLine(0)
}
} catch (e: IOException) {
e.printStackTrace()
}

val icon =
BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.resources,
R.drawable.ic_pickup))
googleMap.addMarker(
MarkerOptions()
.position(LatLng(mLastLocation!!.latitude, mLastLocation.longitude))
.title("Current Location")
.snippet(address)
.icon(icon)
)

val cameraPosition = CameraPosition.Builder()


.target(LatLng(mLastLocation.latitude, mLastLocation.longitude))
.zoom(17f)
.build()

googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
} else {
Toast.makeText(this, "No current location found", Toast.LENGTH_LONG).show()
}
}
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

when (requestCode) {
REQUEST_CHECK_SETTINGS -> {
if (resultCode == Activity.RESULT_OK) {
getCurrentLocation()
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {


menuInflater.inflate(R.menu.menu_main, menu)
return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {


return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
}
Now run app to see your current location.
EXPERIMENT - 6

Aim: : Cross-Platform App Development with React Native or Flutter


● Develop a simple mobile app using React Native, utilizing components and navigation.
● Create a mobile app using Flutter, implementing UI elements and handling user input.

Objective:
1. To create a mobile app using React Native that demonstrates the use of components and
navigation.
2. To develop a mobile app using Flutter that showcases UI elements and user input handling.

Materials Required:
- Computer with a code editor installed (e.g., Visual Studio Code, IntelliJ IDEA)
- Node.js and npm installed (for React Native)
- Flutter SDK installed
- Android Studio or Xcode for emulator/simulator setup
- Basic understanding of JavaScript (for React Native) and Dart (for Flutter)

React Native App Development

Step-by-Step Procedure:

Step 1: Setting Up React Native Project

Step 2: Creating Components


Create and customize components for the app, e.g., `HomeScreen.js`, `AboutScreen.js`, etc.,
within the `src` directory.

Component (`HomeScreen.js`):
Step 3: Implementing Navigation
Install React Navigation and set up navigation between screens.

Navigation Setup (`App.js`):

Step 4: Running the React Native App


Flutter App Development

Step-by-Step Procedure:

Step 1: Creating a New Flutter Project

Step 2: Designing UI Elements


Edit `lib/main.dart` to design the app's UI and functionality using Flutter widgets.

UI Implementation (`lib/main.dart`):
Step 3: Handling User Input
Implement user input handling for interactive elements like buttons and forms.

Input Handling (`lib/main.dart`):

Step 4: Running the Flutter App


Connect an Android/iOS device or start a simulator/emulator, then run the app:
EXPERIMENT - 7

Aim: : Testing and Debugging


● Perform unit testing on key functionalities of an Android app using JUnit and
Android Testing frameworks.
● Debug and test an iOS app using Xcode debugger and XCTest framework.

Procedure :
Unit testing is done to ensure that developers write high-quality and errorless code. It is advised
to write Unit tests before writing the actual app, you will write tests beforehand and the actual
code will have to adhere to the design guidelines laid out by the test. In this article, we are using
JUnit to test our code. JUnit is a “Unit Testing” framework for Java Applications which is
already included by default in android studio. It is an automation framework for Unit as well as
UI Testing. It contains annotations such as @Test, @Before, @After, etc. Here we will be using
only @Test annotation to keep the article easy to understand. Note that we are going to
implement this project using the Kotlin language.

Step by Step Implementation

Step 1: Create a new Project

Step 2: Add dependency to the build.gradle file and click “sync now”

Step 3: Working with the RegistrationUtil.kt file

Create a new Kotlin file RegistrationUtil and choose its type as an object. Since this is a
singleton we do not need to create an object of it while using it in other classes. It has a function
called validRegistrationInput which requires three arguments: username, password, and confirm
password. We will be testing this function with different sets of inputs with the following test
cases.

● Username, password, confirm password should not be empty.


● Passwords must contain at least two digits.
● Password matches the confirmed password.
● Username must not be taken.

Step 4: Create a test class

In order to create a test class of RegistrationUtil right-click on RegistrationUtil then click


generate and then select the test. A dialog will open, from the dialog choose Testing library as
JUnit4 and keep the class name as default that is RegistrationUtilTest, and click ok. After that,
another dialog will open to choose the destination directory, choose the one which has
..app\src\test\. because our test class does not require any context from the application. Below is
the screenshot to guide you to create the test class.
Step 5: Working with RegistrationUtilTest.kt file

Go to the RegistrationUtilTest.kt file and write the following code. Comments are added inside
the code to understand the code in more detail.
Step 6: Run the Test cases

To run the test case click on the little run icon near the class name and then select Run
RegistrationUtilTest. If all the test cases pass you will get a green tick in the Run console. In our
case, all tests have passed.
EXPERIMENT - 8

Aim: : App Deployment and Performance Optimization


● Package and deploy an Android app to Google Play Store.
● Package and deploy an iOS app to the App Store.
● Optimize app performance by analyzing and improving resource usage, network
efficiency, and responsiveness.

Procedure :
Building a dream app that reflects your idea, but, what next? Building a mobile app simply
means you’re half done. But one must be concerned about the launch of the application. It’s very
confusing because as a beginner, they are not friendly with the google play store guidelines. So
let’s understand the step by step process to publish your android app on google play store.

Step 1: Make a Developer Account

A developer account must be needed to upload an app on the Google Play Store, and the process
is very simple. Just go through Google Play Store and do as instructed.

The account can be created in four simple steps:

● Sign-In with Your Google Account


● Accept Terms
● Pay Registration Fee of $25.
● Complete Your Account Details

Step 2: After you completed step 1 you will be redirected to this page where you have to click
on the CREATE APPLICATION button.
Once you click on it a pop up will be shown like this where you have to choose your Default
language and Title of your app. Then click on the CREATE button.

Step 3: Store listing

After you completed step 2 you will be redirected to this page where you have to provide the
Short description and Full description of your App.

Then you scroll down the page and now you have to add the Hi-res icon of your app.
Then you have to provide the Screenshots of your app.

The next thing you have to provide is the Feature Graphic of your app. Note that this graphic is
then used everywhere your app is featured on Google Play.

Then come to Categorization part where you have to provide your Application type and Category
of your app.
Then come to the Contact details part where you have to provide your Website(if any), email,
and Phone of yours.

And finally when you click on SAVE DRAFT button you can see that Store listing tab is now
become turned to green and you are done for the Store listing.

Step 4: App release

After completing step 3 go to App releases then scroll down to Production track and click on
MANAGE button.
After redirecting to the next page click on the CREATE RELEASE button.

After that on the next page, you have to upload your APK file in Android App Bundles and
APKs to add section.

After that simply click on the SAVE button.

Step 5: Content rating


Now after completing step 4 go to Content rating and click on CONTINUE button.

After that fill your email address as well as confirm the email address.

And then Select your app category.

After selecting your app category make sure that you read all of these and answer them correctly.
And after answering them correctly don’t forget to click on SAVE QUESTIONNAIRE button.

Once you saved all those things then click on CALCULATE RATING button.

When you redirected to another page scroll down and click on APPLY RATING button. And you
are done for Content rating section. Don’t forget to notice that Content rating section is now
become turned to green.

Step 6: Pricing & distribution

Then go to the Pricing & distribution section. Then select the country in which you want to
available your app.
Then go down and down and check out the Content guidelines and US export laws section by
marking them tick mark. And click on the SAVE DRAFT button. Don’t forget to notice that
Pricing & distribution section is now become turned to green tick.

Step 7: App content

Then come to the App content section. And in the Privacy policy section click on the Start
button.

And then provide a valid Privacy policy URL. Note that google will check this.
Then go back and continue further steps by clicking start button in Ads section.

Then select does your app contain ads or not? And click on SAVE button.

Then again go back and continue further steps by clicking start button in Target audience and
content section.

In the next page select the Target age group and scroll down and click on the Next button.
Then check the Appeal to children section. And click on the Next button.

On the next page click on the Save button and you are done for App content section.

Step 8: App releases

Again go back to the App releases section. And in the Production track click on the EDIT
RELEASE button.
Then on the next page go down and down and click on the REVIEW button.

And finally, on the next page click on the START ROLLOUT TO PRODUCTION button to send
your app to review. And you are finally done.

After usually 4 to 5 days they will review your app and let you know to either approve or reject
your app.
EXPERIMENT - 9

Aim: : : Augmented Reality (AR) Integration


● Integrate AR features into an Android app using ARCore or ARKit for iOS

Procedure :
Setting Up the Project:
● Create a new Android project in Android Studio.
● Ensure the project includes necessary dependencies for ARCore (Google's platform for
building AR experiences on Android) and Sceneform (a 3D framework for AR
development).

Designing the User Interface (UI):


● Create a simple UI for selecting furniture items to place in the AR scene.
● Add buttons or a list view for choosing different furniture models.

Implementing AR Scene:
● Set up the AR scene using ARCore.
● Initialize the AR session, configure the AR fragment or view, and handle ARCore
lifecycle.

Integrating 3D Furniture Models:


● Import 3D furniture models into your project. Sceneform supports models in .sfb
(Sceneform Binary) format.
● Store references to these models in your app for dynamic loading.

Placing Furniture in AR:


● Use gestures or UI interaction to place selected furniture items in the AR scene.
● Implement logic to anchor furniture models to real-world surfaces detected by ARCore.

Adding Video Nodes:


● Integrate video nodes to enhance the AR experience with additional visual elements.
● Video nodes can be used for displaying instructions, additional information, or
animations related to the furniture

Code :
build.gradle -
proguard-rules.pro
build.gradle

gradlew
settings.gradle

Output :

You might also like