0% found this document useful (0 votes)
9 views

Android Pract 5-9

Mobile computing lab

Uploaded by

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

Android Pract 5-9

Mobile computing lab

Uploaded by

Firoza
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/ 67

PRACTICAL 5

AIM: - Android program to perform CRUD operation using SQlite DB

THEORY: -
What is SQLite?
SQLite is an SQL Database. I am assuming here that you are familiar with SQL databases. So in
SQL database, we store data in tables. The tables are the structure of storing data consisting of
rows and columns. We are not going in depth of what is an SQL database and how to work in
SQL database. If you are going through this post, then you must know the Basics of SQL.

What is CRUD?
As the heading tells you here, we are going to learn the CRUD operation in SQLite Database.
CRUD is nothing but an abbreviation for the basic operations that we perform in any database.
And the operations are
• Create
• Read
• Update
• Delete

STEPS: -
1) activity_main.xml contains the code for the UI
2) The code for below files are written in code section
● MainActivity.java
● MyDBHandler.java
● Student.java
3) The database SQLite is in the Android since newest version.
4) Check for newest version.
5) In device file explorer section we can click and goto the project and expand data
6) The database can be viewed in the data section there.
CODE: -
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">

<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your ROLL NO"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.338"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.072" />

<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ROLL NO: -"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.205"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />

<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NAME: -"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.194"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.159" />

<EditText
android:id="@+id/et2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter your Name"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.338"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.214" />

<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EMAIL-ID: -"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.214"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.29" />
<EditText
android:id="@+id/et3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter your Email"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.338"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.346" />

<TextView
android:id="@+id/tv4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="COURSE: -"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.202"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.424" />

<EditText
android:id="@+id/et4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter your Course"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.348"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.483" />

<TextView
android:id="@+id/tv5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CONTACT NO: -"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.235"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.555" />

<EditText
android:id="@+id/et5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your Contact No"
android:inputType="phone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.348"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.619" />

<TextView
android:id="@+id/tv6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ADDRESS: -"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.208"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.681" />

<EditText
android:id="@+id/et6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter your Address"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.338"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.752" />

<Button
android:id="@+id/load"
android:layout_width="96dp"
android:layout_height="49dp"
android:text="LOAD"
android:onClick="loadStudents"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.852" />

<Button
android:id="@+id/upd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UPDATE"
android:onClick="updateStudent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.996"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.852" />

<Button
android:id="@+id/ins"
android:layout_width="101dp"
android:layout_height="47dp"
android:text="INSERT"
android:onClick="addStudent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.345"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.849" />

<Button
android:id="@+id/del"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DELETE"
android:onClick="deleteStudent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.672"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.852" />

<TextView
android:id="@+id/tv8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.924" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.prac5;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

//TextView resultText;
EditText rno;
EditText name;
EditText email;
EditText course;
EditText contact;
EditText address;
TextView output1;
MyDBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

rno = (EditText) findViewById(R.id.et1);


name = (EditText) findViewById(R.id.et2);
email = (EditText) findViewById(R.id.et3);
course = (EditText) findViewById(R.id.et4);
contact = (EditText) findViewById(R.id.et5);
address = (EditText) findViewById(R.id.et6);
output1=findViewById(R.id.tv8);
//output1.setMovementMethod(new ScrollingMovementMethod());
dbHandler= new MyDBHandler(this);
}
public void loadStudents(View view) {
output1.setText(dbHandler.loadHandler());
rno.setText("");
name.setText("");
email.setText("");
course.setText("");
contact.setText("");
address.setText("");
}

public void addStudent (View view) {


if(!rno.getText().toString().isEmpty() && !name.getText().toString().isEmpty() &&
!email.getText().toString().isEmpty() && !course.getText().toString().isEmpty() &&
!contact.getText().toString().isEmpty() && !address.getText().toString().isEmpty()) {
int id = Integer.parseInt(rno.getText().toString());
String nm = name.getText().toString();
String em = email.getText().toString();
String cr = course.getText().toString();
int cn = Integer.parseInt(contact.getText().toString());
String ad = address.getText().toString();
Student student = new Student(id, nm, em, cr, cn, ad);

long insertId=dbHandler.addHandler(student);
if(insertId==-1){
output1.setText("Record already exists");
}
else{
rno.setText("");
name.setText("");
email.setText("");
course.setText("");
contact.setText("");
address.setText("");
output1.setText("Record added");
}
}
else{
output1.setText("Please fill correct id and name");
}
}
public void updateStudent(View view) {
if(!rno.getText().toString().isEmpty() && !name.getText().toString().isEmpty() &&
!email.getText().toString().isEmpty() && !course.getText().toString().isEmpty() &&
!contact.getText().toString().isEmpty() && !address.getText().toString().isEmpty()) {
boolean result = dbHandler.updateHandler(Integer.parseInt(rno.getText().toString()),
name.getText().toString(), email.getText().toString(), course.getText().toString(),
Integer.parseInt(contact.getText().toString()), address.getText().toString());
if (result) {
rno.setText("");
name.setText("");
email.setText("");
course.setText("");
contact.setText("");
address.setText("");
output1.setText("Record Updated");
} else {
output1.setText("No Record Found");
}
}
else{
output1.setText("Please fill correct id and name");
}
}

public void deleteStudent(View view) {


if(!rno.getText().toString().isEmpty()) {
boolean result = dbHandler.deleteHandler(Integer.parseInt(
rno.getText().toString()));
if (result) {
rno.setText("");
name.setText("");
email.setText("");
course.setText("");
contact.setText("");
address.setText("");
output1.setText("Record Deleted");
} else {
output1.setText("No Record Found");
}
} else{
output1.setText("Please fill correct id");
}
}

@Override
protected void onDestroy() {
super.onDestroy();
dbHandler.close();
}

MyDBHandler.java
package com.example.prac5;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 3;


private static final String DATABASE_NAME = "studentDB.db";
private static final String TABLE_STUDENTS = "newstudent";
private static final String COLUMN_RNO = "rno";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_EMAIL = "email";
private static final String COLUMN_COURSE = "course";
private static final String COLUMN_CONTACT = "contact";
private static final String COLUMN_ADDRESS = "address";

MyDBHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_STUDENT_TABLE = "CREATE TABLE " +
TABLE_STUDENTS + "(" + COLUMN_RNO + " INTEGER PRIMARY KEY," +
COLUMN_NAME
+ " TEXT, " + COLUMN_EMAIL + " TEXT, " + COLUMN_COURSE + " TEXT, " +
COLUMN_CONTACT + " INTEGER, " + COLUMN_ADDRESS + " TEXT" + ")";
db.execSQL(CREATE_STUDENT_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STUDENTS);
onCreate(db);
}

String loadHandler() {
String result = "";
String query = "Select*FROM " + TABLE_STUDENTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int result_0 = cursor.getInt(0);
String result_1 = cursor.getString(1);
String result_2 = cursor.getString(2);
String result_3 = cursor.getString(3);
int result_4 = cursor.getInt(4);
String result_5 = cursor.getString(5);
result += String.valueOf(result_0) + " " + result_1 + " " + result_2 + " " + result_3 + " " +
String.valueOf(result_4)+" " + result_5;
System.getProperty("line.separator");
}
cursor.close();
db.close();
if(result.equals(""))
result="No Record Found";
return result;
}

long addHandler(Student student) {


long id;
ContentValues values = new ContentValues();
values.put(COLUMN_RNO, student.getID());
values.put(COLUMN_NAME, student.getName());
values.put(COLUMN_EMAIL, student.getEmail());
values.put(COLUMN_COURSE, student.getCourse());
values.put(COLUMN_CONTACT, student.getContact());
values.put(COLUMN_ADDRESS, student.getAddress());
SQLiteDatabase db = this.getWritableDatabase();
id = db.insert(TABLE_STUDENTS, null, values);
db.close();
return id;
}

boolean updateHandler(int rno, String name, String email, String course, int contact, String
address) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(COLUMN_RNO, rno);
args.put(COLUMN_NAME, name);
args.put(COLUMN_EMAIL, email);
args.put(COLUMN_COURSE, course);
args.put(COLUMN_CONTACT, contact);
args.put(COLUMN_ADDRESS, address);
return db.update(TABLE_STUDENTS, args, COLUMN_RNO + "=" + rno, null) > 0;
}

boolean deleteHandler(int ID) {


boolean result = false;
String query = "Select*FROM " + TABLE_STUDENTS + " WHERE " + COLUMN_RNO +
" = '" + String.valueOf(ID) + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Student student = new Student();
if (cursor.moveToFirst()) {
student.setID(Integer.parseInt(cursor.getString(0)));
db.delete(TABLE_STUDENTS, COLUMN_RNO + "=?",
new String[] {
String.valueOf(student.getID())
});
cursor.close();
result = true;
}
db.close();
return result;
}

Student.java
package com.example.prac5;

public class Student {


private int rno;
private String name;
private String email;
private String course;
private int contact;
private String address;

Student() {
}
Student(int rno, String name, String email, String course, int contact, String address) {
this.rno = rno;
this.name = name;
this.email=email;
this.course=course;
this.contact=contact;
this.address=address;
}
void setID(int id) {
this.rno = id;
}
int getID() {
return this.rno;
}
void setName(String name) {
this.name = name;
}
String getName() {
return this.name;
}
void setEmail(String email) {
this.email = email;
}
String getEmail() {
return this.email;
}
void setCourse(String course) {
this.course = course;
}
String getCourse() {
return this.course;
}
void setContact(int contact) {
this.contact = contact;
}
int getContact() {
return this.contact;
}
void setAddress(String address) {
this.address = address;
}
String getAddress() {
return this.address;
}
}
OUTPUT: -
Device File Explorer->Data Output

Device File Explorer->Data Output

CONCLUSION: -
From this practical I have learned to implement Android program to perform CRUD operation
using SQlite DB
PRACTICAL 6

AIM: - Android program using shared preference ,Internal and External storage

THEORY: -
Data and file storage overview
Android uses a file system that's similar to disk-based file systems on other platforms. The
system provides several options for you to save your app data:
● App-specific storage: Store files that are meant for your app's use only, either in
dedicated directories within an internal storage volume or different dedicated directories
within external storage. Use the directories within internal storage to save sensitive
information that other apps shouldn't access.
● Shared storage: Store files that your app intends to share with other apps, including
media, documents, and other files.
● Preferences: Store private, primitive data in key-value pairs.
● Databases: Store structured data in a private database using the Room persistence
library.

Reading and Writing Text File in Android Internal Storage


Android offers openFileInput and openFileOutput from the Java I/O classes to modify reading
and writing streams from and to local files.
openFileOutput(): This method is used to create and save a file. Its syntax is
given below:
FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE);

The method openFileOutput() returns an instance of FileOutputStream.


After that we can call write method to write data on the file. Its syntax is given
below:
String str = "test data";
fOut.write(str.getBytes()); fOut.close();

openFileInput(): This method is used to open a file and read it. It returns an
instance of FileInputStream.
Its syntax is given below:
FileInputStream fin = openFileInput(file);

After that, we call read method to read one character at a time from the file and
then print it. Its syntax is given below: int c; String temp=""; while( (c = fin.read()) !=
-1){ temp = temp + Character.toString((char)c); } fin.close();

SHARED PREFERENCE:
Interface for accessing and modifying preference data returned by
Context.getSharedPreferences(String, int). For any particular set of preferences, there is a single
instance of this class that all clients share. Modifications to the preferences must go through an
Editor object to ensure the preference values remain in a consistent state and control when they
are committed to storage. Objects that are returned from the various get methods must be treated
as immutable by the application.

Two Ways To Save Data Through Shared Preference:


There are two different ways to save data in Android through Shared Preferences – One is using
Activity based preferences and other is creating custom preferences.

Activity Preferences:
● For activity preferences developer have to call function getPreferences (int mode)
available in Activity class
● Use only when one preference file is needed in Activity
● It doesn’t require name as it will be the only preference file for this activity
● Developer doesn’t usually prefer using this even if they need only one preference file in
Activity. They prefer using custom
getSharedPreferences(String name,int mode).
To use activity preferences developer have to call function getPreferences (int mode) available in
Activity class. The function getPreferences(int mode) call the other function used to create
custom preferences i.e
getSharedPreferences(String name,int mode). Just because Activity contains only one preference
file so getPreferences(int mode) function simply pass the name of Activity class to create a
preference file. Important Note: Mode are discussed in Custom preferences.
Custom Preferences:
● Developer needs to use getSharedPreferences(String name,int mode) for custom
preferences
● Used in cases when more than one preference file required in Activity
● Name of the preference file is passed in first parameter
Custom Preferences can be created by calling function getSharedPreferences(String name,int
mode), it can be called from anywhere in the application with reference of Context. Here name is
any preferred name for example: User,Book etc. and mode is used to set kind of privacy for file.

There are three types of Mode in Shared Preference:


1. Context.MODE_PRIVATE – default value (Not accessible outside of your application)
MODE_PRIVATE – It is a default mode. MODE_PRIVATE means that when any
preference file is created with private mode then it will not be accessible outside of your
application. This is the most common mode which is used.
2. Context.MODE_WORLD_READABLE – readable to other apps
MODE_WORLD_READABLE – If developer creates a shared preference file using mode world
readable then it can be read by anyone who knows it’s name, so any other outside application can
easily read data of your app. This mode is very rarely used in App.
3. Context.MODE_WORLD_WRITEABLE – read/write to other apps
MODE_WORLD_WRITEABLE – It’s similar to mode world readable but with both kind of
accesses i.e read and write. This mode is never used in App by Developer.

A) Program to create a file in a directory and perform following file operations, Write into a file,
Read from a file, Delete a file
CODE: -
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">

<EditText
android:id="@+id/et2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter File Name"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.303"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.317" />

<TextView
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FILE NAME: -"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.209"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.248" />

<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DIRECTORY NAME: -"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.27"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.053" />

<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Directory Name"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.303"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.113" />

<TextView
android:id="@+id/txt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CONTENT: -"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.202"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.468" />
<EditText
android:id="@+id/et3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter File Content"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.303"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.542" />

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="READ"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.102"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.664" />

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WRITE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.664" />

<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DELETE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.9"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.664" />

<TextView
android:id="@+id/txt4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.816" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.prac6;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText edit = findViewById(R.id.et1);
EditText edit2 = findViewById(R.id.et2);
EditText edit3 = findViewById(R.id.et3);
Button button = findViewById(R.id.btn1);
Button button2 = findViewById(R.id.btn2);
Button button3 = findViewById(R.id.btn3);
TextView output = findViewById(R.id.txt4);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
StringBuilder result = new StringBuilder();
String line;
String folder = getApplication().getFilesDir().getAbsolutePath() + File.separator +
edit.getText().toString();
File subFolder = new File(folder);
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(folder, edit2.getText().toString())));
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
output.setText(result.toString());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}

});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
String folder = getApplication().getFilesDir().getAbsolutePath() + File.separator +
edit.getText().toString();
File subFolder = new File(folder);
if (!subFolder.exists()) {
subFolder.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(new File(subFolder,
edit2.getText().toString()));
outputStream.write(edit3.getText().toString().getBytes());
outputStream.close();
Toast.makeText(getApplicationContext(), "Writing Successful",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}

});

button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
String folder = getApplication().getFilesDir().getAbsolutePath() + File.separator +
edit.getText().toString();
File subFolder = new File(folder);
File file = new File(folder, edit2.getText().toString());
if (file.exists()) {
file.delete();
}
Toast.makeText(getApplicationContext(), "Deletion Successful",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
}

OUTPUT: -
DEVICE FILE EXPLORER OUTPUT

DEVICE FILE EXPLORER OUTPUT


B) Create a new project and create a login Activity. In this create a login UI asking user email
and password with an option of remember me checkbox. Also a button displaying Sign In or
Register using shared preferences.
CODE: -
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">

<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Email: -"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.349"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.207" />

<EditText
android:id="@+id/et1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your email"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.268" />

<TextView
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Password: -"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.375" />

<EditText
android:id="@+id/et2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter your password"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.438" />

<CheckBox
android:id="@+id/cb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remember Me"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.351"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.527" />

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SIGN IN"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.74" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.prac6b;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences =
this.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
String e=sharedPreferences.getString("Email","");
if(e.length()>0)startHomeActivity();
EditText email =findViewById(R.id.et1);
EditText pass = findViewById(R.id.et2);
CheckBox cbbx = findViewById(R.id.cb1);
Button button = findViewById(R.id.btn1);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (cbbx.isChecked())
saveLoginDetails(email.getText().toString(), pass.getText().toString());
startHomeActivity();
}
});
}

private void startHomeActivity() {


Intent intent = new Intent(this, HomeActivity.class);
startActivity(intent);
finish();
}

private void saveLoginDetails(String email, String password) {


Toast.makeText(this,"pref",Toast.LENGTH_LONG);
new Prefmanager(this).saveLoginDetails(email, password);
}

Prefmanager.java
package com.example.prac6b;

import android.content.Context;
import android.content.SharedPreferences;

public class Prefmanager {


Context context;
Prefmanager(Context context) {
this.context = context;
}

public void saveLoginDetails(String email, String password) {


SharedPreferences sharedPreferences =
context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Email", email);
editor.putString("Password", password);
editor.commit();
}}

activity_home.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=".HomeActivity">

<TextView
android:id="@+id/txt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WELCOME TO APP"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
</androidx.constraintlayout.widget.ConstraintLayout>

HomeActivity.java
package com.example.prac6b;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class HomeActivity extends AppCompatActivity {

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

OUTPUT: -
CONCLUSION: -
From this practical I have learned to implement Android program using shared preference
,Internal and External storage.
PRACTICAL 7

AIM: - Android program to work with graphics and animation

THEORY: -

1) Tween Animation
Tween Animation takes some parameters such as start value , end value, size , time duration ,
rotation angle e.t.c and perform the required animation on that object. It can be applied to any
type of object. So in order to use this , android has provided us a class called Animation.

In order to perform animation in android , we are going to call a static function loadAnimation()
of the class AnimationUtils. We are going to receive the result in an instance of Animation
Object. Its syntax is as follows −

Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),


R.anim.myanimation);
Note the second parameter. It is the name of the our animation xml file. You have to create a new
folder called anim under res directory and make an xml file under anim folder.

This animation class has many useful functions which are listed below −

Sr.No Method & Description

start()
1
This method starts the animation.

setDuration(long duration)
2
This method sets the duration of an animation.
getDuration()
3
This method gets the duration which is set by above method

end()
4
This method ends the animation.

cancel()
5
This method cancels the animation.

In order to apply this animation to an object , we will just call the startAnimation() method of the
object. Its syntax is −

ImageView image1 = (ImageView)findViewById(R.id.imageView1);

image.startAnimation(animation);

2) Image Effects
Android allows you to manipulate images by adding different kinds of effects on the images. You
can easily apply image processing techniques to add certain kinds of effects on images. The
effects could be brightness,darkness, grayscale conversion e.t.c.

Android provides Bitmap class to handle images. This can be found under
android.graphics.bitmap. There are many ways through which you can instantiate bitmap. We are
creating a bitmap of image from the imageView.

private Bitmap bmp;


private ImageView img;
img = (ImageView)findViewById(R.id.imageView1);
BitmapDrawable abmp = (BitmapDrawable)img.getDrawable();
Now we will create bitmap by calling getBitmap() function of BitmapDrawable class. Its syntax
is given below −
bmp = abmp.getBitmap();
An image is nothing but a two dimensional matrix. Same way you will handle a bitmap. An
image consist of pixels. So you will get pixels from this bitmap and apply processing to it. Its
syntax is as follows −

for(int i=0; i<bmp.getWidth(); i++){


for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
}
}
The getWidth() and getHeight() functions returns the height and width of the matrix. The
getPixel() method returns the pixel at the specified index. Once you got the pixel, you can easily
manipulate it according to your needs.

Apart from these methods, there are other methods that helps us manipulate images more better.

Sr.N Method & description


O

1
copy(Bitmap.Config config, boolean isMutable)

This method copy this bitmap's pixels into the new bitmap

2
createBitmap(DisplayMetrics display, int width, int height, Bitmap.Config config)

Returns a mutable bitmap with the specified width and height

3
createBitmap(int width, int height, Bitmap.Config config)

Returns a mutable bitmap with the specified width and height

4
createBitmap(Bitmap src)

Returns an immutable bitmap from the source bitmap


5
extractAlpha()

Returns a new bitmap that captures the alpha values of the original

6
getConfig()

This mehtod eturn that config, otherwise return null

7
getDensity()

Returns the density for this bitmap

8
getRowBytes()

Return the number of bytes between rows in the bitmap's pixels

9
setPixel(int x, int y, int color)

Write the specified Color into the bitmap (assuming it is mutable) at the x,y coordinate

10
setDensity(int density)

This method specifies the density for this bitmap


A) To perform the animation on an image and to apply various filters on an image.
A) Perform the following animation on the image:
1. Move.
2. Rotate.
3. Expand.

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

<ImageView
android:id="@+id/imageView"
android:layout_width="153dp"
android:layout_height="231dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.264"
app:srcCompat="@drawable/doraemon" />

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.049"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.713" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ROTATE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.713" />

<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EXPAND"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.949"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.713" />
</androidx.constraintlayout.widget.ConstraintLayout>

Now we have to make xml files


STEPS: -
1) Right click on res→New→Android Resource Directory
2) After choosing new resource directory
3) Dialog box appears set it to anim from the list of values given
4) Now right click on anim folder→New→Anim resource file
5) Dialog box appears enter the file name
6) Make below 3 files by repeating step 4 and 5
move.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator"
android:fillAfter="true">

<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="700" />
</set>

rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<set
xmlns:android="http://schemas.android.com/apk/res/android">
<rotate
android:duration="6000"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" />

<rotate
android:duration="6000"
android:fromDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:startOffset="5000"
android:toDegrees="0" />

</set>

zoom.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="3.0"
android:fromYScale="0.5"
android:toYScale="3.0"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>

<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromXScale="3.0"
android:toXScale="0.5"
android:fromYScale="3.0"
android:toYScale="0.5"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>

</set>

MainActivity.java
package com.example.prac7;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView im = findViewById(R.id.imageView);
Button mvbtn = findViewById(R.id.btn1);
Button robtn = findViewById(R.id.btn2);
Button zobtn = findViewById(R.id.btn3);

mvbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add move animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move);
im.startAnimation(animation);
}
});
robtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add rotate animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.rotate);
im.startAnimation(animation);
}
});
zobtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// To add zoom animation
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.zoom);
im.startAnimation(animation);
}
});}}
OUTPUT: -
B) Apply the following effects on the image:
1. Brightness.
2. Darkness.
3. Grayscale.

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

<ImageView
android:id="@+id/iv1"
android:layout_width="320dp"
android:layout_height="356dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.246"
app:srcCompat="@drawable/scenaricview" />

<Button
android:id="@+id/btn1"
android:layout_width="138dp"
android:layout_height="48dp"
android:text="BRIGHTNESS"
android:onClick="bright"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.542"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.707" />

<Button
android:id="@+id/btn2"
android:layout_width="138dp"
android:layout_height="48dp"
android:text="DARKNESS"
android:onClick="dark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.542"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.806" />

<Button
android:id="@+id/btn3"
android:layout_width="139dp"
android:layout_height="48dp"
android:text="GRAYSCALE"
android:onClick="gray"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.544"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.905" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.prac7b;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {


private Bitmap bmp;
private Bitmap operation;
Button bright,dark,gray;
ImageView im;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bright = findViewById(R.id.btn1);
dark = findViewById(R.id.btn2);
gray = findViewById(R.id.btn3);
im =findViewById(R.id.iv1);
BitmapDrawable abmp = (BitmapDrawable) im.getDrawable();
bmp = abmp.getBitmap();
}
public void bright(View view){
operation= Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),bmp.getConfig());
for(int i=0; i<bmp.getWidth(); i++){
for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);

r = 100 + r;
g = 100 + g;
b = 100 + b;
alpha = 100 + alpha;
operation.setPixel(i, j, Color.argb(alpha, r, g, b));
}
}
im.setImageBitmap(operation);
}
public void dark(View view){
operation= Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),bmp.getConfig());

for(int i=0; i<bmp.getWidth(); i++){


for(int j=0; j<bmp.getHeight(); j++){
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
int alpha = Color.alpha(p);

r = r - 50;
g = g - 50;
b = b - 50;
alpha = alpha -50;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
im.setImageBitmap(operation);
}
public void gray(View view) {
operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), bmp.getConfig());
double red = 0.33;
double green = 0.59;
double blue = 0.11;

for (int i = 0; i < bmp.getWidth(); i++) {


for (int j = 0; j < bmp.getHeight(); j++) {
int p = bmp.getPixel(i, j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);

r = (int) red * r;
g = (int) green * g;
b = (int) blue * b;
operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b));
}
}
im.setImageBitmap(operation);
}
}

OUTPUT: -
CONCLUSION: -
From this practical I have learned to implement Android program to work with graphics and
animation.
PRACTICAL 8

AIM: - Android program to work with google maps and location

THEORY: -
Location
Android allows us to integrate google maps in our application. You can show any location on the
map , or can show different routes on the map e.t.c. You can also customize the map according to
your choices.

Sr.No Method & description

addCircle(CircleOptions options)
1
This method add a circle to the map

addPolygon(PolygonOptions options)
2
This method add a polygon to the map

addTileOverlay(TileOverlayOptions options)
3
This method add tile overlay to the map

animateCamera(CameraUpdate update)
4
This method Moves the map according to the update with an animation

clear()
5
This method removes everything from the map.
getMyLocation()

6 This method returns the currently displayed user location.

moveCamera(CameraUpdate update)

7 This method repositions the camera according to the instructions defined in the
update

setTrafficEnabled(boolean enabled)
8
This method Toggles the traffic layer on or off.

snapshot(GoogleMap.SnapshotReadyCallback callback)
9
This method Takes a snapshot of the map

stopAnimation()
10
This method stops the camera animation if there is one in progress

Calculate Distance
Developers, today, experiment and implement various kinds of features, including the feature to
calculate the distance between two points or GPS coordinates in the Android mobile app. This
can be achieved through Google Maps API. And it has made GPS Coordinate Distance
Calculator easier to find how far two GPS coordinates converter is on a map.
If you are planning to develop a travel app, location tracking, taxi booking, or any on-demand
delivery app, such a feature is very useful. Being a leading custom taxi booking solution
developer, we have developed 50+ taxi booking apps and 40+ on-demand delivery apps. In most
of these native applications, we have used this feature for real-time tracking a lot of times.
In this Android app article, we’ll develop a demo app that will display the route between two
locations.
SphericalUtil.computeDistanceBetween(loc1, loc2);

CODE: -
Building API
Steps: -
1) Goto below site
https://developers.google.com/maps/documentation/android-sdk/get-api-key
2) Click on Goto Credentials

3) Click create project


4) Enter Details

5) Click Create Credentials


6) Choose API Key

7) Below dialog box appear with API Key

8) You have to enable API by going to dashboard


APIs Section→Choose Maps SDK for Android→Choose Enable

build.gradle(:app)
Below line to be added in build.gradle which is above highlighted
implementation 'com.google.maps.android:android-maps-utils:2.3.0'

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.testpractical8">
<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: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.Testpractical8"
tools:targetApi="31">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyCmZqZXt2U-jRrSd1uSwXP8nI8EHSzo3RM" />

<activity
android:name=".MapsActivity"
android:exported="true"
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>

Following line should be added in AndroidManifest.xml refer above code

Between quotes add API KEY


In android:value=””

activity_maps.xml
<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=".MapsActivity">

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
tools:context="net.simplifiedcoding.mymapapp.MapsActivity" />

<EditText
android:id="@+id/et1"
android:layout_width="160dp"
android:layout_height="44dp"
android:ems="10"
android:hint="Longitude"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.045" />

<EditText
android:id="@+id/et2"
android:layout_width="160dp"
android:layout_height="52dp"
android:ems="10"
android:hint="Latitude"
android:inputType="textPersonName"
android:minHeight="48dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.153" />

<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LOCATOR"

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.051"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.26" />

<EditText
android:id="@+id/etn3"
android:layout_width="192dp"
android:layout_height="42dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="2nd Longitude"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.904"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.044" />

<EditText
android:id="@+id/etn4"
android:layout_width="188dp"
android:layout_height="50dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="2nd Latitude"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.905"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.155" />

<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DISTANCE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/map"
app:layout_constraintHorizontal_bias="0.768"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.26" />

</androidx.constraintlayout.widget.ConstraintLayout>

MapsActivity.java
package com.example.testpractical8;

import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.example.testpractical8.databinding.ActivityMapsBinding;
import com.google.maps.android.SphericalUtil;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;


private ActivityMapsBinding binding;
LatLng loc1;
LatLng loc2;
Double distance;
EditText edit1,edit2,edit3,edit4;
double lon,lat,lon1,lat1;
String a,b,c,d;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_maps);
Button button=findViewById(R.id.btn1);
Button button2=findViewById(R.id.btn2);
edit1=findViewById(R.id.et1);
edit2=findViewById(R.id.et2);
edit3=findViewById(R.id.etn3);
edit4=findViewById(R.id.etn4);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
a= edit1.getText().toString();
b= edit2.getText().toString();

lon=Double.parseDouble(a);
lat=Double.parseDouble(b);

LatLng sydney = new LatLng(lon,lat);


mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
Toast.makeText(MapsActivity.this, lon+" "+lat, Toast.LENGTH_LONG).show();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
c=edit3.getText().toString();
d=edit4.getText().toString();
lon1=Double.parseDouble(c);
lat1=Double.parseDouble(d);
LatLng sydney = new LatLng(lon1,lat1);
loc1 = new LatLng(lon, lat);
loc2 = new LatLng(lon1, lat1);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
distance = SphericalUtil.computeDistanceBetween(loc1, loc2);
Toast.makeText(MapsActivity.this, "Distance is \n " + String.format("%.2f", distance /
1000) + "km", Toast.LENGTH_SHORT).show();

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

// Add a marker in Sydney and move the camera


//LatLng sydney = new LatLng(lon,lat);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

}
}

OUTPUT: -
CONCLUSION: -
From this practical I have learned to implement Android program to work with google maps and
location

You might also like