Mad Ex 1to10

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

Experiment No: 10

TITLE: Write an Android application to perform text to speech and generate apk file.

EXCERCISE:
1) Write an Android application to perform text to speech and generate apk file.
 Code :
 activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="16dp"
android:paddingTop="16dp" android:paddingRight="16dp" android:paddingBottom="16dp"
tools:context=".MainActivity">

<EditText android:id="@+id/inputText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text to speak"
android:layout_marginBottom="16dp"
android:inputType="textMultiLine"
android:maxLines="3"
android:layout_above="@id/speakButton" />

<Button android:id="@+id/speakButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true" />

</RelativeLayout>

→. MainActivity.java :

package com.example.practical10;

import androidx.appcompat.app.AppCompatActivity; import


android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import
android.view.View; import android.widget.Button; import android.widget.EditText; import
java.util.Locale; public class MainActivity extends AppCompatActivity implements OnInitListener {

private TextToSpeech textToSpeech;


private EditText inputText; private Button
speakButton;
@Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textToSpeech = new TextToSpeech(this, this); inputText =


findViewById(R.id.inputText); speakButton =
findViewById(R.id.speakButton);

speakButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String textToRead = inputText.getText().toString(); if
(!textToRead.isEmpty()) {
textToSpeech.speak(textToRead, TextToSpeech.QUEUE_FLUSH,
null, null);
}
}
});
}

@Override
public void onInit(int status) { if (status ==
TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);

if (result == TextToSpeech.LANG_MISSING_DATA || result ==


TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TextToSpeech", "Language is not supported or missing data");
} else { speakButton.setEnabled(true);
}
} else {
Log.e("TextToSpeech", "Initialization failed");
}
}

@Override
protected void onDestroy() { if
(textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
}

→. OUTPUT :
QUIZ:
Answer the Followings:
1. What is an apk file.
→. An APK file (Android Package Kit file format) is the file format for applications used
on the Android operating system (OS). An APK file contains all the data an app needs,
including all of the software program's code, assets and resources.
2. Write steps to publishing android applications.
→. Steps to publishing applications :
1. Prepare
2. Keystore
3. Release Build
4. Sign
5. Optimize
6. Release APK
7. Developer Account
8. Store Listing
9. Upload APK
10. Pricing
11. In-App Purchases
12. Publish
Experiment No: 9

TITLE: Write an android application to perform API calling with Retrofit.

EXCERCISE:
1) Write an android application to perform API calling with Retrofit.

→. Answer:
import android.os.Bundle; import
android.util.Log; import
android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call; import retrofit2.Callback; import
retrofit2.Response; import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory; public

class MainActivity extends AppCompatActivity {

private TextView textViewResult;


private JsonPlaceholderApi jsonPlaceholderApi;

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

textViewResult = findViewById(R.id.text_view_result);

// Retrofit setup
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/") // Base URL of the API
.addConverterFactory(GsonConverterFactory.create()) // Gson converter
factory for JSON parsing
.build();

// Create instance of the API interface


jsonPlaceholderApi = retrofit.create(JsonPlaceholderApi.class);

// Call API method and handle response


Call<Post> call = jsonPlaceholderApi.getPost(1); // Example call to retrieve a post
with ID 1 call.enqueue(new Callback<Post>() { @Override
public void onResponse(Call<Post> call, Response<Post> response)
{ if (!response.isSuccessful()) { textViewResult.setText("Code:
"+
response.code()); return;
}

Post post =
response.body(); String
content = ""; if (post != null) { content += "ID: "
+ post.getId() + "\n"; content += "User ID: " +
post.getUserId() + "\n"; content += "Title: " +
post.getTitle() + "\n";
content += "Text: " + post.getText() + "\n\n";
}
textViewResult.setText(content);
}

@Override
public void onFailure(Call<Post> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
}
}
→. Output :

QUIZ:
Answer the Followings:

1. What is an API and an API call.


→. Application programming interfaces (APIs) are a way for one program to interact
with another. API calls are the medium by which they interact.
2. What are other ways except retrofit library to make an API call from
android application.
→. Other ways to make API calls in Android include using HttpURLConnection,
Volley, OkHttp, AsyncTask, Kotlin Coroutines with HttpClient, and libraries like
Apollo-Android for GraphQL.
Experiment No: 8
TITLE: Write an android application to perform CRUD operation on Firebase.

EXCERCISE:
1) Write an android application to perform CRUD operation on Firebase.

→. Answer:
import android.os.Bundle; import
android.text.TextUtils; import
android.view.View; import
android.widget.Button; import
android.widget.EditText; import
android.widget.Toast;

import androidx.annotation.NonNull; import


androidx.appcompat.app.AppCompatActivity;

import com.google.firebase.database.DataSnapshot; import


com.google.firebase.database.DatabaseError; import
com.google.firebase.database.DatabaseReference; import
com.google.firebase.database.FirebaseDatabase; import
com.google.firebase.database.ValueEventListener; public class
MainActivity extends AppCompatActivity {

private EditText editTextName, editTextAge; private Button buttonAdd,


buttonUpdate, buttonDelete, buttonRetrieve; private DatabaseReference
databaseReference;

@Override protected void onCreate(Bundle


savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editTextName = findViewById(R.id.editTextName);
editTextAge = findViewById(R.id.editTextAge);
buttonAdd = findViewById(R.id.buttonAdd);
buttonUpdate = findViewById(R.id.buttonUpdate);
buttonDelete = findViewById(R.id.buttonDelete);
buttonRetrieve = findViewById(R.id.buttonRetrieve);

databaseReference =
FirebaseDatabase.getInstance().getReference().child("Users");
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addUser();
}
});

buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateUser();
}
});

buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteUser();
}
});

buttonRetrieve.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { retrieveUsers();
}
});
}

private void addUser() {


String name = editTextName.getText().toString().trim();
String ageStr = editTextAge.getText().toString().trim();

if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(ageStr)) {


int age = Integer.parseInt(ageStr);
String id = databaseReference.push().getKey();

if (id != null) {
User user = new User(id, name, age);
databaseReference.child(id).setValue(user);
Toast.makeText(this, "User added successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Error generating user ID",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Please enter name and age",
Toast.LENGTH_SHORT).show();
}
}

private void updateUser() {


String id = editTextName.getText().toString().trim();
String name = editTextName.getText().toString().trim();
String ageStr = editTextAge.getText().toString().trim();

if (!TextUtils.isEmpty(id) && !TextUtils.isEmpty(name) &&


!TextUtils.isEmpty(ageStr)) { int age =
Integer.parseInt(ageStr); User user = new
User(id, name, age);
databaseReference.child(id).setValue(user);
Toast.makeText(this, "User updated successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter user ID, name, and age",
Toast.LENGTH_SHORT).show();
}
}

private void deleteUser() {


String id = editTextName.getText().toString().trim();

if (!TextUtils.isEmpty(id)) { databaseReference.child(id).removeValue();
Toast.makeText(this, "User deleted successfully",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter user ID",
Toast.LENGTH_SHORT).show();
}
}

private void retrieveUsers() { databaseReference.addListenerForSingleValueEvent(new


ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
StringBuilder stringBuilder = new StringBuilder();
for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
User user = dataSnapshot.getValue(User.class);
if (user != null) { stringBuilder.append("ID:
").append(user.getId()).append("\n");
stringBuilder.append("Name:
").append(user.getName()).append("\n"); stringBuilder.append("Age:
").append(user.getAge()).append("\n\n");
}
}
Toast.makeText(MainActivity.this, stringBuilder.toString(),
Toast.LENGTH_LONG).show();
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
Toast.makeText(MainActivity.this, "Error retrieving users",
Toast.LENGTH_SHORT).show();
}
});
}
}

→. Output :
QUIZ:

Answer the Followings:


1) Describe firebase database.
→. The Firebase Realtime Database is a cloud-hosted NoSQL database that lets you store
and sync data between your users in real time.
2) What are CRUD operations.
→. CRUD is an acronym that comes from the world of computer programming and
refers to the four functions that are considered necessary to implement a persistent
storage application: create, read, update and delete.
Experiment No: 7
TITLE: Write an android application to insert Customer Details (cID, cName, cOrderID) in
SQLite Database in Android.

EXCERCISE:
1) Write an android application to insert Customer Details (cID, cName,cOrderID) in SQLite Database in
Android.

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

<androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerview"
android:layout_width="409dp" android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/add_button" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginEnd="45dp"
android:layout_marginBottom="43dp"

android:background="@color/black"
android:clickable="true" android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0" app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.988"
app:srcCompat="@drawable/baseline_add"/>
</androidx.constraintlayout.widget.ConstraintLayout> →. MainActivity.java :

package com.example.customerdetails;

import androidx.appcompat.app.AppCompatActivity; import


androidx.recyclerview.widget.RecyclerView;

import android.content.Intent; import


android.os.Bundle; import
android.view.View;

import com.google.android.material.floatingactionbutton.FloatingActionButton; public class


MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

recyclerView = findViewById(R.id.recyclerview); add_button =


findViewById(R.id.add_button);
add_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddActivity.class); startActivity(intent);
}
});
}
}
→. Activity_add.xml :

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".AddActivity" android:padding="30dp">

<EditText android:id="@+id/c_ID_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="148dp" android:ems="10"
android:hint="Customer id" android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.315"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText android:id="@+id/c_NAME_input" android:layout_width="match_parent"


android:layout_height="wrap_content" android:layout_marginTop="24dp"
android:ems="10" android:hint="Customer name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.315"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/c_ID_input" />

<EditText android:id="@+id/c_ORDERID_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:ems="10"
android:hint="Customer Orderid"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.315"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/c_NAME_input"/>

<Button android:id="@+id/add_button"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginTop="40dp" android:text="ADD"
android:textAllCaps="false" android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/c_ORDERID_input"/>
</androidx.constraintlayout.widget.ConstraintLayout>

→. AddActivity.java package
com.example.customerdetails;

import androidx.appcompat.app.AppCompatActivity; import


android.os.Bundle; import android.view.View; import
android.widget.Button; import android.widget.EditText; public class
AddActivity extends AppCompatActivity {

EditText c_NAME_input, c_ORDER_input;


Button add_button;

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

c_NAME_input = findViewById(R.id.c_NAME_input); c_ORDER_input =


findViewById(R.id.c_ORDERID_input); add_button =
findViewById(R.id.add_button); add_button.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
MyDatabaseHelper mydb = new
MyDatabaseHelper(AddActivity.this); mydb.addCustomer(c_NAME_input.getText().toString().trim(),
Integer.valueOf(c_ORDER_input.getText().toString().trim()));
}
});
}
}

→. MyDatabaseHelper.java :

package com.example.customerdetails;

import android.content.ContentValues; import


android.content.Context; import
android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper; import
android.widget.Toast;
import androidx.annotation.Nullable;
public class MyDatabaseHelper extends SQLiteOpenHelper { private Context context;
private static final String DATABASE_NAME =" Customer_library.db"; private static int
DATABASE_VERSION = 1;

private static final String TABLE_NAME ="Customer"; private static final String
COLUMN_ID ="c_ID"; private static final String COLUMN_NAME ="c_NAME";
private static final String COLUMN_ORDERID ="c_ORDERID";

public MyDatabaseHelper(@Nullable Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,
"+
COLUMN_NAME + " TEXT, " +
COLUMN_ORDERID + " INTEDER);"; db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
void addCustomer(String c_NAME,Integer c_ORDERID){
SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv
= new ContentValues(); cv.put(COLUMN_NAME, c_NAME);
cv.put(COLUMN_ORDERID, c_ORDERID); long result =
db.insert(TABLE_NAME,null,cv); if(result == -1){
Toast.makeText(context,"Failed",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context,"Added
Successfully",Toast.LENGTH_SHORT).show();
}

}
}

→ OUTPUT :
QUIZ:

Answer the Followings:


1) SQLite is a ?
→. C. Relational database
2) What do you mean by NoSQL? How it is differ from relational database?
→. NoSQL is a flexible, schema-less database category designed for dynamic data,
offering horizontal scalability and sacrificing some ACID properties.

→. Differences: NoSQL allows flexible data models, dynamic schemas, and horizontal
scalability, while traditional RDBMS relies on fixed schemas, vertical scaling, and strong
ACID properties.
Experiment No: 6

TITLE: Write an application to record video and audio on topic ‚Intent and play the audio and
video.

EXCERCISE:
1) Write an application to record video and audio on topic ‚Intent and play the audio and video.
→. CODE :
→. avtivity_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">

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerInParent="true"
android:layout_marginStart="163dp"
android:layout_marginTop="200dp"
android:onClick="btnRecordPressed"
android:text="Record"
android:layout_centerVertical="true" app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.0"
tools:layout_editor_absoluteX="62dp" />

<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:onClick="btnStopPressed"
android:text="Stop"
android:layout_centerVertical="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.566"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:layout_marginEnd="16dp"
android:onClick="btnplayPressed" android:text="play"
android:layout_centerVertical="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout> →.
MainActivity.java :

package com.example.voicerecorder;

import androidx.appcompat.app.AppCompatActivity; import


androidx.core.app.ActivityCompat; import
androidx.core.content.ContextCompat;

import android.Manifest; import


android.content.ContextWrapper; import
android.content.pm.PackageManager; import
android.media.MediaPlayer; import
android.media.MediaRecorder; import android.os.Bundle;
import android.os.Environment; import
android.view.View; import android.widget.Toast;

import java.io.File; import


java.io.IOException;

public class MainActivity extends AppCompatActivity {

private static int MICROPHONE_PERMISSION_CODE =200;


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

if(isMicrophonePresent()){ getMicrophonePermission();
}
}

public void btnRecordPressed(View v) { try {


mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(getRecordingfilepath());
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.prepare(); mediaRecorder.start();

Toast.makeText(this,"RECORDING is
STRATING",Toast.LENGTH_LONG).show();
}
catch (Exception e){
e.printStackTrace();
}

}
public void btnStopPressed(View v) { mediaRecorder.stop();
mediaRecorder.release(); mediaRecorder = null;

Toast.makeText(this,"RECORDING is STOPPED.",Toast.LENGTH_LONG).show();
}
public void btnPlayPressed(View v) throws IOException { try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(getRecordingfilepath());
mediaPlayer.prepare(); mediaPlayer.start();

Toast.makeText(this,"RECORDING is
PLAYING.",Toast.LENGTH_LONG).show();
}
catch (Exception e){
e.printStackTrace();
}

private boolean isMicrophonePresent() {

if(this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_MICROP
HONE)){
return true;
}
else { return false;
}
}

private void getMicrophonePermission(){ if(ContextCompat.checkSelfPermission(this,


Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.RECORD_AUDIO},MICROPHONE_PERMISSION_CODE );
}
}
private String getRecordingfilepath(){
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); File musicDriectory =
contextWrapper.getExternalFilesDir(Environment.DIRECTORY_MUSIC); File file = new
File(musicDriectory,"testrecordingfile" +"mp3"); return file.getPath();

}
}

→. OUTPUT :
QUIZ:

Answer the Following:


1) What is android media player.
→. The MediaPlayer API is a built-in Android class used for playing audio and video files.
It supports several different media formats and can play media files that are stored in your
application's resources, on the local file system, or at a URI accessible over the Internet.
2) Describe the API or classes to handle audio and video in Android.
→. Audio:
1. MediaPlayer class:
- Handles audio playback.
2. AudioManager class:
- Manages audio settings.
3. SoundPool class:
- Manages short audio clips.
→. Video:
1. VideoView class:
- Displays videos.
2. MediaPlayer class (for video):
- Handles video playback.
3. MediaController class:
- Provides video playback controls.
Experiment No: 5

TITLE: Write an application to mark the daily route of travel in map.

EXCERCISE:
1) Write an application to mark the daily route of travel in map.
→ 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">

<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Show Map"
android:id="@+id/showMap"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout> →.

MainActivity.java : package com.example.routeoftravel; import

androidx.appcompat.app.AppCompatActivity;

import android.content.Intent; import


android.os.Bundle; import
android.view.View; import
android.widget.Button; public class
MainActivity extends AppCompatActivity
{
Button showMap; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); showMap =
findViewById(R.id.showMap);

showMap.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MapActivity.class); startActivity(intent);
}
});
}
}

→. Activity_map.xml :

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


<fragment 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:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"

tools:context=".MapActivity" tools:ignore="MissingClass">

</fragment> →.
mapActivity.java :
package com.example.routeoftravel;

import androidx.annotation.NonNull; import


androidx.appcompat.app.AppCompatActivity; import
androidx.fragment.app.FragmentActivity;

import android.os.Bundle; import


android.widget.FrameLayout; import
com.google.android.gms.maps.CameraUpdateFact
ory; import
com.google.android.gms.maps.GoogleMap; import
com.google.android.gms.maps.OnMapReadyCallb
ack; import
com.google.android.gms.maps.SupportMapFragm
ent; import
com.google.android.gms.maps.model.LatLng;
import
com.google.android.gms.maps.model.MarkerOptio
ns;

public class MapActivity extends FragmentActivity implements OnMapReadyCallback {

GoogleMap gMap;
FrameLayout map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map); map =
findViewById(R.id.map);

SupportMapFragment mapFragment = (SupportMapFragment)


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

@Override
public void onMapReady(@NonNull GoogleMap googleMap) { this.gMap = googleMap;

LatLng mapINDIA = new LatLng(20.5937,78.9629);


this.gMap.addMarker(new MarkerOptions().position(mapINDIA).title("Marker
in INDIA")); this.gMap.moveCamera(CameraUpdateFactory.newLatLng(mapINDIA));

}
}

→. Output :

QUIZ:

Answer the Followings:


1) Why should you keep your API key secure?

→. This is for a few reasons: API keys can't authenticate the individual user making the
request, only the project or application sending the request. API keys are like passwords —
only effective if the owner stores them securely.
Experiment No: 4

TITLE: Write an Android application that creates a simple Dialog box with only 1 button.

EXCERCISE:

1) Write an Android application that creates a simple Dialog box with only 1 button.
 Code :
 activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">

<Button android:id="@+id/showDialogButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Dialog"
android:layout_centerInParent="true"/>
</RelativeLayout> →.
MainActivity.java
package com.example.practical4;

import android.app.AlertDialog; import


android.content.DialogInterface; import
android.os.Bundle; import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity; public class

MainActivity extends AppCompatActivity {

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

Button showDialogButton = findViewById(R.id.showDialogButton);

showDialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) { // Call the
function to show the dialog
showDialog();
}
});
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Simple Dialog")
.setMessage("This is a simple dialog with one button.");

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


@Override
public void onClick(DialogInterface dialog, int which) { dialog.dismiss();
}
});

builder.create().show();
}
}

→. OUTPUT :
QUIZ:

Answer the Followings:


1) What is a Dialog Box?

→ . A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog doesn't fill the screen and is normally used for modal events that
require users to take an action before they can proceed.

2) Explain each type of Dialog Box.


→. type of Dialog Box :
1. Alert Dialog:
- Info or decision prompt.
- Title, message, buttons.
2. Progress Dialog:
- Shows operation progress.
- Title, progress bar, optional message
3. Date Picker Dialog:
- Picks a date.
- Date picker interface.
4. Time Picker Dialog:
- Picks a time.
- Time picker interface.
5. Custom Dialog:
- Custom layout and components.
- User-defined views.
3) Enlist and define types of Menus in android.
→. Here are the main types of menus:
1. Options Menu: A standard menu that appears when the user presses the
hardware "Menu" button or taps the overflow icon on the action bar.
2. Context Menu: A floating menu that appears in response to a long-press on a
UI element, such as a list item or view.
3. Popup Menu: A menu that displays a list of items in a floating window
anchored to a specific view.
4. Submenu: A menu that contains additional items or submenus within an
existing menu.
5. Navigation Drawer:A slide-in menu that is usually hidden off-screen and can
be revealed by swiping from the left edge or tapping a button.
6. Bottom Navigation Menu:A menu that typically appears at the bottom of the
screen and contains a set of tabs or icons for navigation.
Experiment No: 3

TITLE: Write an Android application for calculator.


EXCERCISE:
1) Write an Android application for calculator.
→. Code :
→. activity_main.xml :

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


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

<EditText android:id="@+id/editTextN1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Number 1"
android:inputType="numberDecimal" />

<EditText android:id="@+id/editTextN2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextN1"
android:layout_marginTop="16dp" android:hint="Enter
Number 2" android:inputType="numberDecimal" />

<Button android:id="@+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextN2"
android:layout_marginTop="16dp"
android:text="Add" />
<Button android:id="@+id/btnSub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnAdd"
android:layout_marginTop="16dp"
android:text="Subtract" />

<Button android:id="@+id/btnMul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnSub"
android:layout_marginTop="16dp"
android:text="Multiply" />
<Button android:id="@+id/btnDiv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnMul"
android:layout_marginTop="16dp"
android:text="Divide" />

<Button android:id="@+id/btnClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnDiv"
android:layout_marginTop="16dp"
android:text="Clear" />

<Button android:id="@+id/btnEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnClear"
android:layout_marginTop="16dp"
android:text="Equal" />

<TextView android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnEqual"
android:layout_marginTop="16dp" android:text="Result: "
/>

</RelativeLayout>

→. MainActivity.java :

package com.example.calculator;

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;

public class MainActivity extends AppCompatActivity {

Button buttonAdd, buttonSub, buttonMul, buttonDiv, buttonClear, buttonEqual;


EditText editTextN1, editTextN2;
TextView textView; float num1,
num2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
buttonAdd = findViewById(R.id.btnAdd); buttonSub =
findViewById(R.id.btnSub); buttonMul =
findViewById(R.id.btnMul); buttonDiv =
findViewById(R.id.btnDiv); buttonClear =
findViewById(R.id.btnClear); buttonEqual =
findViewById(R.id.btnEqual);

editTextN1 = findViewById(R.id.editTextN1); editTextN2 =


findViewById(R.id.editTextN2);

textView = findViewById(R.id.resultTextView); buttonAdd.setOnClickListener(new


View.OnClickListener() {
@Override public void onClick(View
v) {
performOperation("+");
}
});

buttonSub.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View
v) {
performOperation("-");
}
});

buttonMul.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View
v) {
performOperation("*");
}
});

buttonDiv.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View
v) {
performOperation("/");
}
});

buttonClear.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View
v) { clearFields();
}
});

buttonEqual.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View
v) {
calculateResult();
}
}); }
private
void
perform
Operati
on(Strin
g
operator
) { try {
num1 = Float.parseFloat(editTextN1.getText().toString()); num2 =
Float.parseFloat(editTextN2.getText().toString());
} catch (NumberFormatException e) {
Toast.makeText(this, "Invalid number format",
Toast.LENGTH_SHORT).show();
return;
}

switch (operator) {
case "+": textView.setText("Result: " + (num1 + num2)); break;

case "-": textView.setText("Result: " + (num1 - num2)); break;

case "*": textView.setText("Result: " + (num1 * num2)); break;

case "/": if (num2 != 0)


{
textView.setText("Result: " + (num1 / num2));
} else {
Toast.makeText(this, "Cannot divide by zero",
Toast.LENGTH_SHORT).show();
}
break;
}
}

private void clearFields() { editTextN1.setText("");


editTextN2.setText("");
textView.setText("Result: ");
}

private void calculateResult() {


}
}

→. Output :
QUIZ:

Answer the Followings:

1) Explain EditText.
→. EditText is a Widget of user interface (UI) used to retrieve and modify text data from a user
in an Android app. EditText is a subclass of TextView that inherit all the property of TextView.
Nowadays, EditText is represented with the PlainText element in UI, which displays an empty
text field while designing the app.

2) Explain Toggle Button in Android.

→ Android Toggle Button is used to display on and off state on a button. Switch is another
type of toggle button that's predominantly used since Android 4.0. Android Switch provides a
slider control. Both ToggleButton and Switch are subclasses of CompoundButton class.
Experiment No: 2
TITLE: Write an Android application to make a Button to open a new activity from another
activity.

EXCERCISE:
1) Write an Android application to make a Button to open a new activity from another
activity.
→. Code :
→.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">

<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity_1" android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="307dp"
android:text="open activity_2" />

</RelativeLayout>

→. MainActivity.java :
package com.example.myapplication; import

androidx.appcompat.app.AppCompatActivity;

import android.content.Intent; import


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

public class MainActivity extends AppCompatActivity { private Button button;


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

button = (Button) findViewById(R.id.button);


button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { openActivity2();
}
});
}
public void openActivity2() {
Intent intent = new Intent(this, MainActivity2.class); startActivity(intent);

}
}

→. Activity_main2.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">

<TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Activity_2" android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />

</RelativeLayout>

→. MainActivity2.java :

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;

public class MainActivity2 extends AppCompatActivity {

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

→. Output :
QUIZ:
Answer the Followings:
1) What are OnResume() and OnPause() call back methods in Activity life cycle.
→. After a fragment has been created successfully it goes through the following stages: The
onStart() method is called when the fragment is now visible to the user followed by the
onResume() method, which is called when the fragment is interactive. The onPause() method
is called once the fragment is no longer interactive.
2) Explain types of intent.
→. Types of Intents in Android:
1. Explicit Intent:

• Launches a specific component within the same application.


• Target component is explicitly defined by its class name.

2. Implicit Intent:
• Invokes a system component or an external application's component without
specifying the exact class name.
• Target component is determined based on the intent's action, data, and category.
Experiment No: 1
Aim: Introduction to Android Programming and installation of Android Studio.

• EXERCISE:

1. Introduction to Android Programming and installation of Android Studio.


Ans: Android programming involves developing applications for the Android operating system,
which is widely used in mobile devices like smartphones and tablets. Android applications are
typically written in Java or Kotlin programming languages, and they are designed to run on the
Android platform.
Android Programming Introduction:
1. Java/Kotlin Programming Languages:
- Android apps are primarily written in Java or Kotlin. Kotlin is the newer, officially
supported language for Android development, offering concise syntax and enhanced features.

2. Android Components:
- Activities: Represent the UI and user interaction.
- Services: Run in the background to perform tasks.
- Broadcast Receivers: Respond to system-wide broadcast announcements.
- Content Providers: Manage and share application data.

3. User Interface (UI) Design:


- Android uses XML-based layouts to define the UI.
- UI components include buttons, text fields, images, and more.
- Layouts like LinearLayout and RelativeLayout help organize UI elements.

Installation of Android Studio:

Android Studio is the official IDE for Android development. Follow these steps to install it:

Prof. Neil Saxena


1. Download Android Studio:
- Visit the [official Android Studio download
page](https://developer.android.com/studio).
- Download the appropriate version for your operating system (Windows, macOS, or
Linux).

2. Install Android Studio:


- Windows:
- Run the installer (.exe file) you downloaded.
- Follow the installation wizard instructions.
- macOS:
- Open the downloaded .dmg file.
- Drag and drop Android Studio into the Applications folder.
- Linux:
- Extract the downloaded .zip file to a location on your system.
- Open a terminal and navigate to the `bin` directory.
- Run `studio.sh` to start Android Studio.

3. Initial Setup:
- Open Android Studio.
- Complete the initial setup, which may include installing necessary components and
configuring the Android Virtual Device (AVD) Manager.

4. Create a New Project:


- Click on "Start a new Android Studio project."
- Follow the project creation wizard, providing details like project name, language
(Java or Kotlin), and device compatibility.

Prof. Neil Saxena


5. Explore Android Studio:
- Familiarize yourself with the layout of Android Studio, including the code editor,
XML layout editor, and Gradle build system.

• QUIZ

1. What is SDK?
Ans: SDK stands for Software Development Kit. It is a set of tools, libraries, documentation,
and sample code that developers use to create and build software applications for specific
platforms, frameworks, or programming languages. SDKs provide a standardized way for
developers to interact with and develop applications for a particular software or hardware
platform.
2. Enlist languages in which we can make android app.
Ans: Android app development primarily supports two main programming languages:
Java and Kotlin
3. Differentiate between JVM and DVM.
Ans:
JVM DVM
1) It is Stack based. 1) It is Register based which is designed to
run on low memory.
2) JVM uses java byte code and runs 2) DVM uses its own byte code and runs
“.class” file having JIT (Just In Time). the “.Dex” file. From Android 2.2 SDK
Dalvik has got a Just in Time compiler

3) A single instance of JVM is shared with 3) DVM has been designed so that a
multiple applications device can run multiple instances of the VM
efficiently. Applications are given their own
instance.
4) JVM supports multiple operating 4) DVM supports the Android operating
systems. system only.
5) For JVM many Re-tools are available. 5) For DVM very few Re-tools are
available
6) It has a constant pool for every class. 6) There is a constant pool for every
application.
7) Here the executable is JAR. 7) Here the executable is APK.
Prof. Neil Saxena
Prof. Neil Saxena

You might also like