Final Mad File

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

GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY

INSTITUTE OF INNOVATION IN TECHNOLOGY & MANAGEMENT

MOBILE APPLICATION DEVELOPMENT

LAB PRACTICAL FILE

BCA-318

Submitted To: Submitted By:

Mr. Kanhiya Lal Name: PRATHAM KANGRA

(Assistant Professor-IT) Enrolment no: 02324402021

BCA VI(E1)
INDEX

S.NO PRACTICALS DATE FACULTY SIGN

1 Setup and install Android Studio for


Android Application Development

2 Create "hello world" application to display


"hello world" in the middle of the screen in
the emulator as well as android phone

3 Create an android app to display various


android lifecycle phases.

4 Create a calculator app that performs


addition, subtraction, division and
multiplication operation on numbers.

5 Write an Android application to convert


into different currencies for example,
Rupees to dollar

6 Write an android Application to create


custom toast.

7 Create an application to take picture using


native application

8 Create an application to pick up any image


from the native application gallery and
display it on the screen

9 Create an application to perform the


operations of create, insert, delete, view and
update, using sqlite database.

10 Read phonebook contacts using content


providers and display in list.

11 Create an application that uses checkbox


for construction of a shopping list so the
user can check off items as they are picked
up. The checked items should be displayed
in a textview control.

12 Write an android application to parse


JSON and show into Recycler view.
PRACTICAL 1:
SETUP AND INSTALL ANDROID STUDIO FOR ANDROID APPLICATION
DEVELOPMENT
STEPS:
Downloading Android Studio:
 Open any web browser and navigate to the Android Studio download page.
 Click on "Download Android Studio" to start the download.
 Read and agree to the Terms and Conditions by selecting the checkbox.
 Save the downloaded file to a location on your computer, such as the Downloads folder.
 Installing Android Studio on Windows:
 Navigate to the folder where you downloaded the Android Studio installation file.
 Double-click the downloaded file to start the installation process.
 If prompted by the User Account Control dialog, click "Yes" to allow the installation to make
changes to your computer.
 Follow the instructions provided in the installation wizard.
 Accept the default installation settings for all steps.
 Click "Finish" when the installation is complete to launch Android Studio.
 Choose your preference for the light or dark theme when Android Studio first launches.
Additional Component Installation:
 During the installation process, the setup wizard will download and install additional
components and tools needed for Android app development.
 Depending on your internet speed, this process may take some time.
 If prompted by User Account Control dialogs or Windows Security Alerts, click "Yes" or
"Allow Access" to continue the installation.
Output:
Practical 2:
Create "hello world" application to display "hello world" in the middle of the screen in the
emulator as well as android phone
CODE:

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


<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main"
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="Hello World!"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

OUTPUT:
PRACTICAL 3:
CREATE AN ANDROID APP TO DISPLAY VARIOUS ANDROID LIFECYCLE PHASES.
CODE:
DESIGN (ACITIVITY_MAIN.XML)

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


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textLifecycle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Lifecycle State"
android:textSize="24sp" />
</RelativeLayout>

LOGIC (MainActivity.java)

package com.example.myapplication2lifecycle;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView textLifecycle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLifecycle = findViewById(R.id.textLifecycle);
updateLifecycleState("onCreate");
Log.d("lifecycle", "onCreate() method executed"); }

@Override
protected void onStart() {
super.onStart();
updateLifecycleState("onStart");
Log.d("lifecycle", "onStart() method executed");}

@Override
protected void onResume() {
super.onResume();
updateLifecycleState("onResume");
Log.d("lifecycle", "onResume() method executed");
}

@Override
protected void onPause() {
super.onPause();
updateLifecycleState("onPause");
Log.d("lifecycle", "onPause() method executed");
}

@Override
protected void onStop() {
super.onStop();
updateLifecycleState("onStop");
Log.d("lifecycle", "onStop() method executed");
}

@Override
protected void onDestroy() {
super.onDestroy();
updateLifecycleState("onDestroy");
Log.d("lifecycle", "onDestroy() method executed");
}

@Override
protected void onRestart() {
super.onRestart();
updateLifecycleState("onRestart");
Log.d("lifecycle", "onRestart() method executed");
}

@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
updateLifecycleState("onAttachedToWindow");
Log.d("lifecycle", "onAttachedToWindow() method executed");
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
updateLifecycleState("onDetachedFromWindow");
Log.d("lifecycle", "onDetachedFromWindow() method executed");
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
updateLifecycleState("onSaveInstanceState");
Log.d("lifecycle", "onSaveInstanceState() method executed");
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
updateLifecycleState("onRestoreInstanceState");
Log.d("lifecycle", "onRestoreInstanceState() method executed");
}
@Override
public void finish() {
// Call finish() to ensure onDestroy() is called before the
activity is finished.
updateLifecycleState("onDestroy (called by finish())");
Log.d("lifecycle", "onDestroy (called by finish()) method
executed");
super.finish();
}

private void updateLifecycleState(String state) {


textLifecycle.append("\n" + state);
}
}
OUTPUT:

HERE IS THE APP CREATED

CREATION STATE OF AN PAUSE STATE OF AN


ANDROID APPLICATION ANDROID APPLICATION
RESTART() CYCLE OF AN
ANDROID’S APP LIFECYCLE

STOP() AND DESTROY()


IN THE LOGCAT
PRACTICAL-4
CREATE A CALCULATOR APP THAT PERFORMS ADDITION, SUBTRACTION,
DIVISION, AND MULTIPLICATION OPERATION ON NUMBERS.
CODE:

(DESIGN)
(ACTIVITY_MAIN.JAVA)

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint=" ENTER NUMBER 1"
android:textSize="30sp"
android:inputType="numberDecimal"
android:layout_marginTop="16dp"/>3
<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editTextNumber1"
android:hint=" ENTER NUMBER 2"
android:textSize="30sp"
android:inputType="numberDecimal"
android:layout_marginTop="16dp"/>
<TextView
android:id="@+id/textViewResult"
android:layout_width="match_parent"
android:layout_height="104dp"
android:layout_below="@id/editTextNumber2"
android:layout_marginTop="19dp"
android:text="RESULT"
android:textSize="30sp"
android:textAlignment="center" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/textViewResult"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<Button
android:id="@+id/buttonAdd"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="+"/>
<Button
android:id="@+id/buttonSubtract"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="-"/>
<Button
android:id="@+id/buttonMultiply"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="x"/>
<Button
android:id="@+id/buttonDivide"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="/"/>
</LinearLayout>
</RelativeLayout>

LOGIC (activity_main.xml)
package com.example.myapplication3calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


private EditText num1EditText1;
private EditText num2EditText2;
private TextView texViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1EditText1 = findViewById(R.id.editTextNumber1);
num2EditText2 = findViewById(R.id.editTextNumber2);
texViewResult = findViewById(R.id.textViewResult);

findViewById(R.id.buttonAdd).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(num1EditText1.getText().toString());
double num2 = Double.parseDouble(num2EditText2.getText().toString());
double result = num1 + num2;
texViewResult.setText(String.valueOf(result));}});
findViewById(R.id.buttonSubtract).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(num1EditText1.getText().toString());
double num2 = Double.parseDouble(num2EditText2.getText().toString());
double result = num1 - num2;
texViewResult.setText(String.valueOf(result));}});
findViewById(R.id.buttonMultiply).setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(num1EditText1.getText().toString());
double num2 = Double.parseDouble(num2EditText2.getText().toString());
double result = num1 * num2;
texViewResult.setText(String.valueOf(result)); }});
findViewById(R.id.buttonDivide).setOnClickListener(new
View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
double num1 = Double.parseDouble(num1EditText1.getText().toString());
double num2 = Double.parseDouble(num2EditText2.getText().toString());
if (num2 == 0) {
texViewResult.setText("Cannot divide by zero");}else {
double result = num1 / num2;
texViewResult.setText(String.valueOf(result));}}});}}

OUTPUT:

ADDITION DIFFERENCE PRODUCT DIVISION


PRACTICAL 5:
WRITE AN ANDROID APPLICATION TO CONVERT INTO DIFFERENT CURRENCIES,
FOR EXAMPLE, RUPEES TO THE DOLLAR.
CODE:
(DESIGN: ACTIVITY_MAIN.XML)

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextAmount"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:inputType="numberDecimal"
android:text="enter_amount" />
<Spinner
android:id="@+id/SpinnerFrom"
android:layout_width="338dp"
android:layout_height="43dp" />
<Spinner
android:id="@+id/spinnerTo"
android:layout_width="359dp"
android:layout_height="69dp" />
<Button
android:id="@+id/btn1"
android:layout_width="235dp"
android:layout_height="68dp"
android:text="convert" />
<TextView
android:id="@+id/textViewResult"
android:layout_width="213dp"
android:layout_height="82dp"
android:layout_below="@id/btn1"
android:layout_marginTop="181dp"
android:text="result" />
</RelativeLayout>

LOGIC : MainActivity.java

package com.example.myapplication5;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
private EditText editTextAmount;
private Spinner SpinnerFrom, SpinnerTo;
private TextView textViewResult;
private final String[] currencies = {"USD", "EUR", "DHR", "INR", "PESO"};
// Add more currencies
private final double[][] conversations = {
{1.0, 0.85, 0.73, 74.87, 112.61},
{1.18, 1.0, 0.86, 86.66, 133.11},
{1.37, 1.16, 1.0, 102.33, 153.74},
{0.013, 0.011, 0.0096, 1.0, 1.5},
{0.0089, 0.0075, 0.0065, 0.088, 1.0} };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAmount = findViewById(R.id.editTextAmount);
SpinnerFrom = findViewById(R.id.SpinnerFrom);
SpinnerTo = findViewById(R.id.spinnerTo);
Button btn1 = findViewById(R.id.btn1);
textViewResult = findViewById(R.id.textViewResult);

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,


android.R.layout.simple_spinner_item,currencies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_it
em);

SpinnerFrom.setAdapter(adapter);
SpinnerTo.setAdapter(adapter);
SpinnerFrom.setSelection(0); // set default selection
SpinnerTo.setSelection(1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
convertCurrency();
}
@SuppressLint("SetTextI18n")
private void convertCurrency() {
try {
double amount = Double.parseDouble(editTextAmount.getText().toString());
int fromIndex = SpinnerFrom.getSelectedItemPosition();
int toIndex = SpinnerTo.getSelectedItemPosition();double result = amount *
conversations[fromIndex][toIndex];
DecimalFormat df = new DecimalFormat("#.##");
String formattedResult = df.format(result);
textViewResult.setText(amount + " " + currencies[fromIndex] + " = " +
formattedResult + " " + currencies[toIndex]);}
catch (NumberFormatException e){
textViewResult.setText("Invalid Input");}}});}}
OUTPUT:
Practical 6
Write an Android application to create custom toast
CODE:
DESIGN(ACITIVITY_MAIN.XML)

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="140dp"
tools:context=".MainActivity"/>
<?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="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:padding="16dp"
android:orientation="horizontal"
android:id="@+id/custom_id">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:textSize="16sp"
android:textStyle="bold"/>
</LinearLayout>

LOGIC(MainActivity.java)

package com.example.customtoast;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomToast();
}
});*/
showCustomToast("onCreate()");
}

@Override
protected void onStart() {
super.onStart();
showCustomToast("onStart()");

@Override
protected void onRestart() {
super.onRestart();
showCustomToast("onRestart()");
}

@Override
protected void onResume() {
super.onResume();
showCustomToast("onResume()");
}

@Override
protected void onPause() {
super.onPause();
showCustomToast("onPause()");
}

@Override
protected void onStop() {
super.onStop();
showCustomToast("onStop()");
}

@Override
protected void onDestroy() {
super.onDestroy();
showCustomToast("onDestroy()");
}

public void showCustomToast(String str)


{
View layout=
getLayoutInflater().inflate(R.layout.customtoast_layout,(ViewGroup)
findViewById(R.id.custom_id));
TextView textView=layout.findViewById(R.id.text);
textView.setText(str);
Toast toast=new Toast(this);
toast.setGravity(Gravity.CENTER,0,0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
OUTPUT
PRACTICAL 7
CREATE A ANDROID APPLICATION TO TAKE PICTURE USING NATIVE
APPLICATION
CODE :

DESIGN: ANDROIDMANIFEST.XML

<?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-feature 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.NativApplication"
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>

ACTIVITY_MAIN.XML

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Picture"
android:textSize="15sp"
android:id="@+id/btn"/>
</LinearLayout>
LOGIC :MainActivity.java

package com.example.nativapplication;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Button IMAGE;
ImageView view;
ActivityResultLauncher<Intent> mStartForResult =
registerForActivityResult(new
ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {

Toast.makeText(getApplicationContext(),result.toString(),Toast.LENGTH_LONG)
.show();
if (result.getResultCode() == Activity.RESULT_OK) {
Intent intent = result.getData();
Bundle data=intent.getExtras();
Bitmap bitmap= (Bitmap) data.get("data");
view.setImageBitmap(bitmap);
}
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IMAGE=findViewById(R.id.btn);
view=findViewById(R.id.imageview);
IMAGE.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mStartForResult.launch(intent);
}
});
}
}
OUTPUT:
PRACTICAL 8
CREATE AN APPLICATION TO PICK UP ANY IMAGE FROM THE NATIVE APPLICATION
GALLERY AND DISPLAY IT ON THE SCREEN

CODE :

DESIGN: ACTIVITY_MAIN.XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.customview.MyCustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/cutom_view"/>
</RelativeLayout>

LOGIC :MainActivity.java
package com.example.customview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}}
package com.example.customview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class MyCustomView extends View {
private Paint paint;
public MyCustomView(Context context) {
super(context);
init();}
public MyCustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();}
private void init()
{ paint=new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL);}
@Override
protected void onDraw(@NonNull Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(150,150,getWidth()-120,getHeight()-120,paint);
}}
PRACTICAL-9.
CREATE AN ANDROID APPLICATION TO PERFORM OPERATIONS OF CREATE ,
INSERT, DELETE VIEW AND UPDATE, USING SQLITE DATABASE.
CODE:
DESIGN: ACITIVITY_MAIN.XML

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/Name1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
android:hint="@string/enter_name" />
<EditText
android:id="@+id/Age1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/Name1"
android:ems="10"
android:hint="@string/enter_age"
android:inputType="text"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="64dp" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/add"
android:layout_below="@id/Age1"/>
<Button
android:id="@+id/buttonUpdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/update"
android:layout_below="@id/button1"/>
<Button
android:id="@+id/Delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/delete"
android:layout_below="@id/buttonUpdate"/>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/Delete"
android:layout_marginTop="16dp"/>
</RelativeLayout>
LOGIC :MainActivity.java
package com.example.crud;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


SQLiteDatabase sqLiteDatabase;
EditText Name1, Age1;
Button button1, buttonUpdate, Delete, buttonView;
ListView listView;
ArrayList<String> arrayList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
DBHelper dbHelper;

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

dbHelper = new DBHelper(this);


sqLiteDatabase = dbHelper.getWritableDatabase();
Name1 = findViewById(R.id.Name1);
Age1 = findViewById(R.id.Age1);
button1 = findViewById(R.id.button1);
buttonUpdate = findViewById(R.id.buttonUpdate);
Delete = findViewById(R.id.Delete);
buttonView = findViewById(R.id.buttonView);
listView = findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);

displayData();

button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = Name1.getText().toString().trim();
String age = Age1.getText().toString().trim();

if (!name.isEmpty() && !age.isEmpty()){


ContentValues contentValues = new ContentValues();
contentValues.put("Name", name);
contentValues.put("Age", age);

long id = sqLiteDatabase.insert("Persons", null,


contentValues);

if (id != -1){
Toast.makeText(MainActivity.this, "Data inserted
Successfully", Toast.LENGTH_LONG).show();
Name1.setText("");
Age1.setText("");
}
else {
Toast.makeText(MainActivity.this, "Failed to insert
Data", Toast.LENGTH_LONG).show();
}

}
else {
Toast.makeText(MainActivity.this, "Please enter name
and age", Toast.LENGTH_LONG).show();
}
}
});

buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Placeholder for update operation
Toast.makeText(MainActivity.this, "Update operation
clicked", Toast.LENGTH_LONG).show();

}
});

Delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Placeholder for delete operation
Toast.makeText(MainActivity.this, "Delete operation
clicked", Toast.LENGTH_LONG).show();

}
});

listView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
String selectedItem = arrayList.get(position);
String[] parts = selectedItem.split(": ");
String personId = parts[0];

int rowsDeleted = sqLiteDatabase.delete("Persons", "Id=?",


new String[]{personId});

if (rowsDeleted > 0) {
Toast.makeText(MainActivity.this, "Data deleted
successfully", Toast.LENGTH_LONG).show();
displayData();
}
else {
Toast.makeText(MainActivity.this, "Failed to delete
data", Toast.LENGTH_LONG).show();
}
}
});

}
private void displayData(){
arrayList.clear();
@SuppressLint("Recycle") Cursor cursor =
sqLiteDatabase.rawQuery("SELECT * FROM Persons", null);
if (cursor.moveToFirst()){
do {
@SuppressLint("Range") String name =
cursor.getString(cursor.getColumnIndex("Name"));
@SuppressLint("Range") String age =
cursor.getString(cursor.getColumnIndex("Age"));

arrayList.add(" "+name + " "+age);

} while (cursor.moveToNext());

}
arrayAdapter.notifyDataSetChanged();
cursor.close();
}

DBHelper.java
package com.example.crud;

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

public class DBHelper extends SQLiteOpenHelper {


private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;

public DBHelper(Context context){


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

@Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE Persons (Id INTEGER PRIMARY KEY
AUTOINCREMENT, Name TEXT, Age TEXT)";
db.execSQL(createTable);

}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS Persons");
onCreate(db);
}
}
OUTPUT
PRACTICAL-10
READ PHONEBOOK CONTACTS USING CONTENT PROVIDERS AND DISPLAY IT IN LIST.

CODE:
DESIGN:Activity_layout.xml

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


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

LOGIC : MainActivity.java

package com.example.contact;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


private static final int REQUEST_CODE_READ_CONTACTS = 101;
private ArrayAdapter<String> contactsAdapter;
private final ArrayList<String> contactsList = new ArrayList<>();

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

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


contactsAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, contactsList);
contactListView.setAdapter(contactsAdapter);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE_READ_CONTACTS);
}
else {
fetchContacts();
}}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults){
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
if (requestCode == REQUEST_CODE_READ_CONTACTS){
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
fetchContacts();

}
} }

private void fetchContacts() {


Cursor cursor =
getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
null,null,null,null);
if (cursor != null){
while (cursor.moveToNext()){
@SuppressLint("Range") String name =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NA
ME));
contactsList.add(name);
}
cursor.close();
contactsAdapter.notifyDataSetChanged();
}
}
}

OUTPUT:
PRACTICAL11.
CREATE AN APPLICATION THAT USES CHECKBOX FOR CONSTRUCTION OF A
SHOPPING LIST SO THE USER CAN CHECK OFF ITEMS AS THEY ARE PICKED UP.
THE CHECKED ITEMS SHOULD BE DISPLAYED IN A TEXTVIEW CONTROL.

CODE:
DESIGN

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/Grapes"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox1"
android:text="@string/Guava"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox2"
android:text="@string/watermelon"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<CheckBox
android:id="@+id/checkBox4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox3"
android:text="@string/Apple"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<CheckBox
android:id="@+id/checkBox5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox4"
android:text="@string/Orange"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="114dp"
android:layout_below="@id/checkBox5"
android:layout_marginTop="4dp"
android:text="" />
</RelativeLayout>
LOGIC: MainActivity.java

package com.example.check;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private CheckBox checkBox1;


private CheckBox checkBox2;
private CheckBox checkBox3;
private CheckBox checkBox4;
private CheckBox checkBox5;

private TextView textView1;


private CompoundButton.OnCheckedChangeListener checkBoxListener;

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

checkBox1 = findViewById(R.id.checkBox1);
checkBox2 = findViewById(R.id.checkBox2);
checkBox3 = findViewById(R.id.checkBox3);
checkBox4 = findViewById(R.id.checkBox4);
checkBox5 = findViewById(R.id.checkBox5);
textView1 = findViewById(R.id.textView1);

// Set listeners for checkboxes


checkBox1.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
updateTextView();
}
});

checkBox2.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
updateTextView();
}
});

checkBox3.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
updateTextView();
}
});
checkBox4.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
updateTextView();
}
});

checkBox5.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
updateTextView();
}
});

CompoundButton.OnCheckedChangeListener checkedChangeListener = new


CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
updateTextView();
}
};
checkBox1.setOnCheckedChangeListener(checkBoxListener);
checkBox2.setOnCheckedChangeListener(checkBoxListener);
checkBox3.setOnCheckedChangeListener(checkBoxListener);
checkBox4.setOnCheckedChangeListener(checkBoxListener);
checkBox5.setOnCheckedChangeListener(checkBoxListener);
}

private void updateTextView() {


StringBuilder stringBuilder = new StringBuilder();

if (checkBox1.isChecked()){
stringBuilder.append("Grapes \n");
}
if (checkBox2.isChecked()){
stringBuilder.append("Guava \n");
}
if (checkBox3.isChecked()){
stringBuilder.append("watermelon \n");
}
if (checkBox4.isChecked()){
stringBuilder.append("Apple \n");
}
if (checkBox5.isChecked()){
stringBuilder.append("Orange \n");
}

textView1.setText(stringBuilder.toString());
}
}
OUTPUT
PRACTICAL-12
Write an android application to parse JSON and show into Recycler view
CODE:
MainActivity.java

package com.example.recyclerviewdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


public RecyclerView recyclerView;
public ArrayList<String> name;
public ArrayList<String> classes;
public CustomAdapter customAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.item_list);
// recyclerView.setLayoutManager(new
LinearLayoutManager(getApplicationContext()));
recyclerView.setLayoutManager(new
GridLayoutManager(MainActivity.this,2));
name=new ArrayList<String>();
classes=new ArrayList<String>();
name.add("A");
name.add("B");
name.add("C");
name.add("D");
classes.add("BCA");
classes.add("BBA");
classes.add("BTech");
classes.add("BArch");
name.add("A");
name.add("B");
name.add("C");
name.add("D");
classes.add("BCA");
classes.add("BBA");
classes.add("BTech");
classes.add("BArch");
name.add("A");
name.add("B");
name.add("C");
name.add("D");
classes.add("BCA");
classes.add("BBA");
classes.add("BTech");
classes.add("BArch");
name.add("A");
name.add("B");
name.add("C");
name.add("D");
classes.add("BCA");
classes.add("BBA");
classes.add("BTech");
classes.add("BArch");
name.add("A");
name.add("B");
name.add("C");
name.add("D");
classes.add("BCA");
classes.add("BBA");
classes.add("BTech");
classes.add("BArch");
customAdapter=new
CustomAdapter(name,classes,getApplicationContext());
recyclerView.setAdapter(customAdapter);
}
}
CustomAdapter
package com.example.recyclerviewdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class CustomAdapter extends


RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private ArrayList<String>name;
private ArrayList<String>classes;
private Context context;

public CustomAdapter(ArrayList<String> name, ArrayList<String> classes,


Context context) {
this.name = name;
this.classes = classes;
this.context = context;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int
viewType) {
View view=
LayoutInflater.from(context).inflate(R.layout.item_custom_list,parent,false
);
return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int
position) {
holder.nm.setText(name.get(position));
holder.cl.setText(classes.get(position));
}
@Override
public int getItemCount() {
return name.size();
}

public class MyViewHolder extends RecyclerView.ViewHolder


{
public TextView nm;
public TextView cl;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
nm=itemView.findViewById(R.id.name_item);
cl=itemView.findViewById(R.id.class_item);
}
}
}

DESIGN :Xml part

cutom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardBackgroundColor="@color/meng"
app:cardCornerRadius="5mm"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/name_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Name"
android:textSize="25dp"
/>
<TextView
android:id="@+id/class_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Class"
android:textSize="25dp"
/>
</LinearLayout>
</androidx.cardview.widget.CardView>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/item_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>

OUTPUT:

You might also like