Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Final Mad Print

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

Practical No 21 1802 Swarnim

X. 1) Write a program to demonstrate all the system broadcast meassage.Sender File:


XML file:

<?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:id="@+id/button" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="384dp" android:text="Send
brodcast Message" android:onClick="onBroadcastSendBtnCicked"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Java File:
<?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:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="384dp" android:text="Send
brodcast Message" android:onClick="onBroadcastSendBtnCicked"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Receiver FileXML File:


<?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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BroadCast Receiver"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Java File:
package com.example.pr18broadcastreciver2;

import androidx.appcompat.app.AppCompatActivity;import

android.content.Intent;
import android.content.IntentFilter;import
android.os.Bundle;

public class MainActivity extends AppCompatActivity {@Override


protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter=new IntentFilter("com.codingpursuits.myBroadcastMessage");
MyBroadcastReceiver objReciver=new MyBroadcastReceiver();
registerReceiver(objReciver,intentFilter);
}
}

Mainfeast File

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


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

<application android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:supportsRtl="true"
android:theme="@style/Theme.Pr18BroadcastReciver2"
tools:targetApi="31">
<receiver android:name=".MyBroadcastReceiver"
android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.codingpursuits.myBroadcastMessage">

</action>
</intent-filter>
</receiver>
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


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

</manifest>

Broadcast Receiver File:

package com.example.pr18broadcastreciver2;

import android.content.BroadcastReceiver;import
android.content.Context;
import
android.content.Intent;
import android.util.Log;
import
android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver

{@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i("BroadcastReceiver","Broadcast message is
received");Toast.makeText(context, "Broadcast message is
received",
Toast.LENGTH_SHORT).show();
}
}

Output:
Exp23:

package com.example.exp23;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback
private Camera camera;
private SurfaceHolder surfaceHolder;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SurfaceView surfaceView = findViewById(R.id.surfaceView);
imageView = findViewById(R.id.imageView);
Button captureButton = findViewById(R.id.captureButton);
if (checkSelfPermission(Manifest.permission.CAMERA) !=
PackageManager.PERMISSION_GRANTED) {requestPermissions(new
String[]{Manifest.permission.CAMERA}, 1);}
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this); captureButton.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
captureImage();
}});}
@Override
public void surfaceCreated(@NonNull SurfaceHolder holder) {
try {
camera = Camera.open();
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(holder);
camera.startPreview();
}} catch (IOException e) {
Log.e("Camera", "Error setting camera preview: " + e.getMessage
@Override
public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int
height) {
if (surfaceHolder.getSurface() == null) {
return;
} try {
camera.stopPreview();
} catch (Exception e) {
Log.e("Camera", "Error stopping camera preview: " + e.getMessage());
}try {camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
Log.e("Camera", "Error starting camera preview: " + e.getMessage());}}
@Override
public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
releaseCamera();}
private void releaseCamera() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;}private void captureImage() {
if (camera != null) {
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap); Toast.makeText(MainActivity.this,
"Image Captured", Toast.LENGTH_SHORT).show();
camera.startPreview();
}});}}
@Override
protected void onDestroy() {
super.onDestroy();
releaseCamera()
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exp23"
xmlns:tools="http://schemas.android.com/tools">
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Exp23"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter" />
<Button
android:id="@+id/captureButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture" />
</LinearLayout>
Practical No.24 1802 Swarnim
Exercise:
Q1.Blutooth Connectivity.

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"
android:transitionGroup="true">

<TextView android:text="Bluetooth Example"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview" android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView"
android:layout_below="@+id/textview"
android:layout_centerHorizontal="true"
android:textColor="#ff7aff24"
android:textSize="35dp" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/imageView"
android:src="@drawable/sample" android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On" android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_toStartOf="@+id/imageView"
android:layout_toLeftOf="@+id/imageView"
android:clickable="true" android:onClick="on" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Get
visible" android:onClick="visible"
android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="List
devices" android:onClick="list"
android:id="@+id/button3"
android:layout_below="@+id/imageView"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="turn
off" android:onClick="off" android:id="@+id/button4"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<ListView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/listView" android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_below="@+id/textView2" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Paired devices:"
android:id="@+id/textView2"
android:textColor="#ff34ff06"
android:textSize="25dp"
android:layout_below="@+id/button4"
android:layout_alignLeft="@+id/listView"
android:layout_alignStart="@+id/listView" />

</RelativeLayout>

Main java
package com.example.blutooth;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

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

import android.widget.ArrayAdapter;import
android.widget.Button; import
android.widget.ListView;

import android.widget.Toast;import
java.util.ArrayList; import java.util.Set;

public class MainActivity extends Activity {Button b1,b2,b3,b4;


private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;ListView lv;

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

b1 = (Button) findViewById(R.id.button);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3);
b4=(Button)findViewById(R.id.button4);

BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}

public void on(View v){


if (!BA.isEnabled()) { Intent
turnOn = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned
on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on",
Toast.LENGTH_LONG).show();
}
}
public void off(View v){
BA.disable(); Toast.makeText(getApplicationContext(), "Turned off"
,Toast.LENGTH_LONG).show();
}

public void visible(View v){Intent


getVisible = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}

public void list(View v){


pairedDevices = BA.getBondedDevices();ArrayList list

= new ArrayList();

for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();

final ArrayAdapter adapter = new


ArrayAdapter(this,android.R.layout.simple_list_item_1, list);

lv.setAdapter(adapter);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"/>

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

</manifest>

Output:
Prac 26
Ans1) 1802 Swarnim

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.Constra intLayout
xmlns:android="http://schemas.android.co m/apk/res/android"
xmlns:app="http://schemas.android.com/a pk/res-auto"
xmlns:tools="http://schemas.android.com/t ools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText android:id="@+id/editTextRecordNum"
android:layout_width="318dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="44dp"
android:layout_marginLeft="44dp"
android:layout_marginTop="124dp"
android:ems="10"
android:fontFamily="@font/poppins_medi um"
android:inputType="number"
android:singleLine="true"
android:textColor="#FFFFFF"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints" />
<Button android:id="@+id/buttonNormalInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editTextRec ordNum"
android:layout_alignLeft="@+id/editText RecordNum"
android:layout_marginStart="44dp"
android:layout_marginLeft="44dp"
android:layout_marginTop="44dp"
android:fontFamily="@font/poppins_medi um"
android:text="Normal Insert" app:layout_constraintStart_toStartOf="par ent"
app:layout_constraintTop_toBottomOf=" @+id/editTextRecordNum" />
<Button android:id="@+id/buttonFastInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/buttonNormalIns
ert"
android:layout_alignBottom="@+id/buttonNormalInse
rt" android:layout_marginTop="44dp"
android:layout_marginEnd="48dp"
android:text="Fast Insert"
app:layout_constraintEnd_toEndOf="parent"
android:layout_alignLeft="@+id/buttonNormalInsert"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="36dp"
android:fontFamily="@font/poppins_medium"
app:layout_constraintTop_toBottomOf=" @+id/editTextRecordNum" />
<TextView android:id="@+id/textViewStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/buttonNorm
alInsert" android:padding="10dp"
android:text="Status"
android:textColor="#FFFFFF"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf=" @+id/buttonNormalInsert" />
</androidx.constraintlayout.widget.Constr aintLayout>

MainActivity.java
package com.example.coexp26;
import android.os.AsyncTask;
import android.os.Bundle;
import
android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity
{
final String TAG = "MainActivity.java";
EditText editTextRecordNum; TextView tvStatus;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View.OnClickListener handler = new
View.OnClickListener() { public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonNormalInsert: new
AsyncInsertData("normal").execute(); break; case
R.id.buttonFastInsert: new AsyncInsertData("fast").execute(); break;
}
}
};
// EditText for entering desired number of records to be inserted
editTextRecordNum = (EditText) findViewById(R.id.editTextRecordNum); // Button for
normal and fast insert
findViewById(R.id.buttonNormalInsert).setOnClickListener(handler);
findViewById(R.id.buttonFastInsert).setO nClickListener(handler); //
status TextView tvStatus = (TextView)
findViewById(R.id.textViewStatus);
} // we used AsyncTask so it won't block the UI thread during
inserts. class AsyncInsertData extends AsyncTask<String, String,
String>
{
DatabaseHandler databaseHandler;
String type;long timeElapsed;
protected AsyncInsertData(String type){ this.type = type;
this.databaseHandler = new DatabaseHandler(MainActivity.this);
} // @type - can be 'normal' or 'fast'
@Override
protected void onPreExecute()
{
super.onPreExecute();
tvStatus.setText("Inserting " + editTextRecordNum.getText() + " records...");
}
@Override
protected String doInBackground(String... aurl) {
try { // get number of records to be inserted int insertCount =
Integer.parseInt(editTextRecordNum.getT ext().toString()); // empty the table
databaseHandler.deleteRecords(); // keep track of execution time long lStartTime =
System.nanoTime();
if (type.equals("normal"))
{ databaseHandler.insertNormal(insertCount );
}
else
{
databaseHandler.insertFast(insertCount);
} // execution finished long lEndTime = System.nanoTime(); // display execution time
timeElapsed = lEndTime - lStartTime; }
catch (Exception e) {
e.printStackTrace(); } return null; } protected void onPostExecute(String unused) {
tvStatus.setText("Done inserting " + databaseHandler.countRecords() + " records. Time
elapsed: " + timeElapsed / 1000000 + " ms.");
}
}
}

DatabaseHandler.java
package com.example.coexp26;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DatabaseHandler extends SQLiteOpenHelper {
// for our logs
public static final String TAG = "DatabaseHandler.java";
// database version
private static final int DATABASE_VERSION = 7;
// database name
protected static final String DATABASE_NAME = "NinjaDatabase2";
// table details
public String tableName = "locations";
public String fieldObjectId = "id";
public String fieldObjectName = "name";
public String fieldObjectDescription = "description";
// constructor
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// creating table
@Override
public void onCreate(SQLiteDatabase
db) { String sql = "";
sql += "CREATE TABLE " +
tableName; sql += " ( ";
sql += fieldObjectId + " INTEGER PRIMARY KEY AUTOINCREMENT, ";
sql += fieldObjectName + " TEXT, ";
sql += fieldObjectDescription + "
TEXT "; sql += " ) ";
db.execSQL(sql);
String INDEX = "CREATE UNIQUE INDEX locations_index ON " + tableName + "
(name, description)";
db.execSQL(INDEX);
}
// When upgrading the database, it will drop the current table and recreate.
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) { String sql = "DROP TABLE IF EXISTS " + tableName;
db.execSQL(sql);
onCreate(db);
}
// insert data using transaction and prepared
statement public void insertFast(int insertCount) {
// you can use INSERT only
String sql = "INSERT OR REPLACE INTO " + tableName + " ( name, description )
VALUES ( ?, ? )"; SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive(); //
db.beginTransaction(); SQLiteStatement stmt =
db.compileStatement(sql);
for (int x = 1; x <= insertCount; x++) {
stmt.bindString(1, "Name # " + x);
stmt.bindString(2, "Description # " + x);
stmt.execute();
stmt.clearBindings();
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
// inserts the record without using transaction and prepare statement
public void insertNormal(int insertCount) {
try {
SQLiteDatabase db =
this.getWritableDatabase(); for (int x = 1; x
<= insertCount; x++) {
ContentValues values = new ContentValues();
values.put(fieldObjectName, "Name # " + x);
values.put(fieldObjectDescription, "Description # "
+ x); db.insert(tableName, null, values);
}
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// deletes all records
public void deleteRecords() {
SQLiteDatabase db =
this.getWritableDatabase();
db.execSQL("delete from " + tableName);
db.close();
}
// count records
public int countRecords() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT count(*) from " + tableName, null);
cursor.moveToFirst();
int recCount = cursor.getInt(0);
cursor.close();
db.close();
return
recCount;
}
}
OUTPUT -
Exp27:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class LoginActivity extends AppCompatActivity {
private EditText editTextUsername, editTextPassword;
private Button buttonLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextUsername = findViewById(R.id.editTextUsername);
editTextPassword = findViewById(R.id.editTextPassword);
buttonLogin = findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = editTextUsername.getText().toString();
String password = editTextPassword.getText().toString();
if (!username.isEmpty() && !password.isEmpty()) {
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Login unsuccessful. Please enter valid credentials.",
Toast.LENGTH_SHORT).show();
}
}
});}}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username" />
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password" />
<Button
android:id="@+id/buttonLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>
Exp 30

AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exp30">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Exp30">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<EditText
android:id="@+id/txtTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="To"/>
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"/>
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="top"
android:hint="Message"/>
<Button
android:id="@+id/btnSend"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Send" />
</LinearLayout>

MainActivity.java:
package com.example.exp30;
import android.content.Intent;
//import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import
androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends
AppCompatActivity { private EditText eTo;
private EditText eSubject;
private EditText eMsg;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eTo =
(EditText)findViewById(R.id.txtTo);
eSubject =
(EditText)findViewById(R.id.txtSub); eMsg =
(EditText)findViewById(R.id.txtMsg); btn =
(Button)findViewById(R.id.btnSend);
btn.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v) {
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, new
String[]{eTo.getText().toString()});
it.putExtra(Intent.EXTRA_SUBJECT,eSubject.getText().toString());
it.putExtra(Intent.EXTRA_TEXT,eMsg.getText());
it.setType("message/rfc822");
startActivity(Intent.createChooser(it,"Choose Mail App"));
}
});
}
}
EXP –
31

Output –
EXP –
31
Exp 31

AndroidMainfest.xml:

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


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exp31">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Exp31">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_api_key" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</RelativeLayout>

strings_xml:
<resources>
<string name="app_name">Exp31</string>
<string name="google_api_key">AIzaSyD4KfDcLVjVPatpIKtrPXot024Z4UHVZQ8</string>
</resources>
EXP –
31
MainActivity.java:
package com.example.exp31;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.common.ConnectionResult;
importcom.google.android.gms.location.LocationRest;
importcom.google.android.gms.location.LocationSces;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
importcom.google.android.gms.maps.internal.ICameraUpdateFactoryDelegate
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback


{ Location currentLocation;
FusedLocationProviderClient
fusedLocationProviderClient; private static final int
REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this
); fetchLastLocation();
}
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) ActivityCompat.requestPermissions(this,new
String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUE
ST_CODE); return;
EXP –
31
}
Task<Location> task =
fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location!=null){
currentLocation = location;
Toast.makeText(getApplicationContext(), "Latitude:
"+currentLocation.getLatitude()+"\n"+"Longitude: "+currentLocation.getLongitude(),
Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(MainActivity.this);
}
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new
LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
MarkerOptions options = new
MarkerOptions().position(latLng).title("I am Here");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng
,5)); googleMap.addMarker(options);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_CODE:
if(grantResults.length>0 &&
grantResults[0]==PackageManager.PERMISSION_GRANTED){
fetchLastLocation();
}
break;
}
}
}
EXP –
32

Output –
EXP –
32
Exp 32

AndroidMainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.exp32">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Exp32">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal
" tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content
" android:id="@+id/et_source"
android:hint="Enter Source
Location" android:padding="12dp"
android:background="@android:drawable/editbox_background"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content
" android:id="@+id/et_destination"
android:hint="Enter Destination
Location" android:padding="12dp"
android:layout_marginTop="8dp"
android:background="@android:drawable/editbox_background"/>
<Button
android:layout_width="wrap_content"
EXP –
32
android:layout_height="wrap_content
" android:id="@+id/bt_track"
android:text="Display Track"
android:layout_marginTop="16dp"/>
</LinearLayout>

MainActivity.java:
package com.example.exp32;
importandroidx.appcompat.app.AppCompatActivi
importandroid.content.ActivityNotFoundExceptio
import android.content.Intent;
import android.net.Uri;
importandroid.os.Bundle;
importandroid.view.View
;
import android.widget.Button;
import
android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends
AppCompatActivity { EditText
etSource,etDestination;
Button btTrack;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mai
n); etSource =
findViewById(R.id.et_source);
etDestination =
findViewById(R.id.et_destination); btTrack =
findViewById(R.id.bt_track);
btTrack.setOnClickListener(new
View.OnClickListener() { @Override
public void onClick(View v) {
String sSource = etSource.getText().toString().trim();
String sDestination =
etDestination.getText().toString().trim();
if(sSource.equals("") && sDestination.equals("")){
Toast.makeText(getApplicationContext(),"Enter
both location",Toast.LENGTH_SHORT).show();
}else {
DisplayTrack(sSource,sDestination);
}
}
});
}EXP –
32
private void DisplayTrack(String sSource, String
sDestination) { try {
Uri uri =
Uri.parse("https://www.google.co.in/maps/dir/"+sSource+"/"+sDestinati
on); Intent intent = new Intent(Intent.ACTION_VIEW,uri);
intent.setPackage("com.google.android.apps.
maps");
intent.setFlags(Intent.FLAG_ACTIVITY_N
EW_TASK);
StartActivity(intent);
}catch
(ActivityNotFoundException e){
Uri uri =
Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.m
aps");
Intent intent = new
Intent(Intent.ACTION_VIEW,uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_
TASK); startActivity(intent);
}
}
}
EXP –
32

You might also like