0% found this document useful (0 votes)
41 views34 pages

MAD Project

Uploaded by

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

MAD Project

Uploaded by

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

GOVT.

POLYTECHNIC
LISANA
PRACTICAL WORK
On
MOBILE APPLICATION DEVELOPMENT

Submitted By : DHEERAJ
Class : CSE 6th SEM.
Roll No. : 210300822006
Submitted To :
Mrs. Pooja Arora
PRACTICAL - 1
Aim : Write a program to demonstrate activity (Application Life Cycle)
There's a simple Android app demonstrating the activity lifecycle:
MainActivity.java :
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: ");
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}

@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}

@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}

@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
}

Activity_main.xml (layout file) :

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

</RelativeLayout>
PRACTICAL – 2

Aim : Write a program to demonstrate different types of layouts

There's a simple Android app demonstrating different types of layouts using XML :

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

<!-- Linear Layout -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
</LinearLayout>

<!-- Relative Layout -->


<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 3"
android:layout_alignParentLeft="true"/>

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 4"
android:layout_alignParentRight="true"/>
</RelativeLayout>

<!-- Constraint Layout -->


<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>

<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 6"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

</LinearLayout>
PRACTICAL – 3

Aim : Write a program to implement simple calculator

There's a simple Android app implementing a basic calculator functionality :

MainActivity.java :

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {

private TextView displayTextView;


private StringBuilder input;
private boolean isResultShown;

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

displayTextView = findViewById(R.id.display_text_view);
input = new StringBuilder();
isResultShown = false;

ButtonClickListener buttonClickListener = new ButtonClickListener();


findViewById(R.id.button_clear).setOnClickListener(buttonClickListener);
findViewById(R.id.button_zero).setOnClickListener(buttonClickListener);
findViewById(R.id.button_one).setOnClickListener(buttonClickListener);
findViewById(R.id.button_two).setOnClickListener(buttonClickListener);
findViewById(R.id.button_three).setOnClickListener(buttonClickListener);
findViewById(R.id.button_four).setOnClickListener(buttonClickListener);
findViewById(R.id.button_five).setOnClickListener(buttonClickListener);
findViewById(R.id.button_six).setOnClickListener(buttonClickListener);
findViewById(R.id.button_seven).setOnClickListener(buttonClickListener);
findViewById(R.id.button_eight).setOnClickListener(buttonClickListener);
findViewById(R.id.button_nine).setOnClickListener(buttonClickListener);
findViewById(R.id.button_add).setOnClickListener(buttonClickListener);
findViewById(R.id.button_subtract).setOnClickListener(buttonClickListener);
findViewById(R.id.button_multiply).setOnClickListener(buttonClickListener);
findViewById(R.id.button_divide).setOnClickListener(buttonClickListener);
findViewById(R.id.button_equals).setOnClickListener(buttonClickListener);
findViewById(R.id.button_dot).setOnClickListener(buttonClickListener);
}

private void appendToInput(String value) {


if (isResultShown) {
input.setLength(0);
isResultShown = false;
}
input.append(value);
displayTextView.setText(input.toString());
}

private void clearInput() {


input.setLength(0);
displayTextView.setText("");
}

private void calculateResult() {


try {
String result = new ExpressionEvaluator().evaluate(input.toString());
displayTextView.setText(result);
input.setLength(0);
input.append(result);
isResultShown = true;
} catch (Exception e) {
displayTextView.setText("Error");
}
}

private class ButtonClickListener implements View.OnClickListener {


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_clear:
clearInput();
break;
case R.id.button_zero:
appendToInput("0");
break;
case R.id.button_one:
appendToInput("1");
break;
case R.id.button_two:
appendToInput("2");
break;
case R.id.button_three:
appendToInput("3");
break;
case R.id.button_four:
appendToInput("4");
break;
case R.id.button_five:
appendToInput("5");
break;
case R.id.button_six:
appendToInput("6");
break;
case R.id.button_seven:
appendToInput("7");
break;
case R.id.button_eight:
appendToInput("8");
break;
case R.id.button_nine:
appendToInput("9");
break;
case R.id.button_add:
appendToInput("+");
break;
case R.id.button_subtract:
appendToInput("-");
break;
case R.id.button_multiply:
appendToInput("*");
break;
case R.id.button_divide:
appendToInput("/");
break;
case R.id.button_equals:
calculateResult();
break;
case R.id.button_dot:
appendToInput(".");
break;
}
}
}
}

ExpressionEvaluator.java :

import java.util.Stack;

public class ExpressionEvaluator {

public String evaluate(String expression) {


try {
Stack<Double> stack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c) || c == '.') {
StringBuilder operand = new StringBuilder();
while (i < expression.length() && (Character.isDigit(expression.charAt(i)) ||
expression.charAt(i) == '.')) {
operand.append(expression.charAt(i++));
}
i--;
stack.push(Double.parseDouble(operand.toString()));
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
double operand2 = stack.pop();
double operand1 = stack.pop();
switch (c) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
case '*':
stack.push(operand1 * operand2);
break;
case '/':
stack.push(operand1 / operand2);
break;
}
}
}
return String.valueOf(stack.pop());
} catch (Exception e) {
return "Error";
}
}
}

Activity_main.xml (layout file) :

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

<TextView
android:id="@+id/display_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textAlignment="viewEnd"
android:layout_margin="16dp"
android:background="#f0f0f0"
android:padding="16dp"
android:layout_above="@id/button_clear"/>
<Button
android:id="@+id/button_clear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="C"
android:textSize="20sp"
android:layout_alignParentBottom="true"
android:background="#E57373"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_above="@id/button_clear">

<Button
android:id="@+id/button_seven"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="7"
android:textSize="20sp"/>

<Button
android:id="@+id/button_eight"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="8"
android:textSize="20sp"/>

<Button
android:id="@+id/button_nine"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="9"
android:textSize="20sp"/>

<Button
android:id="@+id/button_divide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="/"
android:textSize="20sp"/>
</LinearLayout>
PRACTICAL – 4

Aim : Write a program to demonstrate list view.

There's a simple Android app demonstrating a ListView :

MainActivity.java :

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

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

// Sample data
String[] countries = {"USA", "Canada", "Australia", "UK", "Germany", "France", "Japan",
"China", "India"};

// Create an ArrayAdapter to bind data to the ListView


ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, countries);

// Get a reference to the ListView


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

// Set the adapter to the ListView


listView.setAdapter(adapter);
}
}
Activity_main.xml (layout file) :

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

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>
PRACTICAL - 5

Aim : Write a program to demonstrate photo gallery.

There's a simple Android app demonstrating a photo gallery using a GridView :


This app displays a GridView of images. When you click on any image, a toast message will
appear showing the clicked image in full size.

MainActivity.java :

import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

GridView gridView;
int[] images = {
R.drawable.image1, R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.image5, R.drawable.image6,
R.drawable.image7, R.drawable.image8, R.drawable.image9
};

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

gridView = findViewById(R.id.gridView);

ImageAdapter imageAdapter = new ImageAdapter(this, images);


gridView.setAdapter(imageAdapter);

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, android.view.View view, int position,
long id) {
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(images[position]);
Toast toast = new Toast(MainActivity.this);
toast.setView(imageView);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show();
}
});
}
}

ImageAdaptor.java :

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {


private Context mContext;
private int[] mImages;

public ImageAdapter(Context context, int[] images) {


mContext = context;
mImages = images;
}

@Override
public int getCount() {
return mImages.length;
}

@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(350, 350));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mImages[position]);
return imageView;
}
}

Main_activity.xml (layout file) :

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

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:verticalSpacing="8dp"
android:horizontalSpacing="8dp"
android:padding="8dp" />

</LinearLayout>
PRACTICAL – 6

Aim : Write a program to demonstrate Date picker and Time picker.

There's an Android app demonstrating the use of DatePicker and TimePicker:


This app contains a DatePicker and a TimePicker. When you select a date and time and click the
"Show Selected Date & Time" button, it will display the selected date and time in the TextViews.

MainActivity.java :

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private TextView selectedDateTextView;


private TextView selectedTimeTextView;
private DatePicker datePicker;
private TimePicker timePicker;
private Button showDateTimeButton;

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

selectedDateTextView = findViewById(R.id.selected_date_textview);
selectedTimeTextView = findViewById(R.id.selected_time_textview);
datePicker = findViewById(R.id.date_picker);
timePicker = findViewById(R.id.time_picker);
showDateTimeButton = findViewById(R.id.show_date_time_button);
showDateTimeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int year = datePicker.getYear();
int month = datePicker.getMonth();
int dayOfMonth = datePicker.getDayOfMonth();
String selectedDate = dayOfMonth + "/" + (month + 1) + "/" + year;
selectedDateTextView.setText("Selected Date: " + selectedDate);

int hourOfDay = timePicker.getCurrentHour();


int minute = timePicker.getCurrentMinute();
String selectedTime = hourOfDay + ":" + minute;
selectedTimeTextView.setText("Selected Time: " + selectedTime);
}
});
}
}

main_activity.xml (layout file) :

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

<TextView
android:id="@+id/selected_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Selected Date: " />

<DatePicker
android:id="@+id/date_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:datePickerMode="spinner" />

<TextView
android:id="@+id/selected_time_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Selected Time: " />

<TimePicker
android:id="@+id/time_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/show_date_time_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected Date & Time" />

</LinearLayout>
PRACTICAL – 7

Aim : Write a program to View and Edit contact.

Here’s the Android application that allows users to view and edit contacts:
This app displays a TextView to show the selected contact and a Button to pick a contact. When
the user clicks the "Pick Contact" button, it requests permission to read contacts. After granting
permission, the user can pick a contact from their contacts list, and the selected contact's name
will be displayed in the TextView.

MainActivity.java :

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

private static final int PERMISSION_REQUEST_READ_CONTACTS = 1;


private static final int PICK_CONTACT_REQUEST = 2;

private TextView contactTextView;


private Button pickContactButton;

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

contactTextView = findViewById(R.id.contact_text_view);
pickContactButton = findViewById(R.id.pick_contact_button);

pickContactButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_REQUEST_READ_CONTACTS);
} else {
pickContact();
}
}
});
}

private void pickContact() {


Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_READ_CONTACTS) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
pickContact();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
Uri contactUri = data.getData();
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String contactName =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactTextView.setText("Contact Name: " + contactName);
cursor.close();
}
}
}
}
}

main_activity.xml (layout file) :

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

<TextView
android:id="@+id/contact_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Selected Contact"
android:layout_marginBottom="16dp"/>

<Button
android:id="@+id/pick_contact_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Contact"
android:layout_below="@id/contact_text_view"/>

</RelativeLayout>
PRACTICAL – 8

Aim : Develop an application to send SMS.

Below is a simple Android application that allows users to send SMS messages :
This app contains two EditText fields to enter the phone number and message, and a Button to
send the SMS. When the user clicks the "Send" button, it requests permission to send SMS
messages. After granting permission, the app sends the SMS message containing the entered
phone number and message.

MainActivity.java :

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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 static final int PERMISSION_REQUEST_SEND_SMS = 1;

private EditText phoneNumberEditText;


private EditText messageEditText;
private Button sendButton;

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

phoneNumberEditText = findViewById(R.id.phone_number_edit_text);
messageEditText = findViewById(R.id.message_edit_text);
sendButton = findViewById(R.id.send_button);

sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST_SEND_SMS);
} else {
sendMessage();
}
}
});
}

private void sendMessage() {


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

try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(this, "SMS sent successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to send SMS", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
if (requestCode == PERMISSION_REQUEST_SEND_SMS) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
sendMessage();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}

main_activity.xml (layout file) :

<?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/phone_number_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone Number"
android:inputType="phone" />

<EditText
android:id="@+id/message_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/phone_number_edit_text"
android:layout_marginTop="16dp"
android:hint="Message" />

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

</RelativeLayout>
PRACTICAL – 9

Aim : Write a program to create a text file in external memory.

Here's a simple Android application that creates a text file in external memory:
This app contains a Button to create a text file. When the user clicks the button, it requests
permission to write to external storage. After granting permission, the app creates a text file
named "example.txt" in the directory "MyFiles" in external storage with the content "This is the
content of the text file.". A toast message is displayed to indicate whether the file creation was
successful or not.

MainActivity.java :

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";


private static final int PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button createFileButton = findViewById(R.id.create_file_button);

createFileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
createFile();
}
}
});
}

private void createFile() {


String filename = "example.txt";
String content = "This is the content of the text file.";

try {
File directory = new File(Environment.getExternalStorageDirectory(), "MyFiles");
if (!directory.exists()) {
directory.mkdirs();
}

File file = new File(directory, filename);


FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
Toast.makeText(this, "File created successfully: " + file.getAbsolutePath(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e(TAG, "Error creating file: " + e.getMessage());
Toast.makeText(this, "Error creating file: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
if (requestCode == PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
createFile();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}

main_activity.xml (layout file) :

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

<Button
android:id="@+id/create_file_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Text File"
android:layout_centerInParent="true"/>

</RelativeLayout>
PRACTICAL – 10

Aim : Write a program to store and fetch data from SQL Lite Database.

Below is a simple Android application demonstrating storing and fetching data


from a SQLite database:
This app creates a SQLite database named "UserData.db" with a table named
"user". It inserts some sample data into the table and fetches it to display in a
TextView.

MainActivity.java :

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

private TextView displayTextView;

private DatabaseHelper databaseHelper;

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

displayTextView = findViewById(R.id.display_text_view);

// Initialize database helper


databaseHelper = new DatabaseHelper(this);
// Inserting data into database
insertData();

// Fetching data from database


fetchData();
}

private void insertData() {


SQLiteDatabase database = databaseHelper.getWritableDatabase();

ContentValues values1 = new ContentValues();


values1.put(DatabaseContract.UserEntry.COLUMN_NAME, "John");
values1.put(DatabaseContract.UserEntry.COLUMN_AGE, 25);

long newRowId1 = database.insert(DatabaseContract.UserEntry.TABLE_NAME, null,


values1);

ContentValues values2 = new ContentValues();


values2.put(DatabaseContract.UserEntry.COLUMN_NAME, "Emma");
values2.put(DatabaseContract.UserEntry.COLUMN_AGE, 30);

long newRowId2 = database.insert(DatabaseContract.UserEntry.TABLE_NAME, null,


values2);

database.close();

if (newRowId1 != -1 && newRowId2 != -1) {


Toast.makeText(this, "Data inserted successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Failed to insert data", Toast.LENGTH_SHORT).show();
}
}

private void fetchData() {


SQLiteDatabase database = databaseHelper.getReadableDatabase();

String[] projection = {
DatabaseContract.UserEntry._ID,
DatabaseContract.UserEntry.COLUMN_NAME,
DatabaseContract.UserEntry.COLUMN_AGE
};

Cursor cursor = database.query(


DatabaseContract.UserEntry.TABLE_NAME,
projection,
null,
null,
null,
null,
null
);

StringBuilder data = new StringBuilder();


while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.UserEntry._ID));
String name =
cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.UserEntry.COLUMN_NAME)
);
int age =
cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.UserEntry.COLUMN_AGE));

data.append("ID: ").append(id).append(", Name: ").append(name).append(", Age:


").append(age).append("\n");
}
cursor.close();
database.close();

displayTextView.setText(data.toString());
}
}

DatabaseHelper.java:

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

public class DatabaseHelper extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;


public static final String DATABASE_NAME = "UserData.db";

private static final String SQL_CREATE_ENTRIES =


"CREATE TABLE " + DatabaseContract.UserEntry.TABLE_NAME + " (" +
DatabaseContract.UserEntry._ID + " INTEGER PRIMARY KEY," +
DatabaseContract.UserEntry.COLUMN_NAME + " TEXT," +
DatabaseContract.UserEntry.COLUMN_AGE + " INTEGER)";

private static final String SQL_DELETE_ENTRIES =


"DROP TABLE IF EXISTS " + DatabaseContract.UserEntry.TABLE_NAME;

public DatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

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

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}

DatabaseContract.java:

import android.provider.BaseColumns;

public final class DatabaseContract {

private DatabaseContract() {
}

public static class UserEntry implements BaseColumns {


public static final String TABLE_NAME = "user";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_AGE = "age";
}
}

main_activity.xml (layout file) :

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

<TextView
android:id="@+id/display_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Data will be displayed here"
android:textColor="@android:color/black" />

</RelativeLayout>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy