0% found this document useful (0 votes)
51 views24 pages

Mad From 23-1

The document contains code for an Android app that allows a user to take photos and videos using the device camera, and also code for an Android app that allows a user to interact with Bluetooth devices. The first section of code defines an activity class that opens the device camera in response to button clicks, retrieves any captured photos or videos, and displays photos. The second section of code defines a Bluetooth-enabled activity class with buttons for turning Bluetooth on/off, making the device discoverable, and listing paired devices. It retrieves nearby discovered and paired devices using the Bluetooth adapter.

Uploaded by

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

Mad From 23-1

The document contains code for an Android app that allows a user to take photos and videos using the device camera, and also code for an Android app that allows a user to interact with Bluetooth devices. The first section of code defines an activity class that opens the device camera in response to button clicks, retrieves any captured photos or videos, and displays photos. The second section of code defines a Bluetooth-enabled activity class with buttons for turning Bluetooth on/off, making the device discoverable, and listing paired devices. It retrieves nearby discovered and paired devices using the Bluetooth adapter.

Uploaded by

drbsf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 24

pr 23 ex 1

java
package com.example.prac23ex1;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private static final int pic_id = 123;


Button camera_open_id;
ImageView click_image_id;

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

camera_open_id =(Button) this.findViewById(R.id.camera_button);


click_image_id = (ImageView) this.findViewById(R.id.click_image);

camera_open_id.setOnClickListener(v -> {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera_intent, pic_id);
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);


if (requestCode == pic_id) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
click_image_id.setImageBitmap(photo);
}
}
}

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

<!-- add Camera Button to open the Camera -->


<Button
android:id="@+id/camera_button"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:text="Camera" />
<!-- add ImageView to display the captured image -->
<ImageView
android:id="@+id/click_image"
android:layout_width="350dp"
android:layout_height="450dp"
android:layout_marginStart="30dp"
android:layout_marginTop="70dp"
android:layout_marginBottom="10dp" />

</RelativeLayout>

------------------
pr 23 ex 2
java
package com.example.prac23ex2;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private static final int pic_id = 123;


private static final int video_id = 124;

Button camera_open_id;
Button video_open_id;
ImageView click_image_id;

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

camera_open_id =(Button) findViewById(R.id.camera_button);


video_open_id = (Button) findViewById(R.id.video_button);
click_image_id = (ImageView) findViewById(R.id.click_image);

camera_open_id.setOnClickListener(v -> {
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera_intent, pic_id);
});

video_open_id.setOnClickListener(v -> {
Intent video_intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(video_intent, video_id);
});
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {


super.onActivityResult(requestCode, resultCode, data);

if (requestCode == pic_id && resultCode == RESULT_OK) {


Bitmap photo = (Bitmap) data.getExtras().get("data");
click_image_id.setImageBitmap(photo);
} else if (requestCode == video_id && resultCode == RESULT_OK) {
// Handle video recording success
Toast.makeText(this, "Video saved.", Toast.LENGTH_SHORT).show();
} else {
// Handle other cases or errors
Toast.makeText(this, "Action canceled or failed.",
Toast.LENGTH_SHORT).show();
}
}
}

---------------------------------------
pr 24 ex 1
java
package com.example.prac24ex1;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
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 androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

private static final int REQUEST_ENABLE_BT = 1;

private BluetoothAdapter bluetoothAdapter;


private ArrayAdapter<String> devicesArrayAdapter;

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

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {

Toast.makeText(this, "Bluetooth is not supported on this device",


Toast.LENGTH_SHORT).show();
finish();
}

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


Button btnDiscoverable = findViewById(R.id.btnDiscoverable);
Button btnListDevices = findViewById(R.id.btnListDevices);
Button btnTurnOff = findViewById(R.id.btnTurnOff);

ListView listViewDevices = findViewById(R.id.listViewDevices);


devicesArrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1);
listViewDevices.setAdapter(devicesArrayAdapter);

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

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

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

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

private void turnOnBluetooth() {


if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
Toast.makeText(this, "Bluetooth is already turned on",
Toast.LENGTH_SHORT).show();
}
}

private void makeDiscoverable() {


if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Bluetooth is not turned on",
Toast.LENGTH_SHORT).show();
} else {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_ADVERTISE) !=
PackageManager.PERMISSION_GRANTED) {

return;
}
startActivity(discoverableIntent);
}
}

private void listDevices() {


devicesArrayAdapter.clear();

if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {

return;
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {

return;
}
devicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);


registerReceiver(discoveryReceiver, filter);

if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
return;
}
bluetoothAdapter.startDiscovery();
}

private void turnOffBluetooth() {


if (bluetoothAdapter.isEnabled()) {
if (ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {

return;
}
bluetoothAdapter.disable();
Toast.makeText(this, "Bluetooth turned off",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Bluetooth is already turned off",
Toast.LENGTH_SHORT).show();
}
}

private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {


public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (ActivityCompat.checkSelfPermission(context,
android.Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {

return;
}
devicesArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();

unregisterReceiver(discoveryReceiver);
}
}

---------------------------
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=".BluetoothControlActivity">

<Button
android:id="@+id/btnTurnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Bluetooth On"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/btnDiscoverable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make Discoverable"
android:layout_below="@id/btnTurnOn"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/btnListDevices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"
android:layout_below="@id/btnDiscoverable"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/btnTurnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Bluetooth Off"
android:layout_below="@id/btnListDevices"
android:layout_marginTop="16dp"
android:layout_centerHorizontal="true" />

<ListView
android:id="@+id/listViewDevices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btnTurnOff"
android:layout_marginTop="16dp"
android:divider="@android:color/darker_gray"
android:dividerHeight="1dp" />
</RelativeLayout>

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

<!-- add Camera Button to open the Camera -->


<Button
android:id="@+id/camera_button"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:text="Camera" />

<!-- add Video Button to record video -->


<Button
android:id="@+id/video_button"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_below="@id/camera_button"
android:layout_marginStart="150dp"
android:layout_marginTop="20dp"
android:text="Video" />

<!-- add ImageView to display the captured image -->


<ImageView
android:id="@+id/click_image"
android:layout_width="350dp"
android:layout_height="450dp"
android:layout_marginStart="30dp"
android:layout_marginTop="70dp"
android:layout_marginBottom="10dp" />

</RelativeLayout>
----------------------------------------------
pr 26 ex 1
java
package com.example.prac26_1;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText nameEditText;


private EditText branchEditText;
private Button insertButton;
private ListView dataListView;

private DatabaseHelper dbHelper;

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

nameEditText = findViewById(R.id.name_edit_text);
branchEditText = findViewById(R.id.branch_edit_text);
insertButton = findViewById(R.id.insert_button);
dataListView = findViewById(R.id.data_list_view);

dbHelper = new DatabaseHelper(this);

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

new FetchDataTask().execute();
}

private void insertData() {


String name = nameEditText.getText().toString().trim();
String branch = branchEditText.getText().toString().trim();

if (name.isEmpty() || branch.isEmpty()) {
Toast.makeText(this, "Please enter both name and branch.",
Toast.LENGTH_SHORT).show();
return;
}

InsertDataTask insertDataTask = new InsertDataTask();


insertDataTask.execute(name, branch);
}

private class InsertDataTask extends AsyncTask<String, Void, Void> {

@Override
protected Void doInBackground(String... params) {
String name = params[0];
String branch = params[1];

dbHelper.insertData(name, branch);

return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(MainActivity.this, "Data inserted successfully.",
Toast.LENGTH_SHORT).show();
nameEditText.setText("");
branchEditText.setText("");

new FetchDataTask().execute();
}
}

private class FetchDataTask extends AsyncTask<Void, Void, Cursor> {

@Override
protected Cursor doInBackground(Void... params) {
return dbHelper.getAllData();
}

@Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);

// Create an adapter for the ListView


SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this,
android.R.layout.simple_list_item_2,
cursor,
new String[] { DatabaseHelper.COLUMN_NAME,
DatabaseHelper.COLUMN_BRANCH },
new int[] { android.R.id.text1, android.R.id.text2 },
0
);

// Set the adapter to the ListView


dataListView.setAdapter(adapter);
}
}
}

-------------------------
DatabaseHelper.java
package com.example.prac26_1;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "my_database";


private static final int DATABASE_VERSION = 1;

public static final String TABLE_NAME = "my_table";


public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_BRANCH = "branch";

private static final String CREATE_TABLE_QUERY = "CREATE TABLE " + TABLE_NAME +


" (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " +
COLUMN_BRANCH + " TEXT)";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_QUERY);
}

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

public void insertData(String name, String branch) {


SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, name);
values.put(COLUMN_BRANCH, branch);
db.insert(TABLE_NAME, null, values);
db.close();
}

public Cursor getAllData() {


SQLiteDatabase db = this.getReadableDatabase();
return db.query(TABLE_NAME, null, null, null, null, null, null);
}
}

-----------------------
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/name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Enter Name"
android:inputType="text" />

<EditText
android:id="@+id/branch_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/name_edit_text"
android:layout_margin="16dp"
android:hint="Enter Branch"
android:inputType="text" />

<Button
android:id="@+id/insert_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/branch_edit_text"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Insert Data" />

<ListView
android:id="@+id/data_list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/insert_button"
android:layout_marginTop="16dp" />

</RelativeLayout>
-----------------------------------
pr 27 ex 1
java
package com.example.prac27_1;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText etUsername, etPassword;


private Button btnLogin;
private TextView tvResult;

private static final String VALID_USERNAME = "dhiraj";


private static final String VALID_PASSWORD = "dhiraj";

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

etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
tvResult = findViewById(R.id.tvResult);

btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

String username = etUsername.getText().toString();


String password = etPassword.getText().toString();

if (isValidCredentials(username, password)) {

tvResult.setText("LOGIN SUCCESSFUL");
showToast("Login Successful");
} else {
tvResult.setText("");
showToast("Login Failed");
}
}
});
}

private boolean isValidCredentials(String username, String password) {


return username.equals(VALID_USERNAME) && password.equals(VALID_PASSWORD);
}

private void showToast(String message) {


Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
--------------------------------
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/etUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true" />

<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"
android:layout_below="@id/etUsername"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/etPassword"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:textColor="#008000"
android:layout_below="@id/btnLogin"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

</RelativeLayout>
----------------------------------
pr 28 ex 1
java
package com.example.prac28_1;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

private EditText etUsername, etPassword;


private Button btnLogin;

private int loginAttempts = 0;


private TextView tvUsernameError, tvPasswordError,
tvLoginResult,tvLoginAttempts;

private static final int MIN_USERNAME_LENGTH = 5;


private static final Pattern USERNAME_PATTERN = Pattern.compile("[a-zA-Z0-
9]+");

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

etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
tvUsernameError = findViewById(R.id.tvUsernameError);
tvPasswordError = findViewById(R.id.tvPasswordError);
tvLoginResult = findViewById(R.id.tvLoginResult);
tvLoginAttempts = findViewById(R.id.tvLoginAttempts);

btnLogin.setEnabled(false);

etUsername.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int
count, int after) {}

@Override
public void onTextChanged(CharSequence charSequence, int start, int
before, int count) {
validateUsername(charSequence.toString());
}

@Override
public void afterTextChanged(Editable editable) {
validateForm();
}
});

etPassword.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int start, int
count, int after) {}

@Override
public void onTextChanged(CharSequence charSequence, int start, int
before, int count) {
validatePassword(charSequence.toString());
}

@Override
public void afterTextChanged(Editable editable) {
validateForm();
}
});

btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}

private void validateUsername(String username) {


if (TextUtils.isEmpty(username)) {
tvUsernameError.setText("Username cannot be empty");
} else if (username.length() < MIN_USERNAME_LENGTH) {
tvUsernameError.setText("Username must be at least " +
MIN_USERNAME_LENGTH + " characters");
} else if (!USERNAME_PATTERN.matcher(username).matches()) {
tvUsernameError.setText("Invalid characters in username");
} else {
tvUsernameError.setText("");
}
}

private void validatePassword(String password) {


if (TextUtils.isEmpty(password)) {
tvPasswordError.setText("Password cannot be empty");
} else {
tvPasswordError.setText("");
}
}

private void validateForm() {


btnLogin.setEnabled(tvUsernameError.getText().toString().isEmpty() &&
tvPasswordError.getText().toString().isEmpty());
}

private void attemptLogin() {

loginAttempts++;

String username = etUsername.getText().toString();


String password = etPassword.getText().toString();

if ("dhiraj".equals(username) && "dhiraj".equals(password)) {


tvLoginResult.setText("LOGIN SUCCESSFUL");
showToast("Login Successful");
loginAttempts=0;
} else {
tvLoginResult.setText("LOGIN FAILED");
showToast("Login Failed");
}

if(loginAttempts>0)
tvLoginAttempts.setText("Unsuccessful Attempts: " + loginAttempts);
else
tvLoginAttempts.setText("");
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
------------------------------
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/etUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true" />

<TextView
android:id="@+id/tvUsernameError"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#FF0000"
android:layout_below="@id/etUsername"
android:layout_marginTop="8dp"
android:layout_centerHorizontal="true" />
<EditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="Password"
android:layout_below="@id/tvUsernameError"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

<TextView
android:id="@+id/tvPasswordError"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#FF0000"
android:layout_below="@id/etPassword"
android:layout_marginTop="8dp"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:layout_below="@id/tvPasswordError"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

<TextView
android:id="@+id/tvLoginResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="18sp"
android:textColor="#008000"
android:layout_below="@id/btnLogin"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/tvLoginAttempts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_below="@id/tvLoginResult"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

</RelativeLayout>
---------------------------
pr 29 ex 1
java
package com.example.prac29ex1;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

private Button inboxButton;

private EditText phoneNumberEditText, messageEditText;


private Button sendButton;
private TextView receivedMessageTextView;

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

Button inboxButton = findViewById(R.id.buttonInbox);


inboxButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, InboxActivity.class));
}
});

phoneNumberEditText = findViewById(R.id.editTextPhoneNumber);
messageEditText = findViewById(R.id.editTextMessage);
sendButton = findViewById(R.id.buttonSend);
receivedMessageTextView = findViewById(R.id.textViewReceivedMessage);

registerReceiver(smsReceiver, new
IntentFilter("android.provider.Telephony.SMS_RECEIVED"));

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {


if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.RECEIVE_SMS}, 1);
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.SEND_SMS}, 2);
}
}

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

private void sendMessage() {


String phoneNumber = phoneNumberEditText.getText().toString();
String message = messageEditText.getText().toString();

if (!phoneNumber.isEmpty() && !message.isEmpty()) {


SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(this, "Message sent!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter both phone number and message",
Toast.LENGTH_SHORT).show();
}
}

private final BroadcastReceiver smsReceiver = new BroadcastReceiver() {


@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
for (Object pdu : pdus) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[])
pdu);
String sender = smsMessage.getDisplayOriginatingAddress();
String message = smsMessage.getMessageBody();

receivedMessageTextView.setText("Received SMS from: " +


sender + "\nMessage: " + message);
}
}
}
}
};

@Override
protected void onDestroy() {
super.onDestroy();

unregisterReceiver(smsReceiver);
}
}
------------------------
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:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:inputType="phone" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPhoneNumber"
android:layout_marginTop="8dp"
android:hint="Message" />

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextMessage"
android:layout_marginTop="16dp"
android:text="Send" />

<TextView
android:id="@+id/textViewReceivedMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonSend"
android:layout_marginTop="16dp" />

<Button
android:id="@+id/buttonInbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonSend"
android:layout_marginTop="16dp"
android:text="Inbox" />

</RelativeLayout>
---------------
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:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextPhoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:inputType="phone" />

<EditText
android:id="@+id/editTextMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextPhoneNumber"
android:layout_marginTop="8dp"
android:hint="Message" />

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextMessage"
android:layout_marginTop="16dp"
android:text="Send" />

<TextView
android:id="@+id/textViewReceivedMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonSend"
android:layout_marginTop="16dp" />

<Button
android:id="@+id/buttonInbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/buttonSend"
android:layout_marginTop="16dp"
android:text="Inbox" />

</RelativeLayout>
----------------------------------------
InboxActivity.java
package com.example.prac29ex1;
import android.os.Bundle;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class InboxActivity extends AppCompatActivity {

private TextView inboxTextView;

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

inboxTextView = findViewById(R.id.textViewInbox);

String[] receivedMessages = {"Message 1", "Message 2", "Message 3"};

StringBuilder inboxText = new StringBuilder();


for (String message : receivedMessages) {
inboxText.append(message).append("\n\n");
}

inboxTextView.setText(inboxText.toString());
}
}
--------------------------------
activity_inbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<TextView
android:id="@+id/textViewInbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</RelativeLayout>
------------------------------
pr 30 ex 1
java
package com.example.prac30ex1;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {


EditText editTextTo,editTextSubject,editTextMessage;
Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editTextTo=(EditText)findViewById(R.id.editText1);
editTextSubject=(EditText)findViewById(R.id.editText2);
editTextMessage=(EditText)findViewById(R.id.editText3);

send=(Button)findViewById(R.id.button1);

send.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
String to=editTextTo.getText().toString();
String subject=editTextSubject.getText().toString();
String message=editTextMessage.getText().toString();

Intent email = new Intent(Intent.ACTION_SEND);


email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);

email.setType("message/rfc822");

startActivity(Intent.createChooser(email, "Choose an Email


client :"));

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

return true;
}

}
--------------------
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/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="22dp"
android:layout_marginTop="16dp"
android:ems="10" />

<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="18dp"
android:ems="10" />

<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/editText2"
android:layout_marginTop="28dp"
android:ems="10"
android:inputType="textMultiLine" />

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText1"
android:layout_alignBottom="@+id/editText1"
android:layout_alignParentLeft="true"
android:text="To:" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText2"
android:layout_alignBottom="@+id/editText2"
android:layout_alignParentLeft="true"
android:text="Subject:" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/editText3"
android:layout_alignBottom="@+id/editText3"
android:layout_alignParentLeft="true"
android:text="Message:" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText3"
android:layout_below="@+id/editText3"
android:layout_marginLeft="76dp"
android:layout_marginTop="20dp"
android:text="Send" />

</RelativeLayout>

You might also like