0% found this document useful (0 votes)
30 views119 pages

Ilovepdf Merged

Uploaded by

doshijainil5
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)
30 views119 pages

Ilovepdf Merged

Uploaded by

doshijainil5
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/ 119

4351604 Mobile Application Development 226370316018

PRACTICAL: -23
Aim: -Integrate Google maps API to your Android application and find the
distance of any nearby location from your current location and display it.
4351604 Mobile Application Development 226370316018

PRACTICAL: -23
Aim: -Integrate Google maps API to your Android application and find the
distance of any nearby location from your current location and display it.

activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.mapexample.MapsActivity" />

build.gradel

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.google.android.gms:play-services-maps:11.8.0'
compile 'com.google.android.gms:play-services-location:11.8.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

}
4351604 Mobile Application Development 226370316018

MapsActivity.java

package example.com.mapexample;

import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.api.GoogleApiClient;
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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationServices;

import android.location.Location;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,


LocationListener,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener{

private GoogleMapmMap;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleApiClientmGoogleApiClient;
LocationRequestmLocationRequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

SupportMapFragmentmapFragment = (SupportMapFragment) getSupportFragmentManager()


.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

@Override
public void onMapReady(GoogleMapgoogleMap) {
mMap = googleMap;

if (android.os.Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
4351604 Mobile Application Development 226370316018

buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}

}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}

@Override
public void onConnected(Bundle bundle) {

mLocationRequest = new LocationRequest();


mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLnglatLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptionsmarkerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mCurrLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onConnectionFailed(ConnectionResultconnectionResult) {

}
4351604 Mobile Application Development 226370316018

AndroidManifest.xm

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


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

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.com.mapexample">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_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">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
</application>

</manifest>

OUTPUT
4351604 Mobile Application Development 226370316018
4351604 Mobile Application Development 226370316018
4341604 MAD 226370316018

Practical – 18
Aim :- Create an application to retrieve data from the Firebase Database and
display it in the RecyclerView.
4341604 MAD 226370316018

Practical – 18
Aim :- Create an application to retrieve data from the Firebase Database and
display it in the RecyclerView.

 Activity_main.xml

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

<androidx.constraintlayout.widget.ConstraintLayout

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

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<androidx.recyclerview.widget.RecyclerView

android:id="@+id/recycler1"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="#65E4A6"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 person.xml

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

<androidx.cardview.widget.CardView

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

android:layout_marginHorizontal="10dp"
4341604 MAD 226370316018

android:layout_marginTop="10dp"

android:layout_marginBottom="20dp"

android:scrollbars="vertical"

app:cardCornerRadius="20dp">

<androidx.constraintlayout.widget.ConstraintLayout

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/textView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="16dp"

android:layout_marginTop="16dp"

android:text="First name: "

android:textStyle="bold"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

<TextView

android:id="@+id/firstname"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_marginStart="16dp"

android:layout_marginTop="16dp"

android:layout_marginEnd="16dp"

android:text="TextView"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toEndOf="@+id/textView1"

app:layout_constraintTop_toTopOf="parent" />

<TextView
4341604 MAD 226370316018

android:id="@+id/textView2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="16dp"

android:layout_marginTop="16dp"

android:text="Last name:"

android:textStyle="bold"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/textView1" />

<TextView

android:id="@+id/lastname"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_marginStart="16dp"

android:layout_marginTop="16dp"

android:layout_marginEnd="16dp"

android:text="TextView"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toEndOf="@+id/textView2"

app:layout_constraintTop_toBottomOf="@+id/firstname" />

<TextView

android:id="@+id/textView3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="16dp"

android:layout_marginTop="16dp"

android:layout_marginBottom="16dp"

android:text="Age"

android:textStyle="bold"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/textView2" />
4341604 MAD 226370316018

<TextView

android:id="@+id/age"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_marginStart="16dp"

android:layout_marginTop="16dp"

android:layout_marginEnd="16dp"

android:layout_marginBottom="16dp"

android:text="TextView"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toEndOf="@+id/textView3"

app:layout_constraintTop_toBottomOf="@+id/lastname" />

</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

 person.java

// Your package name can be different depending

// on your project name

package com.example.recyclerview;

public class person

// Variable to store data corresponding

// to firstname keyword in database

private String firstname;

// Variable to store data corresponding

// to lastname keyword in database

private String lastname;


4341604 MAD 226370316018

// Variable to store data corresponding

// to age keyword in database

private String age;

// Mandatory empty constructor

// for use of FirebaseUI

public person() {}

// Getter and setter method

public String getFirstname()

return firstname;

public void setFirstname(String firstname)

this.firstname = firstname;

public String getLastname()

return lastname;

public void setLastname(String lastname)

this.lastname = lastname;

public String getAge()

return age;

public void setAge(String age)

this.age = age;

}
4341604 MAD 226370316018

 personAdapter.java

package com.example.recyclerview;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.TextView;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;

import com.firebase.ui.database.FirebaseRecyclerOptions;

// FirebaseRecyclerAdapter is a class provided by

// FirebaseUI. it provides functions to bind, adapt and show

// database contents in a Recycler View

public class personAdapter extends FirebaseRecyclerAdapter<

person, personAdapter.personsViewholder> {

public personAdapter(

@NonNullFirebaseRecyclerOptions<person> options)

super(options);

// Function to bind the view in Card view(here

// "person.xml") iwth data in

// model class(here "person.class")

@Override

protected void

onBindViewHolder(@NonNullpersonsViewholder holder,

int position, @NonNull person model)

{
4341604 MAD 226370316018

// Add firstname from model class (here

// "person.class")to appropriate view in Card

// view (here "person.xml")

holder.firstname.setText(model.getFirstname());

// Add lastname from model class (here

// "person.class")to appropriate view in Card

// view (here "person.xml")

holder.lastname.setText(model.getLastname());

// Add age from model class (here

// "person.class")to appropriate view in Card

// view (here "person.xml")

holder.age.setText(model.getAge());

// Function to tell the class about the Card view (here

// "person.xml")in

// which the data will be shown

@NonNull

@Override

public personsViewholder

onCreateViewHolder(@NonNullViewGroup parent,

intviewType)

View view

= LayoutInflater.from(parent.getContext())

.inflate(R.layout.person, parent, false);

return new personAdapter.personsViewholder(view);

// Sub Class to create references of the views in Crad

// view (here "person.xml")


4341604 MAD 226370316018

class personsViewholder

extends RecyclerView.ViewHolder {

TextViewfirstname, lastname, age;

public personsViewholder(@NonNull View itemView)

super(itemView);

firstname

= itemView.findViewById(R.id.firstname);

lastname = itemView.findViewById(R.id.lastname);

age = itemView.findViewById(R.id.age);

 MainActivity.java

package com.example.recyclerview;

import androidx.appcompat.app.AppCompatActivity;

import androidx.recyclerview.widget.LinearLayoutManager;

import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import com.firebase.ui.database.FirebaseRecyclerOptions;

import com.google.firebase.database.DatabaseReference;

import com.google.firebase.database.FirebaseDatabase;

import com.google.firebase.database.Query;

public class MainActivity extends AppCompatActivity {

private RecyclerViewrecyclerView;

personAdapter

adapter; // Create Object of the Adapter class

DatabaseReferencembase; // Create object of the

// Firebase Realtime Database


4341604 MAD 226370316018

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Create a instance of the database and get

// its reference

mbase

= FirebaseDatabase.getInstance().getReference();

recyclerView = findViewById(R.id.recycler1);

// To display the Recycler view linearly

recyclerView.setLayoutManager(

new LinearLayoutManager(this));

// It is a class provide by the FirebaseUI to make a

// query in the database to fetch appropriate data

FirebaseRecyclerOptions<person> options

= new FirebaseRecyclerOptions.Builder<person>()

.setQuery(mbase, person.class)

.build();

// Connecting object of required Adapter class to

// the Adapter class itself

adapter = new personAdapter(options);

// Connecting Adapter class with the Recycler view*/

recyclerView.setAdapter(adapter);

// Function to tell the app to start getting

// data from database on starting of the activity

@Override protected void onStart()


4341604 MAD 226370316018

super.onStart();

adapter.startListening();

// Function to tell the app to stop getting

// data from database on stopping of the activity

@Override protected void onStop()

super.onStop();

adapter.stopListening();

 AndroidManifest.xml
“uses-permission android:name=”android.permission.INTERNET”

Database
4341604 MAD 226370316018
4341604 MAD 226370316018
4341604 MAD 226370316018
4341604 MAD 226370316018

Output
(4351604) Mobile Application Development 226370316018

Practical – 22
Aim :-Integrate Google maps API to your Android application and display your
current location in the app.
(4351604) Mobile Application Development 226370316018

Practical – 22
Aim :-Integrate Google maps API to your Android application and display your
current location in the app.

 Activity_main.xml

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

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

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/myMap"

android:name="com.google.android.gms.maps.SupportMapFragment"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity" />

 MainActivity.java

import android.Manifest;

import android.content.pm.PackageManager;

import android.location.Location;

import android.os.Bundle;

import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;

import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.location.FusedLocationProviderClient;

import com.google.android.gms.location.LocationServices;

import com.google.android.gms.maps.GoogleMap;

import com.google.android.gms.maps.OnMapReadyCallback;

import com.google.android.gms.maps.model.LatLng;

import com.google.android.gms.maps.model.MarkerOptions;

import com.google.android.gms.tasks.OnSuccessListener;

import com.google.android.gms.tasks.Task;

import androidx.annotation.NonNull;
(4351604) Mobile Application Development 226370316018

import androidx.core.app.ActivityCompat;

import androidx.fragment.app.FragmentActivity;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

Location currentLocation;

FusedLocationProviderClientfusedLocationProviderClient;

private static final int REQUEST_CODE = 101

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

fetchLocation();

private void fetchLocation() {

if (ActivityCompat.checkSelfPermission(

this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED&&ActivityCompat.checkSelfPermission(

this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},


REQUEST_CODE);

return;

Task<Location> task = fusedLocationProviderClient.getLastLocation();

task.addOnSuccessListener(new OnSuccessListener<Location>() {

@Override

public void onSuccess(Location location) {

if (location != null) {

currentLocation = location;

Toast.makeText(getApplicationContext(), currentLocation.getLatitude() + "" + currentLocation.getLongitude(),


Toast.LENGTH_SHORT).show();

SupportMapFragmentsupportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.myMap);

assert supportMapFragment != null;

supportMapFragment.getMapAsync(MainActivity.this);

}
(4351604) Mobile Application Development 226370316018

});

@Override

public void onMapReady(GoogleMapgoogleMap) {

LatLnglatLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());

MarkerOptionsmarkerOptions = new MarkerOptions().position(latLng).title("I am here!");

googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 5));

googleMap.addMarker(markerOptions);

@Override

public void onRequestPermissionsResult(intrequestCode, @NonNull String[] permissions, @NonNullint[]


grantResults) {

switch (requestCode) {

case REQUEST_CODE:

if (grantResults.length> 0 &&grantResults[0] == PackageManager.PERMISSION_GRANTED) {

fetchLocation();

break;

 strings.xml

<resources>

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

<string name="map_key" translatable="false">Enter your google API key here</string>

</resources>

 androidManifest.xml

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


(4351604) Mobile Application Development 226370316018

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">

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

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

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

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

<meta-data android:name="com.google.android.geo.API_KEY" android:value="@string/map_key"/>

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

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

</intent-filter>

</activity>

</application>

</manifest>
(4351604) Mobile Application Development 226370316018

Output
4341604 MAD 226370316018

Practical – 16
AIM = Create an application to Update and Delete data from the
SQLite database using SQLiteOpenHelper class.
4341604 MAD 226370316018

Practical – 16
AIM = Create an application to Update and Delete data from the
SQLite database using SQLiteOpenHelper class.

activity_main.xml

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

<LinearLayout

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity">

<!--Edit text to enter course name-->

<EditText

android:id="@+id/idEdtCourseName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter course Name" />

<!--edit text to enter course duration-->

<EditText

android:id="@+id/idEdtCourseDuration"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter Course Duration" />


4341604 MAD 226370316018

<!--edit text to display course tracks-->

<EditText

android:id="@+id/idEdtCourseTracks"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter Course Tracks" />

<!--edit text for course description-->

<EditText

android:id="@+id/idEdtCourseDescription"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter Course Description" />

<!--button for adding new course-->

<Button

android:id="@+id/idBtnAddCourse"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:text="Add Course"

android:textAllCaps="false" />

</LinearLayout>
4341604 MAD 226370316018

DBHandler.java

import android.content.ContentValues;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DBHandler extends SQLiteOpenHelper {

// creating a constant variables for our database.

// below variable is for our database name.

private static final String DB_NAME = "coursedb";

// below int is our database version

private static final int DB_VERSION = 1;

// below variable is for our table name.

private static final String TABLE_NAME = "mycourses";

// below variable is for our id column.

private static final String ID_COL = "id";

// below variable is for our course name column

private static final String NAME_COL = "name";

// below variable id for our course duration column.

private static final String DURATION_COL = "duration";

// below variable for our course description column.

private static final String DESCRIPTION_COL = "description";

// below variable is for our course tracks column.


4341604 MAD 226370316018

private static final String TRACKS_COL = "tracks";

// creating a constructor for our database handler.

public DBHandler(Context context) {

super(context, DB_NAME, null, DB_VERSION);

// below method is for creating a database by running a sqlite query

@Override

public void onCreate(SQLiteDatabase db) {

// on below line we are creating

// an sqlite query and we are

// setting our column names

// along with their data types.

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

+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "

+ NAME_COL + " TEXT,"

+ DURATION_COL + " TEXT,"

+ DESCRIPTION_COL + " TEXT,"

+ TRACKS_COL + " TEXT)";

// at last we are calling a exec sql

// method to execute above sql query

db.execSQL(query);

// this method is use to add new course to our sqlite database.

public void addNewCourse(String courseName, String courseDuration, String courseDescription, String


courseTracks) {

// on below line we are creating a variable for

// our sqlite database and calling writable method

// as we are writing data in our database.


4341604 MAD 226370316018

SQLiteDatabase db = this.getWritableDatabase();

// on below line we are creating a

// variable for content values.

ContentValues values = new ContentValues();

// on below line we are passing all values

// along with its key and value pair.

values.put(NAME_COL, courseName);

values.put(DURATION_COL, courseDuration);

values.put(DESCRIPTION_COL, courseDescription);

values.put(TRACKS_COL, courseTracks);

// after adding all values we are passing

// content values to our table.

db.insert(TABLE_NAME, null, values);

// at last we are closing our

// database after adding database.

db.close();

@Override

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

// this method is called to check if the table exists already.

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

onCreate(db);

}
4341604 MAD 226370316018

MainActivity.java

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

// creating variables for our edittext, button and dbhandler

private EditText courseNameEdt, courseTracksEdt, courseDurationEdt, courseDescriptionEdt;

private Button addCourseBtn;

private DBHandler dbHandler;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// initializing all our variables.

courseNameEdt = findViewById(R.id.idEdtCourseName);

courseTracksEdt = findViewById(R.id.idEdtCourseTracks);

courseDurationEdt = findViewById(R.id.idEdtCourseDuration);

courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);

addCourseBtn = findViewById(R.id.idBtnAddCourse);

// creating a new dbhandler class

// and passing our context to it.

dbHandler = new DBHandler(MainActivity.this);


4341604 MAD 226370316018

// below line is to add on click listener for our add course button.

addCourseBtn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// below line is to get data from all edit text fields.

String courseName = courseNameEdt.getText().toString();

String courseTracks = courseTracksEdt.getText().toString();

String courseDuration = courseDurationEdt.getText().toString();

String courseDescription = courseDescriptionEdt.getText().toString();

// validating if the text fields are empty or not.

if (courseName.isEmpty() && courseTracks.isEmpty() && courseDuration.isEmpty() &&


courseDescription.isEmpty()) {

Toast.makeText(MainActivity.this, "Please enter all the data..", Toast.LENGTH_SHORT).show();

return;

// on below line we are calling a method to add new

// course to sqlite data and pass all our values to it.

dbHandler.addNewCourse(courseName, courseDuration, courseDescription, courseTracks)

// after adding the data we are displaying a toast message.

Toast.makeText(MainActivity.this, "Course has been added.", Toast.LENGTH_SHORT).show();

courseNameEdt.setText("");

courseDurationEdt.setText("");

courseTracksEdt.setText("");

courseDescriptionEdt.setText("");

});

}
4341604 MAD 226370316018

OUTPUT

Insert data
4341604 MAD 226370316018

For update data in file


activity_update_course.xml

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

<LinearLayout

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".UpdateCourseActivity">

<!--Edit text to enter course name-->

<EditText

android:id="@+id/idEdtCourseName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter course Name" />

<!--edit text to enter course duration-->

<EditText

android:id="@+id/idEdtCourseDuration"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter Course Duration" />

<!--edit text to display course tracks-->

<EditText

android:id="@+id/idEdtCourseTracks"

android:layout_width="match_parent"
4341604 MAD 226370316018

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter Course Tracks" />

<!--edit text for course description-->

<EditText

android:id="@+id/idEdtCourseDescription"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:hint="Enter Course Description" />

<!--button for updating our course-->

<Button

android:id="@+id/idBtnUpdateCourse"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:text="Update Course"

android:textAllCaps="false" />

</LinearLayout>
4341604 MAD 226370316018

DBHandler.java

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;

public class DBHandler extends SQLiteOpenHelper {

// creating a constant variables for our database.

// below variable is for our database name.

private static final String DB_NAME = "coursedb";

// below int is our database version

private static final int DB_VERSION = 1;

// below variable is for our table name.

private static final String TABLE_NAME = "mycourses";

// below variable is for our id column.

private static final String ID_COL = "id";

// below variable is for our course name column

private static final String NAME_COL = "name";

// below variable id for our course duration column.

private static final String DURATION_COL = "duration";

// below variable for our course description column.

private static final String DESCRIPTION_COL = "description";


4341604 MAD 226370316018

// below variable is for our course tracks column.

private static final String TRACKS_COL = "tracks";

// creating a constructor for our database handler.

public DBHandler(Context context) {

super(context, DB_NAME, null, DB_VERSION);

// below method is for creating a database by running a sqlite query

@Override

public void onCreate(SQLiteDatabase db) {

// on below line we are creating

// an sqlite query and we are

// setting our column names

// along with their data types.

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

+ ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "

+ NAME_COL + " TEXT,"

+ DURATION_COL + " TEXT,"

+ DESCRIPTION_COL + " TEXT,"

+ TRACKS_COL + " TEXT)";

// at last we are calling a exec sql

// method to execute above sql query

db.execSQL(query);

// this method is use to add new course to our sqlite database.

public void addNewCourse(String courseName, String courseDuration, String courseDescription, String


courseTracks) {

// on below line we are creating a variable for


4341604 MAD 226370316018

// our sqlite database and calling writable method

// as we are writing data in our database.

SQLiteDatabase db = this.getWritableDatabase();

// on below line we are creating a

// variable for content values.

ContentValues values = new ContentValues();

// on below line we are passing all values

// along with its key and value pair.

values.put(NAME_COL, courseName);

values.put(DURATION_COL, courseDuration);

values.put(DESCRIPTION_COL, courseDescription);

values.put(TRACKS_COL, courseTracks);

// after adding all values we are passing

// content values to our table.

db.insert(TABLE_NAME, null, values);

// at last we are closing our

// database after adding database.

db.close();

// we have created a new method for reading all the courses.

public ArrayList<CourseModal> readCourses() {

// on below line we are creating a

// database for reading our database.

SQLiteDatabase db = this.getReadableDatabase();

// on below line we are creating a cursor with query to read data from database.

Cursor cursorCourses = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);


4341604 MAD 226370316018

// on below line we are creating a new array list.

ArrayList<CourseModal> courseModalArrayList = new ArrayList<>();

// moving our cursor to first position.

if (cursorCourses.moveToFirst()) {

do {

// on below line we are adding the data from cursor to our array list.

courseModalArrayList.add(new CourseModal(cursorCourses.getString(1),

cursorCourses.getString(4),

cursorCourses.getString(2),

cursorCourses.getString(3)));

} while (cursorCourses.moveToNext());

// moving our cursor to next.

// at last closing our cursor

// and returning our array list.

cursorCourses.close();

return courseModalArrayList;

// below is the method for updating our courses

public void updateCourse(String originalCourseName, String courseName, String courseDescription,

String courseTracks, String courseDuration) {

// calling a method to get writable database.

SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();

// on below line we are passing all values

// along with its key and value pair.

values.put(NAME_COL, courseName);

values.put(DURATION_COL, courseDuration);

values.put(DESCRIPTION_COL, courseDescription);
4341604 MAD 226370316018

values.put(TRACKS_COL, courseTracks);

// on below line we are calling a update method to update our database and passing our values.

// and we are comparing it with name of our course which is stored in original name variable.

db.update(TABLE_NAME, values, "name=?", new String[]{originalCourseName});

db.close();

@Override

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

// this method is called to check if the table exists already.

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

onCreate(db);

}
4341604 MAD 226370316018

Output
For update
4341604 MAD 226370316018

Practical – 20
AIM : - Perform insertion of data to MySQL database using PHP from
an Android application.
4341604 MAD 226370316018

Practical – 20
AIM : - Perform insertion of data to MySQL database using PHP from
an Android application.

Crud.php
<?php

$servername = "localhost";

// for testing the user name is root.

$username = "root";

// the password for testing is "blank"

$password = "";

// below is the name for our

// database which we have added.

$dbname = "id16310745_gfgdatabase";

// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// an array to display response

$response = array();

// on below line we are checking if the body provided by user contains

// this keys as course name,course description and course duration

if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){

// if above three parameters are present then we are extracting values

// from it and storing it in new variables.

$courseName = $_POST['courseName'];

$courseDuration = $_POST['courseDuration'];

$courseDescription = $_POST['courseDescription'];

// after that we are writing ansql query to

// add this data to our database.


4341604 MAD 226370316018

// on below line make sure to add your table name

// in previous article we have created our table name

// as courseDb and add all column headers to it except our id.

$stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`, `courseDescription`)


VALUES (?,?,?)");

$stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription);

// on below line we are checking if our sql query is executed successfully.

if($stmt->execute() == TRUE){

// if the script is executed successfully we are

// passing data to our response object

// with a success message.

$response['error'] = false;

$response['message'] = "course created successfully!";

} else{

// if we get any error we are passing error to our object.

$response['error'] = true;

$response['message'] = "failed\n ".$conn->error;

} else{

// this method is called when user

// donot enter sufficient parameters.

$response['error'] = true;

$response['message'] = "Insufficient parameters";

// at last we are printing our response which we get.

echo json_encode($response);

?>
4341604 MAD 226370316018

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

<LinearLayout

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity">

<!--Edit text for getting course Name-->

<EditText

android:id="@+id/idEdtCourseName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="20dp"

android:layout_marginEnd="10dp"

android:hint="Course Name"

android:importantForAutofill="no"

android:inputType="text" />

<!--Edittext for getting course Duration-->

<EditText

android:id="@+id/idEdtCourseDuration"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="20dp"

android:layout_marginEnd="10dp"

android:hint="Course Duration in min"

android:importantForAutofill="no"

android:inputType="time" />
4341604 MAD 226370316018

<!--Edittext for getting course Description-->

<EditText

android:id="@+id/idEdtCourseDescription"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="20dp"

android:layout_marginEnd="10dp"

android:hint="Course Description"

android:importantForAutofill="no"

android:inputType="text" />

<!--Button for adding your course to Firebase-->

<Button

android:id="@+id/idBtnSubmitCourse"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:text="Submit Course Details"

android:textAllCaps="false" />

</LinearLayout>
4341604 MAD 226370316018

MainActivity.java
import android.os.Bundle;

import android.text.TextUtils;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.StringRequest;

import com.android.volley.toolbox.Volley;

import org.json.JSONException;

import org.json.JSONObject;

import java.util.HashMap;

import java.util.Map;

public class MainActivity extends AppCompatActivity {

// creating variables for our edit text

private EditTextcourseNameEdt, courseDurationEdt, courseDescriptionEdt;

// creating variable for button

private Button submitCourseBtn;

// creating a strings for storing our values from edittext fields.

private String courseName, courseDuration, courseDescription;


4341604 MAD 226370316018

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// initializing our edittext and buttons

courseNameEdt = findViewById(R.id.idEdtCourseName);

courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);

courseDurationEdt = findViewById(R.id.idEdtCourseDuration);

submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);

submitCourseBtn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// getting data from edittext fields.

courseName = courseNameEdt.getText().toString();

courseDescription = courseDescriptionEdt.getText().toString();

courseDuration = courseDurationEdt.getText().toString();

// validating the text fields if empty or not.

if (TextUtils.isEmpty(courseName)) {

courseNameEdt.setError("Please enter Course Name");

} else if (TextUtils.isEmpty(courseDescription)) {

courseDescriptionEdt.setError("Please enter Course Description");

} else if (TextUtils.isEmpty(courseDuration)) {

courseDurationEdt.setError("Please enter Course Duration");

} else {

// calling method to add data to Firebase Firestore.

addDataToDatabase(courseName, courseDescription, courseDuration);

});
4341604 MAD 226370316018

private void addDataToDatabase(String courseName, String courseDescription, String courseDuration) {

// url to post our data

String url = "http://localhost/courseApp/addCourses.php";

// creating a new variable for our request queue

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

// on below line we are calling a string

// request method to post the data to our API

// in this we are calling a post method.

StringRequest request = new StringRequest(Request.Method.POST, url, new


com.android.volley.Response.Listener<String>() {

@Override

public void onResponse(String response) {

Log.e("TAG", "RESPONSE IS " + response);

try {

JSONObjectjsonObject = new JSONObject(response);

// on below line we are displaying a success toast message.

Toast.makeText(MainActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();

} catch (JSONException e) {

e.printStackTrace();

// and setting data to edit text as empty

courseNameEdt.setText("");

courseDescriptionEdt.setText("");

courseDurationEdt.setText("");

}, new com.android.volley.Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {


4341604 MAD 226370316018

// method to handle errors.

Toast.makeText(MainActivity.this, "Fail to get response = " + error, Toast.LENGTH_SHORT).show();

}) {

@Override

public String getBodyContentType() {

// as we are passing data in the form of url encoded

// so we are passing the content type below

return "application/x-www-form-urlencoded; charset=UTF-8";

@Override

protected Map<String, String>getParams() {

// below line we are creating a map for storing

// our values in key and value pair.

Map<String, String> params = new HashMap<String, String>();

// on below line we are passing our

// key and value pair to our parameters.

params.put("courseName", courseName);

params.put("courseDuration", courseDuration);

params.put("courseDescription", courseDescription);

// at last we are returning our params.

return params;

};

// below line is to make

// a json object request.

queue.add(request);
4341604 MAD 226370316018

Insert data into database

Inserted data is shown here in database


4341604 MAD 226370316018
4351604 Mobile Application Development 7
226370316018

Practical:-17
Aim:- Perform Firebase Integration to your Android application and store the data
in the Firebase Database.
4351604 Mobile Application Development 7
226370316018

Practical:-17
Aim:- Perform Firebase Integration to your Android application and store the data
in the Firebase Database.

Step 1: Create a New Project


To create a new project in Android Studio please refer to How to Create/Start a New Project
in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to Firebase


After creating a new project navigate to the Tools option on the top bar. Inside that click
on Firebase. After clicking on Firebase, you can get to see the right column mentioned below
in the screenshot.

Inside that column Navigate to Firebase Realtime Database. Click on that option and you
will get to see two options on Connect app to Firebase and Add Firebase Realtime
Database to your app. Click on Connect now and your app will be connected to Firebase.
After that click on the second option and now your App is connected to Firebase.
4351604 Mobile Application Development 7
226370316018

After connecting your app to Firebase you will get to see the below screen.
4351604 Mobile Application Development 7
226370316018

Step 3: Working with AndroidManifest.xml file


For adding data to Firebase we should have to give permissions for accessing the internet. For
adding these permissions navigate to the app > AndroidManifest.xml and inside that file add
the below permissions to it.

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


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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Pr17"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

</manifest>
4351604 Mobile Application Development 7
226370316018

OUTPUT:-
4351604 Mobile Application Development 7
226370316018

Step 4: Working with the activity_main.xml file


Go to the activity_main.xml file and refer to the following code. Below is the code for
the activity_main.xml file.

<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!--EditText for adding employee name-->


<EditText
android:id="@+id/idEdtEmployeeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:hint="Enter Employee Name"
android:importantForAutofill="no"
android:inputType="textPersonName" />

<!--EditText for adding employee phone-->


<EditText
android:id="@+id/idEdtEmployeePhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeName"
android:layout_margin="10dp"
android:hint="Enter employee phone number"
android:importantForAutofill="no"
android:inputType="phone" />

<!--EditText for adding employee address-->


<EditText
android:id="@+id/idEdtEmployeeAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeePhoneNumber"
4351604 Mobile Application Development 7
226370316018

android:layout_margin="10dp"
android:hint="Enter employee address"
android:inputType="textPostalAddress" />

<!--Button for adding data to Firebase-->


<Button
android:id="@+id/idBtnSendData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeAddress"
android:layout_margin="10dp"
android:text="Add employee details"
android:textAllCaps="false" />

</RelativeLayout>
4351604 Mobile Application Development 7
226370316018

Step 5: Create a new Java class for storing our data


For sending multiple data to the Firebase Realtime database we have to create an Object class
and send that whole object class to Firebase. For creating an object class navigate to the app >
java > your app’s package name > Right-click on it and Click on New > Java Class >
Give a name to your class. In my case, it is EmployeeInfo, and add below code to it.

package com.example.pr17;

public class EmployeeInfo {


// string variable for
// storing employee name.
private String employeeName;

// string variable for storing


// employee contact number
private String employeeContactNumber;

// string variable for storing


// employee address.
private String employeeAddress;

// an empty constructor is
// required when using
// Firebase Realtime Database.
public EmployeeInfo() {

// created getter and setter methods


// for all our variables.
public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {


this.employeeName = employeeName;
}

public String getEmployeeContactNumber() {


return employeeContactNumber;
4351604 Mobile Application Development 7
226370316018

public void setEmployeeContactNumber(String employeeContactNumber) {


this.employeeContactNumber = employeeContactNumber;
}

public String getEmployeeAddress() {


return employeeAddress;
}

public void setEmployeeAddress(String employeeAddress) {


this.employeeAddress = employeeAddress;
}
}
4351604 Mobile Application Development 7
226370316018

OUTPUT:-
4351604 Mobile Application Development 7
226370316018

Step 6: Working with the MainActivity.java file


Go to the MainActivity.java file and refer to the following code. Below is the code for
the MainActivity.java file. Comments are added inside the code to understand the code in
more detail.

package com.example.pr17;

import android.os.Bundle;

import android.text.TextUtils;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DataSnapshot;

import com.google.firebase.database.DatabaseError;

import com.google.firebase.database.DatabaseReference;

import com.google.firebase.database.FirebaseDatabase;

import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {

private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;

private Button sendDatabtn;

FirebaseDatabase firebaseDatabase;

DatabaseReference databaseReference;

EmployeeInfo employeeInfo;

@Override
4351604 Mobile Application Development 7
226370316018

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

employeeNameEdt = findViewById(R.id.idEdtEmployeeName);

employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);

employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);

firebaseDatabase = FirebaseDatabase.getInstance();

databaseReference = firebaseDatabase.getReference("EmployeeInfo");

employeeInfo = new EmployeeInfo()

sendDatabtn = findViewById(R.id.idBtnSendData);

sendDatabtn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

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

String phone = employeePhoneEdt.getText().toString();

String address = employeeAddressEdt.getText().toString();

if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) &&


TextUtils.isEmpty(address)) {

Toast.makeText(MainActivity.this, "Please add some data.",


Toast.LENGTH_SHORT).show();

} else {

addDatatoFirebase(name, phone, address);

});

}
4351604 Mobile Application Development 7
226370316018

private void addDatatoFirebase(String name, String phone, String address) {

employeeInfo.setEmployeeName(name);

employeeInfo.setEmployeeContactNumber(phone);

employeeInfo.setEmployeeAddress(address);

databaseReference.addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(@NonNull DataSnapshot snapshot) {

databaseReference.setValue(employeeInfo);

Toast.makeText(MainActivity.this, "data added",


Toast.LENGTH_SHORT).show();

@Override

public void onCancelled(@NonNull DatabaseError error) {

Toast.makeText(MainActivity.this, "Fail to add data " + error,


Toast.LENGTH_SHORT).show();

});

}
4351604 Mobile Application Development 7
226370316018

After adding this code go to this link for Firebase. After clicking on this link you will get to see
the below page and on this page Click on Go to Console option in the top right corner.

After clicking on this screen you will get to see the below screen with your all project inside
that select your project.
4351604 Mobile Application Development 7
226370316018

Inside that screen click n Realtime Database in the left window.

After clicking on this option you will get to see the screen on the right side. On this page click
on the Rules option which is present in the top bar. You will get to see the below screen.

Inside this screen click on the Rules tab you will get to see the above screen and change the
rules to true as shown in the screenshot. The rules are changed to true because we are not
providing authentication inside our app and we have to write data to our database. That’s why
we are specifying it to true. After changing your rules click on the publish rules button. Click
on that option and your rules will be published. Now come back to the Data tab of your
database.
4351604 Mobile Application Development 7
226370316018
4341604 Mobile Application Development 9
226370316018

Practical – 21
AIM : - Perform reading of the data from the MySQL database using
PHP in the JSON format and display on the screen of an Android
application.
4341604 Mobile Application Development 9
226370316018

PHP file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "id16310745_gfgdatabase";

// connect with database demo


$conn = new mysqli($servername, $username, $password, $dbname);

// an array to display response


$response = array();
// on below line we are checking if the parameter send is id or not.
if($_POST['id']){
// if the parameter send from the user id then
// we will search the item for specific id.
$id = $_POST['id'];
//on below line we are selecting the course detail with below id.
$stmt = $conn->prepare("SELECT courseName,courseDescription,courseDuration FROM courseDb WHERE
id = ?");
$stmt->bind_param("s",$id);
$result = $stmt->execute();
// on below line we are checking if our
// table is having data with specific id.
if($result == TRUE){
// if we get the response then we are displaying it below.
$response['error'] = false;
$response['message'] = "Retrieval Successful!";
// on below line we are getting our result.
$stmt->store_result();
// on below line we are passing parameters which we want to get.
$stmt->bind_result($courseName,$courseDescription,$courseDuration);
// on below line we are fetching the data.
$stmt->fetch();
// after getting all data we are passing this data in our array.
$response['courseName'] = $courseName;
$response['courseDescription'] = $courseDescription;
$response['courseDuration'] = $courseDuration;
} else{
// if the id entered by user donot exist then
// we are displaying the error message
$response['error'] = true;
$response['message'] = "Incorrect id";
}
} else{
// if the user donot adds any parameter while making request
// then we are displaying the error as insufficient parameters.
$response['error'] = true;
$response['message'] = "Insufficient Parameters";
}
// at last we are printing
// all the data on below line.
4341604 Mobile Application Development 9
226370316018

echo json_encode($response);
?>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<!--Edit text for getting course id-->


<EditText
android:id="@+id/idEdtCourseId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:hint="Enter Course Id"
android:importantForAutofill="no"
android:inputType="number" />

<!--Button for adding your course to Firebase-->


<Button
android:id="@+id/idBtnGetCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Get Course Details"
android:textAllCaps="false" />

<androidx.cardview.widget.CardView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/idCVCOurseItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:visibility="gone"
app:cardCornerRadius="6dp"
app:cardElevation="4dp">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:orientation="vertical"
android:padding="4dp">

<!--Textview for displaying our Course Name-->


4341604 Mobile Application Development 9
226370316018

<TextView
android:id="@+id/idTVCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="CourseName"
android:textColor="@color/purple_500"
android:textSize="18sp"
android:textStyle="bold" />

<!--Textview for displaying our Course Duration-->


<TextView
android:id="@+id/idTVCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Duration"
android:textColor="@color/black" />

<!--Textview for displaying our Course Description-->


<TextView
android:id="@+id/idTVCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:text="Description"
android:textColor="@color/black" />
</LinearLayout>

</androidx.cardview.widget.CardView>

</LinearLayout>
Main_activity.java

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
4341604 Mobile Application Development 9
226370316018

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

// creating variables for our edit text


private EditText courseIDEdt;

// creating variable for button


private Button getCourseDetailsBtn;

// creating variable for card view and text views.


private CardView courseCV;
private TextView courseNameTV, courseDescTV, courseDurationTV;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// initializing all our variables.


courseNameTV = findViewById(R.id.idTVCourseName);
courseDescTV = findViewById(R.id.idTVCourseDescription);
courseDurationTV = findViewById(R.id.idTVCourseDuration);
getCourseDetailsBtn = findViewById(R.id.idBtnGetCourse);
courseIDEdt = findViewById(R.id.idEdtCourseId);
courseCV = findViewById(R.id.idCVCOurseItem);

// adding click listener for our button.


getCourseDetailsBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// checking if the id text field is empty or not.
if (TextUtils.isEmpty(courseIDEdt.getText().toString())) {
Toast.makeText(MainActivity.this, "Please enter course id",
Toast.LENGTH_SHORT).show();
return;
}
// calling method to load data.
getCourseDetails(courseIDEdt.getText().toString());
}
});
}

private void getCourseDetails(String courseId) {

// url to post our data


String url = "http://localhost/courseApp/readCourses.php";

// creating a new variable for our request queue


RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

// on below line we are calling a string


4341604 Mobile Application Development 9
226370316018

// request method to post the data to our API


// in this we are calling a post method.
StringRequest request = new StringRequest(Request.Method.POST, url, new
com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
// on below line passing our response to json object.
JSONObject jsonObject = new JSONObject(response);
// on below line we are checking if the response is null or not.
if (jsonObject.getString("courseName") == null) {
// displaying a toast message if we get error
Toast.makeText(MainActivity.this, "Please enter valid id.",
Toast.LENGTH_SHORT).show();
} else {
// if we get the data then we are setting it in our text views in
below line.
courseNameTV.setText(jsonObject.getString("courseName"));

courseDescTV.setText(jsonObject.getString("courseDescription"));

courseDurationTV.setText(jsonObject.getString("courseDuration"));
courseCV.setVisibility(View.VISIBLE);
}
// on below line we are displaying
// a success toast message.
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// method to handle errors.
Toast.makeText(MainActivity.this, "Fail to get course" + error,
Toast.LENGTH_SHORT).show();
}
}) {
@Override
public String getBodyContentType() {
// as we are passing data in the form of url encoded
// so we are passing the content type below
return "application/x-www-form-urlencoded; charset=UTF-8";
}

@Override
protected Map<String, String> getParams() {

// below line we are creating a map for storing our values in key and value pair.
Map<String, String> params = new HashMap<String, String>();

// on below line we are passing our key and value pair to our parameters.
params.put("id", courseId);
4341604 Mobile Application Development 9
226370316018

// at last we are returning our params.


return params;
}
};
// below line is to make
// a json object request.
queue.add(request);
}
}
4341604 Mobile Application Development 9
226370316018

Output
4351604 Mobile Application Development 04
226370316018

Practical No:- 19
Aim:- Connect an Android application to the MySQL database using
PHP, and insert the data in the database table.
4351604 Mobile Application Development 04
226370316018

Output:
4351604 Mobile Application Development 04
226370316018

Practical No:- 19
Aim:- Connect an Android application to the MySQL database using
PHP, and insert the data in the database table.

PHP code:
<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "id16310745_gfgdatabase";

$conn = new mysqli($servername, $username, $password, $dbname);

$response = array();

if($_POST['courseName'] && $_POST['courseDuration'] && $_POST['courseDescription']){

$courseName = $_POST['courseName'];

$courseDuration = $_POST['courseDuration'];

$courseDescription = $_POST['courseDescription'];

$stmt = $conn->prepare("INSERT INTO `courseDb`(`courseName`, `courseDuration`,


`courseDescription`) VALUES (?,?,?)");

$stmt->bind_param("sss",$courseName,$courseDuration,$courseDescription);

if($stmt->execute() == TRUE){

$response['error'] = false;

$response['message'] = "course created successfully!";

} else{
4351604 Mobile Application Development 04
226370316018

$response['error'] = true;

$response['message'] = "failed\n ".$conn->error;

} else{

$response['error'] = true;

$response['message'] = "Insufficient parameters";

echo json_encode($response);

?>
4351604 Mobile Application Development 04
226370316018

Output:
4351604 Mobile Application Development 04
226370316018

 activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

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

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

tools:context=".MainActivity">

<!--Edit text for getting course Name-->

<EditText

android:id="@+id/idEdtCourseName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="20dp"

android:layout_marginEnd="10dp"

android:hint="Course Name"

android:importantForAutofill="no"

android:inputType="text" />

<!--Edittext for getting course Duration-->


4351604 Mobile Application Development 04
226370316018

<EditText

android:id="@+id/idEdtCourseDuration"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="20dp"

android:layout_marginEnd="10dp"

android:hint="Course Duration in min"

android:importantForAutofill="no"

android:inputType="time" />

<!--Edittext for getting course Description-->

<EditText

android:id="@+id/idEdtCourseDescription"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginStart="10dp"

android:layout_marginTop="20dp"

android:layout_marginEnd="10dp"

android:hint="Course Description"

android:importantForAutofill="no"

android:inputType="text" />
4351604 Mobile Application Development 04
226370316018

<!--Button for adding your course to Firebase-->

<Button

android:id="@+id/idBtnSubmitCourse"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_margin="10dp"

android:text="Submit Course Details"

android:textAllCaps="false" />

</LinearLayout>

 Add the below dependency in your build.gradle file.


implementation ‘com.android.volley:volley:1.1.1’

 Adding permissions to the internet in the AndroidManifest.xml file


<uses-permission android:name="android.permission.INTERNET"/>
4351604 Mobile Application Development 04
226370316018

 MainActivity.java file:
import android.os.Bundle;

import android.text.TextUtils;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.VolleyError;

import com.android.volley.toolbox.StringRequest;

import com.android.volley.toolbox.Volley;

import org.json.JSONException;

import org.json.JSONObject;

import java.util.HashMap;

import java.util.Map;
4351604 Mobile Application Development 04
226370316018

public class MainActivity extends AppCompatActivity {

private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt;

private Button submitCourseBtn;

private String courseName, courseDuration, courseDescription

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

courseNameEdt = findViewById(R.id.idEdtCourseName);

courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);

courseDurationEdt = findViewById(R.id.idEdtCourseDuration);

submitCourseBtn = findViewById(R.id.idBtnSubmitCourse);

submitCourseBtn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

courseName = courseNameEdt.getText().toString();

courseDescription = courseDescriptionEdt.getText().toString();

courseDuration = courseDurationEdt.getText().toString();

if (TextUtils.isEmpty(courseName)) {

courseNameEdt.setError("Please enter Course Name");

} else if (TextUtils.isEmpty(courseDescription)) {

courseDescriptionEdt.setError("Please enter Course


Description");

} else if (TextUtils.isEmpty(courseDuration)) {
4351604 Mobile Application Development 04
226370316018

courseDurationEdt.setError("Please enter Course Duration");

} else {.

addDataToDatabase(courseName, courseDescription, courseDuration);}

}});

private void addDataToDatabase(String courseName, String courseDescription, String


courseDuration) {

String url = "http://localhost/courseApp/addCourses.php";

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

StringRequest request = new StringRequest(Request.Method.POST, url, new


com.android.volley.Response.Listener<String>() {

@Override

public void onResponse(String response) {

Log.e("TAG", "RESPONSE IS " + response);

try {

JSONObject jsonObject = new JSONObject(response);

jsonObject.getString("message"), Toast.LENGTH_SHORT).show();

} catch (JSONException e) {

e.printStackTrace();}

courseNameEdt.setText("");

courseDescriptionEdt.setText("");

courseDurationEdt.setText("");

}
4351604 Mobile Application Development 04
226370316018

}, new com.android.volley.Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

Toast.makeText(MainActivity.this, "Fail to get response = " +


error, Toast.LENGTH_SHORT).show();

}) {

@Override

public String getBodyContentType() {

return "application/x-www-form-urlencoded; charset=UTF-8";

@Override

protected Map<String, String> getParams() {

Map<String, String> params = new HashMap<String, String>();

params.put("courseName", courseName);

params.put("courseDuration", courseDuration);

params.put("courseDescription", courseDescription);

return params;

};

queue.add(request);

}
4351604 Mobile Application Development 2263703160184

Practical No:- 17
Aim:- Perform Firebase Integration to your Android applicationand
store the data in the Firebase Database.
4351604 Mobile Application Development 2263703160184

Practical No:- 17

Aim:- Perform Firebase Integration to your Android application and store thedata
in the Firebase Database.

Step 1: Create a New Project


To create a new project in Android Studio please refer to How to Create/Start a New Project
in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to Firebase


After creating a new project navigate to the Tools option on the top bar. Inside that click
on Firebase. After clicking on Firebase, you can get to see the right column mentioned below
in the screenshot.

Inside that column Navigate to Firebase Realtime Database. Click on that option and you
will get to see two options on Connect app to Firebase and Add Firebase Realtime
Database to your app. Click on Connect now and your app will be connected to Firebase.
After that click on the second option and now your App is connected to Firebase.
4351604 Mobile Application Development 2263703160184

After connecting your app to Firebase you will get to see the below screen.
4351604 Mobile Application Development 2263703160184

Step 3: Working with AndroidManifest.xml file:

For adding data to Firebase we should have to give permissions for accessing the internet. For
adding these permissions navigate to the app > AndroidManifest.xml and inside that file add
the below permissions to it.

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


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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Pr17"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

</manifest>
4351604 Mobile Application Development 2263703160184

Output:
4351604 Mobile Application Development 2263703160184

Step 4: Working with the activity_main.xml file:

Go to the activity_main.xml file and refer to the following code. Below is the code for
the activity_main.xml file.

<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!--EditText for adding employee name-->


<EditText
android:id="@+id/idEdtEmployeeName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:hint="Enter Employee Name"
android:importantForAutofill="no"
android:inputType="textPersonName" />

<!--EditText for adding employee phone-->


<EditText
android:id="@+id/idEdtEmployeePhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeName"
android:layout_margin="10dp"
android:hint="Enter employee phone number"
android:importantForAutofill="no"
android:inputType="phone" />

<!--EditText for adding employee address-->


<EditText
android:id="@+id/idEdtEmployeeAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
4351604 Mobile Application Development 2263703160184

android:layout_below="@id/idEdtEmployeePhoneNumber"
android:layout_margin="10dp"
android:hint="Enter employee address"
android:inputType="textPostalAddress" />

<!--Button for adding data to Firebase-->


<Button
android:id="@+id/idBtnSendData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/idEdtEmployeeAddress"
android:layout_margin="10dp"
android:text="Add employee details"
android:textAllCaps="false" />

</RelativeLayout>
4351604 Mobile Application Development 2263703160184

Step 5: Create a new Java class for storing our data:

For sending multiple data to the Firebase Realtime database we have to create an Object class
and send that whole object class to Firebase. For creating an object class navigate to the app >
java > your app’s package name > Right-click on it and Click on New > Java Class >
Give a name to your class. In my case, it is EmployeeInfo, and add below code to it.

package com.example.pr17;

public class EmployeeInfo {


// string variable for
// storing employee name.
private String employeeName;

// string variable for storing


// employee contact number
private String employeeContactNumber;

// string variable for storing


// employee address.
private String employeeAddress;

// an empty constructor is
// required when using
// Firebase Realtime Database.
public EmployeeInfo() {

// created getter and setter methods


// for all our variables.
public String getEmployeeName() {
return employeeName;
}

public void setEmployeeName(String employeeName) {


this.employeeName = employeeName;
}

public String getEmployeeContactNumber() {


4351604 Mobile Application Development 2263703160184

return employeeContactNumber;
}

public void setEmployeeContactNumber(String employeeContactNumber) {


this.employeeContactNumber = employeeContactNumber;
}

public String getEmployeeAddress() {


return employeeAddress;
}

public void setEmployeeAddress(String employeeAddress) {


this.employeeAddress = employeeAddress;
}
}
4351604 Mobile Application Development 2263703160184

Output:
4351604 Mobile Application Development 2263703160184

Step 6: Working with the MainActivity.java file:

Go to the MainActivity.java file and refer to the following code. Below is the code for
the MainActivity.java file. Comments are added inside the code to understand the code in
more detail.

package com.example.pr17;

import android.os.Bundle;

import android.text.TextUtils;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DataSnapshot;

import com.google.firebase.database.DatabaseError;

import com.google.firebase.database.DatabaseReference;

import com.google.firebase.database.FirebaseDatabase;

import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {

private EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;

private Button sendDatabtn;

FirebaseDatabase firebaseDatabase;

DatabaseReference databaseReference;

EmployeeInfo employeeInfo;

@Override
4351604 Mobile Application Development 2263703160184

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

employeeNameEdt = findViewById(R.id.idEdtEmployeeName);

employeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);

employeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);

firebaseDatabase = FirebaseDatabase.getInstance();

databaseReference = firebaseDatabase.getReference("EmployeeInfo");

employeeInfo = new EmployeeInfo()

sendDatabtn = findViewById(R.id.idBtnSendData);

sendDatabtn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

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

String phone = employeePhoneEdt.getText().toString();

String address = employeeAddressEdt.getText().toString();

if (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) &&


TextUtils.isEmpty(address)) {

Toast.makeText(MainActivity.this, "Please add some data.",


Toast.LENGTH_SHORT).show();

} else {

addDatatoFirebase(name, phone, address);

});

}
4351604 Mobile Application Development 2263703160184

private void addDatatoFirebase(String name, String phone, String address) {

employeeInfo.setEmployeeName(name);

employeeInfo.setEmployeeContactNumber(phone);

employeeInfo.setEmployeeAddress(address);

databaseReference.addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(@NonNull DataSnapshot snapshot) {

databaseReference.setValue(employeeInfo);

Toast.makeText(MainActivity.this, "data added",


Toast.LENGTH_SHORT).show();

@Override

public void onCancelled(@NonNull DatabaseError error) {

Toast.makeText(MainActivity.this, "Fail to add data " + error,


Toast.LENGTH_SHORT).show();

});

}
4351604 Mobile Application Development 2263703160184

After adding this code go to this link for Firebase. After clicking on this link you will get to see
the below page and on this page Click on Go to Console option in the top right corner.

After clicking on this screen you will get to see the below screen with your all project inside
that select your project.
4351604 Mobile Application Development 2263703160184

Inside that screen click n Realtime Database in the left window.

After clicking on this option you will get to see the screen on the right side. On this page click
on the Rules option which is present in the top bar. You will get to see the below screen.

Inside this screen click on the Rules tab you will get to see the above screen and change the
rules to true as shown in the screenshot. The rules are changed to true because we are not
providing authentication inside our app and we have to write data to our database. That’s why
we are specifying it to true. After changing your rules click on the publish rules button. Click
on that option and your rules will be published. Now come back to the Data tab of your
database.
4351604 Mobile Application Development 226370316008

PRACTICAL – 28

Aim :- Demonstrate publishing an Android app on the Google


Play Store following the policies and guidelines
4351604 Mobile Application Development 226370316008

PRACTICAL – 28

A im :- D e m on stra te pu blish in g a n A n d roid a pp on th e G oo g le P la y S tore

follow in g th e po lic ies a n d gu id elin e s

Step 1: Create a Google Developer account

Before diving into the specifics of publishing your app, let's make sure you have all the
essentials in place. Creating a Google Developer account is something you can do at the
beginning of the app development process. Without a Google Play Store account, you can't
publish your app on the Play Market.

You can use any of your current Google accounts or create another one to sign up for a Google
Developer Account. It doesn't matter whether it's a personal or corporate account. You may
easily transfer your app to another one down the line if needed.

Signing up for a Google Developer account is easy. All you have to do is to:

● Agree to the Google Play Developer Distribution Agreement.


● Provide some basic information.
● Pay a one-time registration fee of $25.
4351604 Mobile Application Development 226370316008

Google Play Developer distribution agreement

Keep in mind that developers with personal developer accounts must meet certain app testing
requirements before they can distribute their app on Google Play. Also, since 2024, developers
with new personal accounts need to verify access to a real Android device using the Play
Console mobile app.

Usually, it takes no more than two days to get approval from Google. Don't worry if you forget
to add some information. You can edit your account later.

Step 2: Add a Merchant account


If you plan to sell paid apps or in-app purchases, you have to create a Google Merchant
Account. A Google Merchant Account will help you manage app sales and your monthly
payouts, as well as analyze sales reports.

Once you finish creating the Merchant profile, the developer account gets automatically linked
to it.

Step 3: Prepare the documents


4351604 Mobile Application Development 226370316008

Based on our experience, we highly recommend starting to prepare the End User License
Agreement (EULA) and Privacy Policy in advance.

You can take the documents from similar apps as references and create your own based on
them, or ask a lawyer to make everything from scratch.

EULA is an agreement between a product owner and a user of the product. In brief, it contains:

● What the users can do with the app and what they aren't allowed to do
● Licensing fees
● Intellectual property information, etc.
While Google Play doesn't require you to have a Terms of Use document for your app, it's a
highly recommended practice. Terms of Use or Terms and Conditions explain how users can
interact with your app and what to expect. You can combine Privacy Policy and Terms of Use
into a single document, with separate chapters for each.

Make sure to include the following information in the Privacy Policy:

● A complete list of personal data that is collected, processed, and used through the app
● Technical information that is collected about the device and the installed OS
● Functional features of the app, its paid and free functionality
● Place of registration of the company and/or location of the copyright holder of the
application
● The chosen legal system and legislation that will be applied in resolving disputes and
regulating legal relations
● The terms of the subscription
● Citizenship (residence) of the overwhelming majority of application users
● Age criteria, the presence of specific content

Step 4: Study Google developer policies


By this time, you must have a well-defined understanding of your product concept. Now you
need to make sure that all the planned features comply with the Google Developer Policies.
These documents explain how mobile apps need to be developed, updated, and promoted to
support the store's high-quality standards. Making sure your app doesn't violate any of the
policies is one of the crucial steps to publish successfully.

If Google decides that your product violates some policy chapters, your app may get rejected,
blocked, or even deleted from Google Play. Besides, numerous and repetitive violations may
lead to account termination.

Read also: Why Google and Apple may remove your app and how to deal with that
4351604 Mobile Application Development 226370316008

So study all the available information about:

● Restricted content definition


● App store listing and promotion
● Impersonation and intellectual property
● Rules for monetization and ads
● Privacy, security, and deception regulation
● Spam and minimum functionality
Google is constantly refreshing its policies, so it's important to monitor the changes even after
your Android app is released.

Step 5: Technical requirements


You went through the development process, endless testing, and bug fixing, and finally, the
“X-day” comes. Before moving on to the upload process, you need to check the following
things:

● Unique bundle ID
The package name should be suitable over the life of your application. You cannot change it
after the distribution. You can set the package name in the application's manifest file.

● Signed app release with a signing certificate


Every application should be digitally signed with a developer's certificate. The certificate is
used to identify the author of an app and can’t be generated again.

● The app size


Google imposes file size limits for uploads, allowing up to 100MB for Android 2.3 and higher
(API level 9-10, 14 and above) and 50MB for earlier Android versions.

If your app exceeds this limit, you can always switch to APK Expansion Files.

● The file format


Google accepts two release formats, including app bundles and .apk. However, .aab is a more
preferred option. To use this format, you need to enroll in app signing by Google Play.

You may learn more about app file technical requirements in the Developer
Documents, Prepare for the release guide.
4351604 Mobile Application Development 226370316008

Step 6: Creating the App on the Google Console


When you have the file lined up, you need to create a brand new app listing in your Developer
Account. Here's how to do it:

● Head over to the All applications tab in the menu


● Now select Create Application
● Choose the app’s default language from the drop-down menu
● Add a brief app description (you can change it later)
● Tap on Create
After this, you will be directed to the store listing page, where you can add all the details about
your mobile app.

Step 7: Prepare store listing


Your app listing contains the information needed for app store optimization (ASO) and gives
users more insights into your app before downloading. The mandatory sections are marked
with *.

You may need input from a designer and a copywriter, so it's better to start preparing the
following materials in advance.

● Product description
It contains a title of your app (up to 50 symbols), a brief description (up to 80 symbols), and a
full description (up to 4000 symbols). But remember, avoid keyword stuffing. Focus on writing
naturally and engagingly, and the right keywords will find their way in.
4351604 Mobile Application Development 226370316008

Store listing

● Screenshots
You may add from 2 to 8 screenshots. Choose the ones that highlight the app's functionality
and its unique value.

The requirements are the following:

- JPEG or 24-bit PNG (no alpha)

- from 320px to 3840 px

- the ratio of the long side to the short side should not be more than 2:1
4351604 Mobile Application Development 226370316008

Store listing - Product details

● Icon
The requirements are the following:

- 512px by 512px

- 32-bit PNG (with alpha)

- Maximum file size: 1024KB

● Feature graphic
It is an optional marketing tool displayed in various places on Google Play, including the
homepage.

The requirements are the following:

- JPEG or 24-bit PNG (no alpha)

- 1024px x 500px

● Promo video
If you have any promo videos, you may add a link to your YouTube channel directly in the app
listing. This video will be displayed at the top of your app's page.
4351604 Mobile Application Development 226370316008

● Tags
Unlike some app stores, Google Play doesn't allow custom keywords. When creating your app
listing, you'll be able to choose from a predefined list of relevant keywords. Here's the trick:
selecting the most accurate keywords will significantly boost your App Store Optimization
(ASO) and help users discover your app.

● Localization
If your app supports several languages, you can add translations for your app's Store Listing
page, APK files, strings or in-app products. It's highly recommended to include localized
screenshots and images.

● Application type and categorization


Through the drop-down menu, select your application type: game or app. Then pick the
category that best fits your app's genre or purpose. You can also add a section to rate your
content after uploading the APK to the Google Play store.

App categories on Google Play

● Contact details
Here, you should provide the support service contacts. By filling in the website URL, email, and
phone, you make it easier for the users to contact you if necessary.
4351604 Mobile Application Development 226370316008

● Privacy Policy
Google requires you to add a link to the Privacy Policy that we mentioned above.

While editing the Store Listing, you can take a break at any moment, click Save Draft, and
complete this stage later.

Step 8: Content rating


To ensure your app is visible on Google Play and avoid potential removal, you'll need to
complete a Content Rating questionnaire. You can easily find this section on the left-side
menu.

You must provide accurate information for the questionnaire as any misrepresentation of your
app's content might lead to suspension or removal of the Google Play account.

● Click on Save Questionnaire once you complete the survey


● Click on Calculate Rating
● Сlick on Apply Rating to confirm the rating and move forward with the pricing &
distribution plan

Step 9: Pricing the application


In the Pricing and distribution section, you need to fill in the following information:

● Whether your app is free or paid


● Where the app will be available to download (just choose the countries from the list)
● Whether your app will be available only on specific devices
● Whether the app has sensitive content and is not suitable for children under the age of
13
● Whether your app contains ads
Remember that you can change your paid app to a free one later, but a free app cannot be
changed to a paid one. If you decide later that you want to distribute the app for money, you'll
have to create another app with a new package name.
4351604 Mobile Application Development 226370316008

Step 10: Upload the APK and send it for review

Finally, you are ready to upload your Android app file. Head over to the App Releases section
on the left panel. Here, you will find three options for publishing the app: Production, Beta and
Alpha tracks.

We highly recommend starting with the Alpha or Beta versions. In this case, after passing the
review process, your app will not be available to everyone on the Google Play store.

The Alpha version assumes testing in a closed environment where you can invite a trusted
group of testers. With Beta testing, anyone can sign up to be a tester and send feedback to
you after giving your app a test drive.

Pre-release testing allows you to gather people's opinions, test your app with a broader
audience, and fix issues before making the app public.

Note that if you decide to change the Alpha or Beta version to the Production type, it will take
time to go through another review round.

Once you choose the type of release, follow the steps:

● Choose Manage (Production/Beta/Alpha)


4351604 Mobile Application Development 226370316008

● Click on Edit Release


● Upload an APK or app bundle
The release name will be added automatically. For the first time, you may delete the text from
the What’s new in this release field.

App releases

● Click on Review to confirm the changes and send your app for review by pressing Start
rollout to production
Don't stress over missing crucial details. Google Play offers helpful instructions and tips
throughout the publishing process. Plus, the system won't let you submit your app for review if
there are any critical missing pieces.

Remember that with the very first version, there is no opportunity to set manual publishing.
The app will be released right after it passes the review. Usually, it takes up to 2 days. Google
says the review process could take up to 7 days or even longer in exceptional cases.

Once the app is reviewed, you'll receive a notification on Google Console Dashboard.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy