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

Mobile Application Development-3161612 201290116509

ASSIGNMENT

Name : Sheth Rachit.

Enrollment No: 201290116509.

Subject : Mobile Application Development.

GMIT 1
Mobile Application Development-3161612 201290116509

PRACTICAL:-1
AIM:-Write an Android application for calculator.

Program:-
File :- 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"
android:background="#8BC34A"
android:backgroundTint="@android:color/darker_gray"
tools:context=".MainActivity">

<!-- Text View to display our basic heading of


"calculator"-->
<TextView
android:layout_width="194dp"
android:layout_height="43dp"
android:layout_marginStart="114dp"
android:layout_marginLeft="114dp"
android:layout_marginTop="58dp"
android:layout_marginEnd="103dp"
android:layout_marginRight="103dp"
android:layout_marginBottom="502dp"
android:scrollbarSize="30dp"
android:text=" Calculator"

GMIT 1
Mobile Application Development-3161612 201290116509

android:textAppearance="@style/TextAppearance.AppCompat.
Body1"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Edit Text View to input the values -->


<EditText
android:id="@+id/num1"
android:layout_width="364dp"
android:layout_height="28dp"
android:layout_marginStart="72dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="416dp"
android:background="@android:color/white"
android:ems="10"
android:hint="Number1(0)"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Edit Text View to input 2nd value-->


<EditText
android:id="@+id/num2"

GMIT 1
Mobile Application Development-3161612 201290116509

android:layout_width="363dp"
android:layout_height="30dp"
android:layout_marginStart="72dp"
android:layout_marginTop="112dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="374dp"
android:background="@android:color/white"
android:ems="10"
android:hint="number2(0)"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Text View to display result -->


<TextView
android:id="@+id/result"
android:layout_width="356dp"
android:layout_height="71dp"
android:layout_marginStart="41dp"
android:layout_marginTop="151dp"
android:layout_marginEnd="48dp"
android:layout_marginBottom="287dp"
android:background="@android:color/white"
android:text="result"
android:textColorLink="#673AB7"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"

GMIT 1
Mobile Application Development-3161612 201290116509

app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform 'sum' operation -->


<Button
android:id="@+id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSum"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform subtraction operation. -->


<Button
android:id="@+id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="210dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="113dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"

GMIT 1
Mobile Application Development-3161612 201290116509

android:onClick="doSub"
android:text="-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform division. -->


<Button
android:id="@+id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="307dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doDiv"
android:text="/"
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" />

<!-- A button to perform multiplication. -->


<Button
android:id="@+id/mul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

GMIT 1
Mobile Application Development-3161612 201290116509

android:layout_marginStart="16dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMul"
android:text="x"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- A button to perform a modulus function. -->


<Button
android:id="@+id/button"
android:layout_width="92dp"
android:layout_height="48dp"
android:layout_marginStart="113dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="206dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMod"
android:text="%(mod)"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

GMIT 1
Mobile Application Development-3161612 201290116509

<!-- A button to perform a power function. -->


<Button
android:id="@+id/pow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="113dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="210dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doPow"
android:text="n1^n2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

File :- Main_Activity.java

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

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

GMIT 1
Mobile Application Development-3161612 201290116509

EditText e1, e2;


TextView t1;
int num1, num2;

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

// a public method to get the input numbers


public boolean getNumbers() {

// defining the edit text 1 to e1


e1 = (EditText) findViewById(R.id.num1);

// defining the edit text 2 to e2


e2 = (EditText) findViewById(R.id.num2);

// defining the text view to t1


t1 = (TextView) findViewById(R.id.result);

// taking input from text box 1


String s1 = e1.getText().toString();

// taking input from text box 2


String s2 = e2.getText().toString();

// condition to check if box is not empty


if ((s1.equals(null) && s2.equals(null))
|| (s1.equals("") && s2.equals(""))) {

GMIT 1
Mobile Application Development-3161612 201290116509

String result = "Please enter a value";


t1.setText(result);

return false;
} else {
// converting string to int.
num1 = Integer.parseInt(s1);

// converting string to int.


num2 = Integer.parseInt(s2);
}

return true;
}

// a public method to perform addition


public void doSum(View v) {

// get the input numbers


if (getNumbers()) {
int sum = num1 + num2;
t1.setText(Integer.toString(sum));
}
}

// a public method to perform power function


public void doPow(View v) {

// get the input numbers


if (getNumbers()) {

GMIT 1
Mobile Application Development-3161612 201290116509

double sum = Math.pow(num1, num2);


t1.setText(Double.toString(sum));
}
}

// a public method to perform subtraction


public void doSub(View v) {

// get the input numbers


if (getNumbers()) {
int sum = num1 - num2;
t1.setText(Integer.toString(sum));
}
}

// a public method to perform multiplication


public void doMul(View v) {

// get the input numbers


if (getNumbers()) {
int sum = num1 * num2;
t1.setText(Integer.toString(sum));
}
}

// a public method to perform Division


public void doDiv(View v) {

// get the input numbers


if (getNumbers()) {

GMIT 1
Mobile Application Development-3161612 201290116509

// displaying the text in text view assigned as t1


double sum = num1 / (num2 * 1.0);
t1.setText(Double.toString(sum));
}
}

// a public method to perform modulus function


public void doMod(View v) {

// get the input numbers


if (getNumbers()) {
double sum = num1 % num2;
t1.setText(Double.toString(sum));
}
}
}

Output:

GMIT 1
Mobile Application Development-3161612 201290116509

PRACTICAL:-2
AIM:-Write an Android application to convert into
different currencies for example, Rupees to dollar.

Program:-
File :- Activity_main.xml

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


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

<TextView
android:id="@+id/textView"

GMIT 1
Mobile Application Development-3161612 201290116509

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Currency Converter"
android:textSize="36dp"
android:layout_gravity="center"
android:layout_margin="20dp"
/>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="****ENTER AMOUNT****"
android:textSize="15dp"
android:layout_margin="20dp"
/>
<EditText
android:id="@+id/currency_to_be_converted"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="From Currency:"

GMIT 1
Mobile Application Development-3161612 201290116509

android:textSize="15dp"
android:layout_margin="20dp"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
>
<Spinner
android:layout_width="250dp"
android:layout_height="40dp"
android:id="@+id/from"
android:layout_gravity="center"

/>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="To Currency:"
android:textSize="15dp"
android:layout_margin="20dp"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
>

GMIT 1
Mobile Application Development-3161612 201290116509

<Spinner
android:layout_width="250dp"
android:layout_height="40dp"
android:id="@+id/to"
android:layout_gravity="center"

/>
</RelativeLayout>

</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="162dp"
android:layout_marginLeft="162dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="162dp"
android:layout_marginRight="162dp"
android:layout_marginBottom="30dp"
android:textColor="@color/colorPrimaryDark"

android:text="Convert"
/>

<EditText
android:id="@+id/currency_converted"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Result"

GMIT 1
Mobile Application Development-3161612 201290116509

/>

</LinearLayout>

File :- Main_Activity.java

package com.example.myapplication;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.JsonObject;

import Kamal.kamalBuild;
import Kamal.kamalInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {


Button button;
EditText currencyToBeConverted;
EditText currencyConverted;
Spinner convertToDropdown;
Spinner convertFromDropdown;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

currencyConverted = (EditText) findViewById(R.id.currency_converted);

GMIT 1
Mobile Application Development-3161612 201290116509

currencyToBeConverted = (EditText)
findViewById(R.id.currency_to_be_converted);
convertToDropdown = (Spinner) findViewById(R.id.to);
convertFromDropdown = (Spinner) findViewById(R.id.from);
button = (Button) findViewById(R.id.button);

String[] dropDownList = {"USD", "INR","EUR","NZD"};


ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.support_simple_spinner_dropdown_item, dropDownList);
convertToDropdown.setAdapter(adapter);
convertFromDropdown.setAdapter(adapter);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
kamalInterface retrofitInterface =
kamalBuild.getRetrofitInstance().create(kamalInterface.class);

Call<JsonObject> call =
retrofitInterface.getExchangeCurrency(convertFromDropdown.getSelectedItem().t
oString());
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
JsonObject res = response.body();
JsonObject rates = res.getAsJsonObject("conversion_rates");
double currency =
Double.valueOf(currencyToBeConverted.getText().toString());
double multiplier =
Double.valueOf(rates.get(convertToDropdown.getSelectedItem().toString()).toStri
ng());
double result = currency * multiplier;
currencyConverted.setText(String.valueOf(result));
}

@Override
public void onFailure(Call<JsonObject> call, Throwable t) {

GMIT 1
Mobile Application Development-3161612 201290116509

});

}
});}}

import retrofit2.converter.gson.GsonConverterFactory;

public class kamalBuild {


private static Retrofit retrofit;

public static Retrofit getRetrofitInstance() {


if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl("https://api.exchangerate-api.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();

}
return retrofit;
}
}

package Kamal;

import com.google.gson.JsonObject;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface kamalInterface {


@GET("v6/1929988978e7cd9733e5e654/latest/{currency}")

GMIT 1
Mobile Application Development-3161612 201290116509

Call<JsonObject> getExchangeCurrency(@Path("currency") String currency);


}

Output:-

GMIT 1
Mobile Application Development-3161612 201290116509

PRACTICAL:-3
AIM:- Write an android application to count library overdue.

Program:-
File :- 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/textView"
android:layout_width="wrap_content"

GMIT 1
Mobile Application Development-3161612 201290116509

android:layout_height="wrap_content"
android:text="Library Overdue"
android:textSize="30sp"
android:textStyle="bold"
android:textColor="@color/purple_500"
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.064" />

<EditText
android:id="@+id/namestudent"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:minHeight="51dp"
android:hint="Enter Student Name"
android:background="@color/teal_200"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:textSize="20sp"
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.202" />

<EditText
android:id="@+id/enrollment"
android:layout_width="320dp"

GMIT 1
Mobile Application Development-3161612 201290116509

android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:minHeight="48dp"
android:hint="Enter Enrollment No."
android:background="@color/teal_200"
android:paddingLeft="15dp"
android:paddingRight="20dp"
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.293" />

<EditText
android:id="@+id/bookname"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:minHeight="48dp"
android:hint="Enter Book Name"
android:background="@color/teal_200"
android:paddingLeft="15dp"
android:paddingRight="20dp"
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.383" />

<EditText

GMIT 1
Mobile Application Development-3161612 201290116509

android:id="@+id/bookauthor"
android:layout_width="320dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:minHeight="48dp"
android:hint="Enter Author Name"
android:background="@color/teal_200"
android:paddingLeft="15dp"
android:paddingRight="20dp"
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.472" />

<!-- <EditText-->
<!-- android:id="@+id/return_date"-->
<!-- android:layout_width="320dp"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:ems="10"-->
<!-- android:inputType="textPersonName"-->
<!-- android:minHeight="48dp"-->
<!-- android:hint="Enter Return Date"-->
<!-- android:background="@color/teal_200"-->
<!-- android:paddingLeft="15dp"-->
<!-- android:paddingRight="20dp"-->
<!-- 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.472" />-->

GMIT 1
Mobile Application Development-3161612 201290116509

<Button
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:drawableEnd="@color/purple_200"
android:hint="Choose Date"
android:text=""
android:textColor="#000"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:textSize="20sp"
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.575" />

<Button
android:id="@+id/returndate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:drawableEnd="@color/purple_200"
android:hint="Choose Return Date"
android:text=""
android:textColor="#000"
android:layout_marginTop="140dp"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"

GMIT 1
Mobile Application Development-3161612 201290116509

app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.575" />

<Button
android:id="@+id/submit"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="@color/purple_200"
android:text="Submit"
android:textColor="#fff"
android:textSize="20sp"
android:layout_marginTop="200dp"
android:textStyle="bold"
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.718" />

</androidx.constraintlayout.widget.ConstraintLayout>

File :- Main_Activity.java
package com.example.library_overdue_td;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.AdaptiveIconDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

GMIT 1
Mobile Application Development-3161612 201290116509

import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

EditText student_name,enrollment,book_name,author_name;
Button dateborrow, submit,returndate;
DatePickerDialog.OnDateSetListener dateSetListener1;
DatePickerDialog.OnDateSetListener dateSetListener2;

private String dateTimeDisplay;


private Calendar calendar;
private SimpleDateFormat dateFormat;
private String date;

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

student_name = findViewById(R.id.namestudent);
enrollment = findViewById(R.id.enrollment);
book_name = findViewById(R.id.bookname);
author_name = findViewById(R.id.bookauthor);
dateborrow = findViewById(R.id.date);
submit = findViewById(R.id.submit);
returndate = findViewById(R.id.returndate);

calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("MM/dd/yyyy");
date = dateFormat.format(calendar.getTime());

GMIT 1
Mobile Application Development-3161612 201290116509

// dateTimeDisplay.setText( date);

Calendar calendar = Calendar.getInstance();


final int year = calendar.get(Calendar.YEAR);
final int month = calendar.get(Calendar.MONTH);
final int day = calendar.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat simpleDateFormat = new
SimpleDateFormat("dd/MM/yyyy");
String date =
simpleDateFormat.format(Calendar.getInstance().getTime());

dateborrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this
, android.R.style.Theme_Holo_Dialog_MinWidth
,dateSetListener1,year,month,day
);
datePickerDialog.getWindow().setBackgroundDrawable(new
ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});

returndate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this
, android.R.style.Theme_Holo_Dialog_MinWidth
,dateSetListener2,year,month,day
);
datePickerDialog.getWindow().setBackgroundDrawable(new
ColorDrawable(Color.TRANSPARENT));
datePickerDialog.show();
}
});

GMIT 1
Mobile Application Development-3161612 201290116509

dateSetListener1 = new DatePickerDialog.OnDateSetListener() {


@Override
public void onDateSet(DatePicker datePicker, int year, int month, int
day) {
month = month +1;
String date = day + "/" + month + "/" + year;
dateborrow.setText(date);

}
};
dateSetListener2 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int
day) {
month = month +1;
String date = day + "/" + month + "/" + year;
returndate.setText(date);

}
};

submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer noOfDaysBorrowed = getNoOfDaysBorrowed();
noOfDaysBorrowed -= 30;

String dayDifference;

try {
Date date1;
Date date2;
SimpleDateFormat dates = new
SimpleDateFormat("dd/MM/yyyy");
//Setting dates
date1 = dates.parse(dateborrow.getText().toString());
date2 = dates.parse(returndate.getText().toString());

GMIT 1
Mobile Application Development-3161612 201290116509

//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);

//Convert long to String


dayDifference = Long.toString(differenceDates);
Toast.makeText(MainActivity.this, ""+dayDifference,
Toast.LENGTH_SHORT).show();

// Log.e("HERE","HERE: " + dayDifference);

} catch (Exception exception) {


// Log.e("DIDN'T WORK", "exception " + exception);
}

if(noOfDaysBorrowed>0)
{

String message = getStudentInfo();


message += "\n Borrow date:"+(dateborrow.getText().toString())
+"\n Return Date:"+(returndate.getText().toString())+"\n\n Book return date is
overdue. \n Pay fine of "+noOfDaysBorrowed+" rupees.";
makeAlert(message);
}
else
{
String message = getStudentInfo();

message += "\n Borrow date:"+(dateborrow.getText().toString())


+"\n\n Book returned successfully.";
makeAlert(message);
}
}

private String getStudentInfo()


{
String student_str, enrollment_str, book_str, author_str,
student_info;

GMIT 1
Mobile Application Development-3161612 201290116509

student_str = student_name.getText().toString();
enrollment_str = enrollment.getText().toString();
book_str = book_name.getText().toString();
author_str = author_name.getText().toString();

student_info = " Student name: "+student_str+"\n Enrollment no:


"+enrollment_str+"\n Book name:"+book_str+"\n Author name:"+author_str;
return student_info;
}
private int getNoOfDaysBorrowed()
{

Date borrow_dt = new Date();

try {
borrow_dt =
simpleDateFormat.parse(dateborrow.getText().toString());
} catch (ParseException e) {
try {
borrow_dt = simpleDateFormat.parse("01/01/2022");
} catch (ParseException parseException) {
parseException.printStackTrace();
}
}

Date current_dt = Calendar.getInstance().getTime();


long timeDifference = current_dt.getTime() - borrow_dt.getTime();
int NoOfDays = (int) (timeDifference/86400000);

return NoOfDays;
}

private void makeAlert(String message)


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

GMIT 1
Mobile Application Development-3161612 201290116509

builder.setMessage(message);

builder.setPositiveButton("Ok", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"Book returned
successfully",Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"Process
completed",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});

}
}

Output:-

GMIT 1
Mobile Application Development-3161612 201290116509

PRACTICAL:-4
AIM:- Write an android application to convert a ball from size
of radius 2(colour red) to radius 4(colour blue) to radius 6
(colour green). The ball must rotate in circle for 1 minute before
changing size and colour.

GMIT 1
Mobile Application Development-3161612 201290116509

Program:-
File :- Activity_main.xml

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">

<ImageView
android:id="@+id/imageView"
android:layout_width="match_paren
t"
android:layout_height="match_paren
t"

android:background="@android:color/white" />
</RelativeLayout>

File :- Main_Activity.java

package com.myapplication;
import
android.graphics.Bitmap;
import
android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import
android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import
android.os.Handler;

GMIT 1
Mobile Application Development-3161612 201290116509

import
android.os.Looper;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
{

ImageView
img; Canvas
canvas; Paint
paint;

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

setDrawingElements
();
callDrawingThread()
;
}

private void setDrawingElements()


{
img = findViewById(R.id.imageView);
Bitmap bp = Bitmap.createBitmap(720,
1280, Bitmap.Config.ARGB_8888);
img.setImageDrawable(new BitmapDrawable(bp));

canvas = new
Canvas(bp); paint = new

Paint();
paint.setTextSize(100);
}

GMIT 1
Mobile Application Development-3161612 201290116509

private void
callDrawingThread(){
drawCircle(Color.RED,
20);

final Handler handler =


new
Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{ @Override
public void run() { img.invalidate();
drawCircle(Color.GREEN, 60);
}
},
5000
);

final Handler handler2 =


new
Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable()
{ @Override
public void run() {
img.invalidate();
drawCircle(Color.BLUE,
120);
}
}, 10000);
}

public void drawCircle(int color, int size)


{
paint.setColor(color);

canvas.drawText("Circle", 220, 450, paint);


canvas.drawCircle(360,680, size, paint);
}
}

GMIT 1
Mobile Application Development-3161612 201290116509

Output:-

PRACTICAL:-5
AIM:- Write an application to mark the daily route of travel
in map.

Program:-
File :- Activity_main.xml

GMIT 1
Mobile Application Development-3161612 201290116509

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".view.activities.MainActivity"
>

<include layout="@layout/main_toolbar"/>

<fragment
android:id="@+id/navHostFragmen
t"
android:name="androidx.navigation.fragment.NavHostFragment
" android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
app:defaultNavHost="true"
app:navGraph="@navigation/main_navigation" />

<com.google.android.material.bottomnavigation.BottomNavigationVie
w android:id="@+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"

android:layout_gravity="bottom"

app:menu="@menu/main_navigation_menu"
app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior" />

</LinearLayout>

File :- Main_Activity.java
public class MapsActivity extends

GMIT 1
Mobile Application Development-3161612 201290116509

FragmentActivityimplements OnMapReadyCallback {
private GoogleMap mMap; ArrayList markerPoints=
new ArrayList(); @Override protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps); // 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); } @Override
public void onMapReady(GoogleMap googleMap)
{ mMap = googleMap; LatLng sydney = new
LatLng(-34, 151);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in
Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom
(s ydney, 16)); mMap.setOnMapClickListener(new
GoogleMap.OnMapClickListener() { @Override public
void onMapClick(LatLng latLng) { if
(markerPoints.size() > 1) { markerPoints.clear();
mMap.clear(); } // Adding new item to the ArrayList
markerPoints.add(latLng); // Creating MarkerOptions
MarkerOptions options = new MarkerOptions(); //
Setting the position of the marker options.position(latLng);
if (markerPoints.size() == 1) {
options.icon(BitmapDescriptorFactory.defaultMarke
r( BitmapDescriptorFactory.HUE_GREEN)); } else if

(markerPoints.size() == 2) {
options.icon(BitmapDescriptorFactory.defaultMarke
r( BitmapDescriptorFactory.HUE_RED)); } // Add new
marker to the Google Map Android API V2
mMap.addMarker(options); // Checks, whether start and end
locations are captured if (markerPoints.size() >= 2)
{ LatLng origin = (LatLng) markerPoints.get(0);
LatLng dest = (LatLng) markerPoints.get(1); //
Getting URL to the Google Directions API String url =

GMIT 1
Mobile Application Development-3161612 201290116509

getDirectionsUrl(origin, dest); DownloadTask


downloadTask = new DownloadTask(); // Start downloading
json data from Google Directions API
downloadTask.execute(url); } } }); }

private class DownloadTask extends AsyncTask {


@Override protected String doInBackground(String...
url) { String data = ""; try { data =
downloadUrl(url[0]); } catch (Exception e) {
Log.d("Background Task", e.toString()); } return
data; } @Override protected void
onPostExecute(String result) {
super.onPostExecute(result); ParserTask
parserTask
= new ParserTask(); parserTask.execute(result); }
} private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap>>> {
// Parsing the data in non-ui thread @Override protected
List<List<HashMap>> doInBackground(String...
jsonData) { JSONObject jObject;
List<List<HashMap>> routes = null; try { jObject
= new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new
DirectionsJSONParser(); routes =
parser.parse(jObject); } catch (Exception e) {
e.printStackTrace(); } return routes; } @Override
protected void onPostExecute(List<List<HashMap>>
result) { ArrayList points = null;

PolylineOptions lineOptions = null; MarkerOptions


markerOptions = new MarkerOptions(); for (int i =
0; i < result.size(); i++) { points = new
ArrayList(); lineOptions = new PolylineOptions();
List<HashMap> path = result.get(i); for (int j =
0; j < path.size(); j++) { HashMap point =
path.get(j); double lat =
Double.parseDouble(point.get("lat")); double lng
= Double.parseDouble(point.get("lng")); LatLng
position = new LatLng(lat, lng);

GMIT 1
Mobile Application Development-3161612 201290116509

points.add(position); }
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true); } // Drawing polyline in the
Google Map for the i-th route
mMap.addPolyline(lineOptions);
} } private String getDirectionsUrl(LatLng
origin, LatLng dest) { // Origin of route String
str_origin = "origin=" + origin.latitude + "," +
origin.longitude; // Destination of route String str_dest
= "destination=" + dest.latitude + "," +
dest.longitude; // Sensor enabled String sensor =
"sensor=false"; String mode = "mode=driving"; //
Building the parameters to the web service String parameters =
str_origin + "&" + str_dest + "&" + sensor + "&"
+ mode; // Output format String output = "json"; //
Building the url to the web service String url =
"https://maps.googleapis.com/maps/api/directions/
"
+ output + "?" + parameters; return url; }
private String downloadUrl(String strUrl) throws
IOException { String data = ""; InputStream
iStream
= null; HttpURLConnection urlConnection = null; try
{ URL url = new URL(strUrl); urlConnection =
(HttpURLConnection) url.openConnection();
urlConnection.connect(); iStream =

urlConnection.getInputStream(); BufferedReader br =
new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer(); String line =
""; while ((line = br.readLine()) != null) {
sb.append(line); } data = sb.toString(); br.close(); }
catch (Exception e) { Log.d("Exception",
e.toString()); } finally { iStream.close();
urlConnection.disconnect(); } return data; } }

GMIT 1
Mobile Application Development-3161612 201290116509

Output:-

PRACTICAL:-6
AIM:- Write an application to record video and audio on
topic “Intent” and play the audio and video.

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

GMIT 1
Mobile Application Development-3161612 201290116509

<!--XML code for activity_main.xml-->


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d" xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<!--Heading Text View-->
<TextView
android:id="@+id/txthead"
android:layout_width="match_paret"
android:layout_height="wrap_contn"
android:layout_centerHorizontal="tr
ue"
android:text="@string/audio_record
er" android:textAlignment="center"
android:textColor="@color/black"
android:textSize="30sp" />
<!--This will display the status of our app when
we will record some audio and play that audio-
->
<TextView android:id="@+id/idTVstatus"
android:layout_width="match_parent
"
android:layout_height="wrap_content
" android:layout_marginTop="80dp"
android:text="@string/status"

GMIT 1
Mobile Application Development-3161612 201290116509

android:textAlignment="center"
android:textSize="18sp" /> <!--Linear
Layout for adding textviews in
horizontal manner--> <LinearLayout
android:layout_width="match_parent
"
android:layout_height="wrap_content "
android:layout_marginTop="140dp"
android:orientation="horizontal"
android:weightSum="4"> <!--Textview to
start audio recording drawableTop will add
above mic image--> <!Textview to stop audio
recording drawableTop will add above mic
image--> <TextView
android:id="@+id/btnRecord"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@color/purple_5 00"
android:padding="5dp"
android:text="@string/start_recording"
android:textAlignment="center"
android:textColor="@color/white" />
<TextView android:id="@+id/btnStop"
android:layout_width="0dp"
android:layout_height="wrap_cont ent"
android:layout_margin="5dp"
android:layout_weight="1"

GMIT 1
Mobile Application Development-3161612 201290116509

android:background="@color/purpl e_500"
android:padding="5dp"
android:text="@string/stop_recordi ng"
android:textAlignment="center"
android:textColor="@color/white" /> <!-
Textview to play audio that is recorded
drawableTop will add above mic image-->
<TextView android:id="@+id/btnPlay"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@color/purple_500 "
android:padding="5dp"
android:text="@string/play_recording"
android:textAlignment="center"
android:textColor="@color/white" /> <!
Textview to pause the play of audio recording
drawableTop will add above mic image-->
<TextView android:id="@+id/btnStopPlay"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@color/purple_5 00"
android:lines="2" android:padding="5dp"
android:text="@string/stop_playing"
android:textAlignment="center"

GMIT 1
Mobile Application Development-3161612 201290116509

android:textColor="@color/white" />
</LinearLayout> <TextView
android:id="@+id/head"
android:layout_width="match_paren
t"
android:layout_height="wrap_conten
t"
android:layout_centerHorizontal="tr
ue" android:text="Video Recorder"
android:layout_marginTop="240dp"
android:textAlignment="center"
android:textColor="@color/black"
android:textSize="30sp" />
<LinearLayout
android:id="@+id/layoutlinear"
android:layout_width="match_paren
t"
android:layout_height="wrap_conten
t"
android:layout_marginTop="300dp"
android:orientation="horizontal"
android:weightSum="4"> <Button
android:id="@+id/record_video"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conten
t"
android:layout_marginLeft="130dp"
android:text="Record Video" />
</LinearLayout> <VideoView
android:layout_marginTop="20dp"

GMIT 1
Mobile Application Development-3161612 201290116509

android:id="@+id/video_view"
android:layout_width="350dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_below="@id/layoutlinear
" />
</RelativeLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.practical_7">
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/
>
<uses-permission android:name="android.permission.STORAGE"/>
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_rou nd"
android:supportsRtl="true"
android:theme="@style/Theme.Practical_7"> <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>

GMIT 1
Mobile Application Development-3161612 201290116509

</activity>
</application>
</manifest>

MainActivity.java package com.example.practical_7; i


mport static
android.Manifest.permission.RECORD_AUDIO;
import static
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
; import androidx.appcompat.app.AppCompatActivity; import
androidx.core.app.ActivityCompat; import
androidx.core.content.ContextCompat; import
android.content.Intent; import
android.content.pm.PackageManager; import
android.media.MediaPlayer; import
android.media.MediaRecorder; import android.net.Uri; import
android.os.Bundle; import android.os.Environment; import
android.provider.MediaStore; import android.util.Log; import
android.view.View; import android.widget.Button; import
android.widget.MediaController; import
android.widget.TextView; import android.widget.Toast; i
mport android.widget.VideoView; import java.io.File;
import java.io.IOException; public class MainActivity
extends AppCompatActivity { private TextView startTV,
stopTV, playTV, stopplayTV, statusTV,statusvideo;
private Button startrecording, playrecording; private
MediaRecorder mRecorder; private MediaPlayer mPlayer;
private static String mFileName = null; public static final
int
REQUEST_AUDIO_PERMISSION_CODE =

GMIT 1
Mobile Application Development-3161612 201290116509

1;
private static final int VIDEO_CAPTURE = 101; static
final int REQUEST_VIDEO_CAPTURE = 1;
Uri videoUri; @Override protected void onCreate(Bundle
savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); statusTV =
findViewById(R.id.idTVstatus); startTV =
findViewById(R.id.btnRecord); stopTV =
findViewById(R.id.btnStop); playTV =
findViewById(R.id.btnPlay); stopplayTV =
findViewById(R.id.btnStopPlay);
stopTV.setBackgroundColor(getResources().getColor(R.color.gr
a
y));
playTV.setBackgroundColor(getResources().getColor(R.color.gra
y));
stopplayTV.setBackgroundColor(getResources().getColor(R.color .gray)
); startrecording = findViewById(R.id.record_video);
startTV.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) { // start recording method will // start the
recording of audio.
startRecording();
} });
stopTV.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View v) { // pause
Recording method will //
pause the recording of audio.
pauseRecording();
} });
playTV.setOnClickListener(new View.OnClickListener() {

GMIT 1
Mobile Application Development-3161612 201290116509

@Override public void


onClick(View v) { // play audio
method will play // the audio
which we have recorded
playAudio();
} });
stopplayTV.setOnClickListener(new View.OnClickListener() {
@Override public void
onClick(View v) { //
pause play method
will // pause the play of
audio pausePlaying();
}
});
startrecording.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View
view) { startRecordingVideo(); }
});
}
public void startRecordingVideo() { Intent
takeVideoIntent = new
Intent(MediaStore.ACTION_VIDEO_CAPTURE); if
(takeVideoIntent.resolveActivity(getPackageManager()) != null)
{ startActivityForResult(takeVideoIntent,
REQUEST_VIDEO_CAPTURE);
}
} protected void onActivityResult(int requestCode, int resultCode,
Intent intent){ super.onActivityResult(requestCode, resultCode,
intent); VideoView mVideoView = (VideoView)
findViewById(R.id.video_view); if (requestCode ==
REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri videoUri = intent.getData(); mVideoView.setVideoURI(videoUri);
mVideoView.start();

GMIT 1
Mobile Application Development-3161612 201290116509

}
} private void
startRecording() {
// check permission method is used to
check // that the user has granted
permission // to record nd store the audio. if
(CheckPermissions()) {
// setbackgroundcolor method will change // the background color of text
view.
stopTV.setBackgroundColor(getResources().getColor(R.color.purple_200))
; startTV.setBackgroundColor(getResources().getColor(R.color.gray));
playTV.setBackgroundColor(getResources().getColor(R.color.gray));
stopplayTV.setBackgroundColor(getResources().getColor(R.color.gray));
// we are here initializing our filename variable
// with the path of the recorded audio file. mFileName =
Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/AudioRecording.3gp";
// below method is used to initialize // the media recorder clss mRecorder
= new MediaRecorder(); // below method is used to set the audio //
source which we are using a mic.

mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC)
;
// below method is used to set
// the output format of the audio.
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
// below method is used to set the
// audio encoder for our recorded audio.
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
// below method is used to set the
// output file location for our recorded audio
mRecorder.setOutputFile(mFileName);
try {
// below method will prepare //
our audio recorder class

GMIT 1
Mobile Application Development-3161612 201290116509

mRecorder.prepare();
} catch (IOException e) {
Log.e("TAG", "prepare() failed");
}
// start method will start //
the audio recording.
mRecorder.start();
statusTV.setText("Recording
Started");
} else
{
// if audio recording permissions are
// not granted by user below method will
// ask for runtime permission for mic and storage.
RequestPermissions();
}
}
@Override public void onRequestPermissionsResult(int
requestCode, String[] permissions, int[] grantResults) { // this
method is called when user will // grant the permission for audio
recording. super.onRequestPermissionsResult(requestCode,
permissions, grantResults); switch (requestCode) {
case REQUEST_AUDIO_PERMISSION_CODE:
if (grantResults.length > 0) { boolean
permissionToRecord = grantResults[0] ==
PackageManager.PERMISSION_GRANTED
;
boolean permissionToStore = grantResults[1]
==PackageManager.PERMISSION_GRANT
ED;
if (permissionToRecord && permissionToStore) {
Toast.makeText(getApplicationContext(), "Permission Granted",
Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(getApplicationContext(), "Permission Denied",
Toast.LENGTH_LONG).show();

GMIT 1
Mobile Application Development-3161612 201290116509

}}
break; }
}
public boolean CheckPermissions() { // this method is used to check
permission int result =
ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE); int result1 =
ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO); return result ==
PackageManager.PERMISSION_GRANTED && result1 ==
PackageManager.PERMISSION_GRANTED;
} private void
RequestPermissions() {
// this method is used to request the
// permission for audio recording and storage.
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{RECORD_AUDIO, WRITE_EXTERNAL_STORAGE},
REQUEST_AUDIO_PERMISSION_CODE);
} public void playAudio()
{ stopTV.setBackgroundColor(getResources().getColor(R.color.gray));
startTV.setBackgroundColor(getResources().getColor(R.color.purple_20
0));
playTV.setBackgroundColor(getResources().getColor(R.color.gray));
stopplayTV.setBackgroundColor(getResources().getColor(R.color.purple
_20
0));
// for playing our recorded
audio // we are using media
player class. mPlayer = new
MediaPlayer();
try {
// below method is used to set the // data
source which will be our file name
mPlayer.setDataSource(mFileName); //
below method will prepare our media

GMIT 1
Mobile Application Development-3161612 201290116509

player mPlayer.prepare(); // below


method will start our media player.
mPlayer.start();
statusTV.setText("Recording Started
Playing");
} catch (IOException e) {
Log.e("TAG", "prepare() failed");
}
}
public void pauseRecording()
{ stopTV.setBackgroundColor(getResources().getColor(R.color.gray));
startTV.setBackgroundColor(getResources().getColor(R.color.purple_200));
playTV.setBackgroundColor(getResources().getColor(R.color.purple_200));
stopplayTV.setBackgroundColor(getResources().getColor(R.color.purple_20
0));
// below method will
stop // the audio
recording.
mRecorder.stop(); //
below method will
release // the media
recorder class.
mRecorder.release();
mRecorder = null;
statusTV.setText("Recordi
ng Stopped");
} public void
pausePlaying() {
// this method will release the media player //
class and pause the playing of our recorded
audio.

GMIT 1
Mobile Application Development-3161612 201290116509

mPlayer.release(); mPlayer = null;


stopTV.setBackgroundColor(getResource().getColor(R.color.gray));
startTV.setBackgroundColor(getResources().getColor(R.color.purple
_200);
playTV.setBackgroundColor(getResources().getColor(R.color.purple
_200));
stopplayTV.setBackgroundColor(getResources().getColor(R.color.gr
ay)); statusTV.setText("Recording Play Stopped");
}
}

Output:-

GMIT 1
Mobile Application Development-3161612 201290116509

GMIT 1

You might also like