0% found this document useful (0 votes)
34 views67 pages

MAD Lab Manual

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

MAD Lab Manual

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

Q1: Write a program by using checkbox, TextView and RelativeLayout to implement list of secondary

color names. As per the multiple color selected by the user, display the selected color names on the
TextView.

String.xml
<resources>
<string name="app_name">SecondaryColor</string>
</resources>

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="wrap_content"
android:scrollbarSize="15dp"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="322dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginStart="46dp"
android:layout_marginEnd="43dp"
android:layout_marginBottom="473dp"
android:text="Button" />

<CheckBox
android:id="@+id/blue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="27dp"
android:layout_marginTop="39dp"
android:text="Blue" />

<CheckBox
android:id="@+id/yellow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/blue"
android:layout_alignParentStart="true"
android:layout_marginStart="26dp"
android:layout_marginTop="35dp"
android:text="Yellow" />

<CheckBox
android:id="@+id/red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/yellow"
android:layout_alignParentStart="true"
android:layout_marginStart="26dp"
android:layout_marginTop="31dp"
android:text="Red" />

<TextView
android:id="@+id/result"
android:layout_width="403dp"
android:layout_height="40dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="0dp"
android:layout_marginTop="314dp"
android:layout_marginEnd="8dp"
android:background="#D6B8B8"
android:gravity="center"
android:text="Result"
android:textSize="20dp" />

</RelativeLayout>

MainActivity.java
package com.divya.secondarycolor;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

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


CheckBox red = findViewById(R.id.red);
CheckBox yellow = findViewById(R.id.yellow);
CheckBox blue = findViewById(R.id.blue);
TextView result = findViewById(R.id.result);

button.setOnClickListener(view -> {
if(red.isChecked()&&yellow.isChecked()&&blue.isChecked())
result.setText("WHITE");

else if(red.isChecked()&&yellow.isChecked())
result.setText("ORANGE");

else if (red.isChecked() && blue.isChecked())


result.setText("VIOLET");

else if(yellow.isChecked() && blue.isChecked())


result.setText("GREEN");
else
result.setText("select 2 or more boxes");
});
}
}

output:

OR

String.xml
<resources>
<string name="app_name">color_checkbox</string>
<string name="orange">orange</string>
<string name="green">green</string>
<string name="violet">violet</string>
</resources>
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">

<CheckBox
android:id="@+id/chxcolor1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/orange"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>

<CheckBox
android:id="@+id/chxcolor2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/green"
android:layout_alignParentLeft="true"
android:layout_below="@+id/chxcolor1"
/>

<CheckBox
android:id="@+id/chxcolor3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/violet"
android:layout_alignParentLeft="true"
android:layout_below="@+id/chxcolor2"
/>

<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textStyle="bold"
android:layout_centerInParent="true"
/>
<Button
android:id="@+id/btnshow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result"
android:textColor="@color/black"
android:layout_below="@+id/chxcolor3"
/>

</RelativeLayout>
MainActivity.java

package com.divya.color_checkbox;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {


CheckBox chxOrange,chxGreen,chxViolet;
String result;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chxOrange=findViewById(R.id.chxcolor1);
chxGreen=findViewById(R.id.chxcolor2);
chxViolet=findViewById(R.id.chxcolor3);
TextView txtResult=findViewById(R.id.txtResult);
Button btn =findViewById(R.id.btnshow);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String result = "Selected colors";
if(chxOrange.isChecked()){
result += "\nOrange";
}
if(chxGreen.isChecked()){
result += "\nGreen";
}
if(chxViolet.isChecked()){
result += "\nViolet";
}

txtResult.setText(result);
}
});

}
}

output:
Q2 Design an android application by using RadioGroup and RadioButton to display list of PG courses
names. Display selected PG course name by the user using Toast.

Strings.xml

<resources>
<string name="app_name">PG_Course_Q2</string>
</resources>

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

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="40dp"
android:layout_marginEnd="10dp"
android:gravity="center">

<RadioButton
android:id="@+id/mba"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"
android:padding="4dp"
android:text="MBA"
android:textAlignment="center"
android:textSize="20sp" />

<RadioButton
android:id="@+id/mca"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"
android:padding="4dp"
android:text="MCA"
android:textAlignment="center"
android:textSize="20sp" />

<RadioButton
android:id="@+id/msc"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="false"
android:padding="4dp"
android:text="M.Sc"
android:textAlignment="center"
android:textSize="20sp" />

</RadioGroup>
</LinearLayout>

</RelativeLayout>

MainActivity.java
package com.divya.pg_course_q2;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

rdogroup=findViewById(R.id.radioGroup);

rdogroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton radioButton = findViewById(i);

Toast.makeText(MainActivity.this, "Selected Course is : " +


radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}

output
Q3 Write an android code by using LinearLayout to accept rating value of a seminar by using RatingBar
and SeekBar. Display provided rating values using TextView components.

Strings.xml
<resources>
<string name="app_name">Rating_val_Seminar</string>
</resources>

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

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical”>
<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginTop="200dp"
android:numStars="5"
android:rating="3.5"/>
<Button
android:id="@+id/btnGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/ratingBar1"
android:layout_below="@+id/ratingBar1"
android:layout_marginTop="30dp"
android:layout_marginLeft="60dp"
android:text="Rating"/>
<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnGet"
android:layout_below="@+id/btnGet"
android:layout_marginTop="20dp"
android:textSize="20dp"
android:textStyle="bold"/>

<SeekBar
android:id="@+id/seekBar1"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="50dp"
android:max="100"
android:indeterminate="false"
android:progress="0"
android:layout_below="@+id/textview1"
/>
<TextView
android:id="@+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/seekBar1"
android:layout_below="@+id/seekBar1"
android:layout_marginTop="40dp"
android:layout_marginLeft="130dp"
android:textSize="20dp"
android:textStyle="bold"/>
</LinearLayout>

</RelativeLayout>

MainActivity.java
package com.divya.rating_val_seminar;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

RatingBar rBar;
SeekBar sBar;
TextView tView, tView2;
Button btn;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

rBar = (RatingBar) findViewById(R.id.ratingBar1);


tView = (TextView) findViewById(R.id.textview1);
btn = (Button)findViewById(R.id.btnGet);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int noofstars = rBar.getNumStars();
float getrating = rBar.getRating();
tView.setText("Rating: "+getrating+"/"+noofstars);
}});
//seekbar
sBar = (SeekBar) findViewById(R.id.seekBar1);
tView2 = (TextView) findViewById(R.id.textview2);
tView2.setText(sBar.getProgress() + "/" + sBar.getMax());
sBar.setOnSeekBarChangeListener(new
SeekBar.OnSeekBarChangeListener() {
int pval = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean
fromUser) {
pval = progress;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
tView2.setText(pval + "/" + seekBar.getMax());
}
});
}
}
output:
Q4 Design an android application to design image gallery by using ImageButton and GridLayout. As per
the ImageButton click, display the image properties using Toast definition.

Strings.xml
<resources>
<string name="app_name">Q4_DesignImageGallary</string>
</resources>

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout 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"
android:rowCount="3"
android:columnCount="3"
android:id="@+id/gridone">
<ImageButton
android:id="@+id/first"
android:layout_width="117dp"
android:layout_height="wrap_content"
android:src="@drawable/back2" />

<ImageButton
android:id="@+id/second"
android:layout_width="127dp"
android:layout_height="122dp"
android:layout_row="0"
android:layout_column="1"
android:src="@drawable/back1" />

<ImageButton
android:id="@+id/third"
android:layout_width="143dp"
android:layout_height="119dp"
android:src="@drawable/back4" />

<ImageButton
android:id="@+id/fourth"
android:layout_width="122dp"
android:layout_height="118dp"
android:src="@drawable/back3" />

</GridLayout>

MainActivity.java
package com.divya.q4_designimagegallary;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

ImageButton btnfirst,btnsecond,btnthird ,btnfourth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnfirst=findViewById(R.id.first);
btnsecond=findViewById(R.id.second);
btnthird=findViewById(R.id.third);
btnfourth=findViewById(R.id.fourth);

btnfirst.setOnClickListener(V->{

Toast.makeText(this, "first Image clicked \n"+"image


id:"+btnfirst.getId(), Toast.LENGTH_SHORT).show();

});
btnsecond.setOnClickListener(V->{

Toast.makeText(this, "second Image clicked \n"+"image


id:"+btnsecond.getId(), Toast.LENGTH_SHORT).show();

});
btnthird.setOnClickListener(V->{

Toast.makeText(this, "third Image clicked \n"+"image


id:"+btnthird.getId(), Toast.LENGTH_SHORT).show();

});
btnfourth.setOnClickListener(V->{

Toast.makeText(this, "fourth Image clicked \n"+"image


id:"+btnfourth.getId(), Toast.LENGTH_SHORT).show();

});

output
Q5. Design an android application by using Spinner component to display secondary colors names. As per
user selected a color from Spinner component, change the activity background color

Strings.xml
<resources>
<string name="app_name">SpinnerComponent_secondaryColor</string>
</resources>

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/txtVw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="150dp"
android:text="Select Color:"
android:textStyle="bold"
android:textSize="15dp" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/txtVw"
android:layout_toRightOf="@+id/txtVw" />

</RelativeLayout>

MainActivity.java
package com.divya.spinnercomponent_secondarycolor;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements


AdapterView.OnItemSelectedListener {

String[] colors = { "pink","skyblue","green" };


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spin = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, colors);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(this);
}

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i,
long l) {

if (colors[i]=="pink")
getWindow().getDecorView().setBackgroundColor(Color.MAGENTA);
if (colors[i]=="skyblue")
getWindow().getDecorView().setBackgroundColor(Color.CYAN);
if (colors[i]=="green")
getWindow().getDecorView().setBackgroundColor(Color.GREEN);

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
}

output

Q6. Write an android code to make phone call using Intent

Strings.xml
<resources>
<string name="app_name">PhoneCall_Intent</string>
</resources>

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="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">

<EditText
android:id="@+id/mobNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter mobile no"
android:inputType="number"
android:maxEms="10"
android:padding="11dp" />

<androidx.appcompat.widget.AppCompatButton
android:id="@+id/callBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call" />

</LinearLayout>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.CALL_PHONE"/>

MainActivity.java
package com.divya.phonecall;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;

import android.content.Intent; import android.net.Uri;


import android.os.Bundle; import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

EditText mobNo = findViewById(R.id.mobNo);


AppCompatButton callBtn = findViewById(R.id.callBtn);

callBtn.setOnClickListener(view -> {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + mobNo.getText().toString()));
startActivity(intent);
});
}
}

output:

Q7. Write an android code to turn ON/OFF Bluetooth

Strings.xml
<resources>
<string name="app_name">OnOffBluetooth</string>
</resources>

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

<Button
android:id="@+id/btnblue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Turn On" />

</RelativeLayout>

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

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />


<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

MainActivity.java
package com.divya.onoffbluetooth;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


int REQUEST_BLUETOOTH = 1;
boolean enable = false;
final BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();

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

Button btntOn = (Button) findViewById(R.id.btnblue);

btntOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth Not
Supported", Toast.LENGTH_SHORT).show();
} else {
if (!bAdapter.isEnabled()) {

if
(ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_BLUETOOTH);
}
{
// startActivityForResult(new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),1);
bAdapter.enable();
btntOn.setText("off");
Toast.makeText(getApplicationContext(), "Bluetooth
Turned on", Toast.LENGTH_SHORT).show();
}
}
else {
btntOn.setText("on");
bAdapter.disable();
Toast.makeText(getApplicationContext(), "Bluetooth is
off", Toast.LENGTH_SHORT).show();
}

}
}
});
} }

output:

Q8 Write an android code to turn ON /OFF the Wi-Fi

Strings.xml
<resources>
<string name="app_name">WiFi_OnOff</string>
</resources>
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="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">

<Button
android:id="@+id/btnwifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Turn On"
android:onClick="enablewifi"/>
<Button
android:id="@+id/btnwifidisalbe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Turn Off"
android:onClick="disablewifi"/>

</LinearLayout>

AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATE "/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-feature android:name="android.hardware.wifi"/>
<uses-permission android:name="android.permission.WAKE_LOCK">
</uses-permission>

MainActivity.java
package com.divya.wifi_onoff;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


boolean enable=false;
int REQUEST_WIFI=1;
WifiManager wifiManager;

Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btntOn = findViewById(R.id.btnwifi);
wifiManager =
(WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE); }
public void enablewifi(View v){
wifiManager.setWifiEnabled(true);
}
public void disablewifi(View v){
wifiManager.setWifiEnabled(true);
}
output:

Q9. Design android application for login activity by using TableLayout. Write android code to check login
credentials with username = "mca" and password = "android". Display appropriate toast message to the
user.

Strings.xml
<resources>
<string name="app_name">Q9_loginUsing_TableLayout</string>
</resources>

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout 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"
android:gravity="center"
android:paddingLeft="100dp">

<TableRow>

<TextView
android:text="Username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />

<EditText
android:id="@+id/edtusername"
android:width="200px"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</TableRow>

<TableRow>

<TextView
android:text="Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />

<EditText
android:id="@+id/edtpass"
android:width="100px"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</TableRow>

<TableRow>
<Button
android:id="@+id/btnlogin"
android:text="Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"/>
</TableRow>

</TableLayout>

MainActivity.java
package com.divya.q9_loginusing_tablelayout;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText edtuser,edtPass;
Button btnLogin;

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

edtuser=findViewById(R.id.edtusername);
edtPass=findViewById(R.id.edtpass);
btnLogin=findViewById(R.id.btnlogin);

btnLogin.setOnClickListener(v->{
if(edtuser.getText().toString().equals("mca") &&
edtPass.getText().toString().equals("android")){

Toast.makeText(this, "Login successful",


Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Please enter correct credentials",
Toast.LENGTH_SHORT).show();
}
});
}
}

output:
Q10 Create a fragment that has its own UI and enable your activities to communicate with fragments.

Strings.xml
<resources>
<string name="app_name">Q10Fragment_its_ownUI</string>
</resources>

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="match_parent"
tools:context=".MainActivity"
android:orientation="horizontal">

<fragment
android:layout_height="match_parent"
android:layout_width="350px"
class="com.divya.q10fragment_its_ownui.Listmenu"
android:id="@+id/fragment"
tools:layout="@layout/fragment_listmenu"
tools:ignore="MissingClass" />

<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.divya.q10fragment_its_ownui.Details"
android:id="@+id/fragment2"
tools:layout="@layout/fragment_details" />

</LinearLayout>

Fragment_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".Details">

<!-- TODO: Update blank fragment layout -->


<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#191515"
android:layout_marginTop="200px"
android:layout_marginLeft="200px"
android:id="@+id/Name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="200px"
android:textColor="#231D1D"
android:id="@+id/Location"/>
</FrameLayout>

Fragment_listmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".Listmenu">

<!-- TODO: Update blank fragment layout -->


<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@android:id/list"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:textIsSelectable="false"
/>
</FrameLayout>

MaintActivity.java
package com.divya.q10fragment_its_ownui;

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);

}
}

Details.java
package com.divya.q10fragment_its_ownui;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

/**
* A simple {@link Fragment} subclass.
* Use the {@link Details#newInstance} factory method to
* create an instance of this fragment.
*/
public class Details extends Fragment {
TextView name,location;

// TODO: Rename parameter arguments, choose names that match


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;

public Details() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Details.
*/
// TODO: Rename and change types and number of parameters
public static Details newInstance(String param1, String param2) {
Details fragment = new Details();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment

View view = inflater.inflate(R.layout.fragment_details, container,


false);
name = (TextView)view.findViewById(R.id.Name);
location = (TextView)view.findViewById(R.id.Location);
return view;

public void change(String uname, String ulocation){


name.setText(uname);
location.setText(ulocation);
}
}

Listmenu.java
package com.divya.q10fragment_its_ownui;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.ListFragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

/**
* A simple {@link Fragment} subclass.
* Use the {@link Listmenu#newInstance} factory method to
* create an instance of this fragment.
*/
public class Listmenu extends ListFragment {

String[] users = new String[] { "Amar","Akabar","Anthony"};


String[] location = new String[]{"Hyderabad","Guntur","Nagpur"};

// TODO: Rename parameter arguments, choose names that match


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters


private String mParam1;
private String mParam2;

public Listmenu() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment Listmenu.
*/
// TODO: Rename and change types and number of parameters
public static Listmenu newInstance(String param1, String param2) {
Listmenu fragment = new Listmenu();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_listmenu, container,
false);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, users);
setListAdapter(adapter);
return view;
}

@Override
public void onListItemClick(@NonNull ListView l, @NonNull View v, int
position, long id) {
getListView().setSelector(android.R.color.holo_blue_dark);
Details txt =
(Details)getFragmentManager().findFragmentById(R.id.fragment2);
txt.change("Name: "+ users[position],"Location : "+ location[position]);
System.out.println("clicked item");
}
}

output

Q11. Demonstrate Array Adapter using List View to display list of fruits.

Strings.xml
<resources>
<string name="app_name">Q11ArrayAdapterFruitsList</string>
</resources>

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="match_parent"
tools:context=".MainActivity">

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

</LinearLayout>

MainActivity.java
package com.divya.q11arrayadapterfruitslist;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {


private ListView mListView;
private ArrayAdapter aAdapter;
private String[] fruit = { "Mango","Kiwi","pear","Grapes","Orange"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mListView = findViewById(R.id.fruitList);
aAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
fruit);
mListView.setAdapter(aAdapter);

} }
output

Q12. Write an application to demonstrate Alert Dialog Box in android

Strings.xml
<resources>
<string name="app_name">Q12AlertDialogBox</string>
</resources>

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="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">

<Button
android:gravity="center"
android:id="@+id/btnalert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="click me"/>

</LinearLayout>

MainActivity.java
package com.divya.q12alertdialogbox;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {


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

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new
AlertDialog.Builder(MainActivity.this);
builder.setTitle("Click Alert")
.setMessage("Are you sure, you want to continue ?")
.setCancelable(false)
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int
which) {
Toast.makeText(MainActivity.this,"Selected
Option: YES",Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int
which) {
Toast.makeText(MainActivity.this,"Selected
Option: No",Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}

Output:
Q13. Demonstrate Options Menu, Context Menu and Popup Menu in android

Strings.xml
<resources>
<string name="app_name">Q13OptionContentPopupMenu</string>
</resources>

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="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center">

<Button
android:id="@+id/btnPopumenu"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text=" Popup menu"/>

<Button
android:id="@+id/btncontext"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="context menu"
/>
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="long press context menu to see result"/>

</LinearLayout>

Menu-folder

Option_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/print_item"
android:title="Print" />
<item android:id="@+id/share_item"
android:title="Share" />
<item android:id="@+id/bookmark_item"
android:title="BookMark" />

</menu>

Popup_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/print_item"
android:title="Print" />
<item android:id="@+id/share_item"
android:title="Share" />
<item android:id="@+id/bookmark_item"
android:title="BookMark" />

</menu>

MainActivity.java
package com.divya.q13optioncontentpopupmenu;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;

public class MainActivity extends AppCompatActivity {


Button btn ,btncontext ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn =findViewById(R.id.btnPopumenu);
btncontext=findViewById(R.id.btncontext);
registerForContextMenu(btncontext);
btn.setOnClickListener(v->{
PopupMenu popup = new PopupMenu(MainActivity.this, v);
//
popup.setOnMenuItemClickListener((PopupMenu.OnMenuItemClickListener)
MainActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
});
}

//option menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu,menu);
return super.onCreateOptionsMenu(menu);
}

//context menu

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "Search");
menu.add(0, v.getId(), 0, "Share");
menu.add(0, v.getId(), 0, "Bookmark");
}
}

output
Q14. Write an application to produce Notification

Strings.xml
<resources>
<string name="app_name">Q14ProduceNofication</string>
</resources>

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="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>

<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Notification"
android:layout_marginTop="200dp"
android:layout_marginLeft="100dp"/>

</LinearLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.NotificationChannel; import


android.app.NotificationManager; import
android.app.PendingIntent; import
android.content.Intent; import android.os.Build; import
android.os.Bundle;

public class MainActivity extends AppCompatActivity {

private static final String CHANNEL_ID = "Notification Channel"; private static final int REQ_CODE =
100;

@Override protected void onCreate(Bundle savedInstanceState)


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

findViewById(R.id.btn).setOnClickListener(view -> {

NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

NotificationCompat.Builder nb = new NotificationCompat.Builder(this,


CHANNEL_ID);

Intent intent = new Intent(MainActivity.this, NewActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(this, REQ_CODE, intent,

PendingIntent.FLAG_UPDATE_CURRENT);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)


{ nb.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("New Message Title")

.setContentText("Context text")

.setSubText("Subtext")

.setContentIntent(pendingIntent)

.setChannelId(CHANNEL_ID)
.build();

nm.createNotificationChannel((new
NotificationChannel(CHANNEL_ID, "Channel One",

NotificationManager.IMPORTANCE_HIGH)));

} else {

nb.setSmallIcon(R.drawable.ic_launcher_background)

.setContentTitle("New Message Title")

.setContentText("Context text")

.setSubText("Subtext")

.setContentIntent(pendingIntent)

.setChannelId(CHANNEL_ID)

.build();

nm.notify(1, nb.build());

});

NewActivity.java package
com.subhdroid.lab_j14;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class NewActivity extends AppCompatActivity {


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

Output:

Q15. Write an android application using SQLite to create table and perform CRUD operations (Example.
COURSE table (ID, Name, Duration, Description), perform ADD, UPDATE, DELETE and READ operations)

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="match_parent" android:gravity="center" android:orientation="vertical"
tools:context=".MainActivity">
<EditText android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="11dp" android:hint="Course
name" android:inputType="text" />

<EditText android:id="@+id/duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="11dp"
android:hint="Duration (in year)"
android:inputType="number" />

<EditText android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="11dp"
android:hint="Description" />

<androidx.appcompat.widget.AppCompatButton android:id="@+id/addBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Course" />

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

<androidx.appcompat.widget.AppCompatButton android:id="@+id/updateBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Update" />
<androidx.appcompat.widget.AppCompatButton android:id="@+id/deleteBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Delete" />

<androidx.appcompat.widget.AppCompatButton android:id="@+id/displayBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Display" />
</LinearLayout>

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

</LinearLayout>

MainActivity.java package
com.subhdroid.lab_j15;

//15. Write an android application using SQLite to create table and perform CRUD operations

// (Example. COURSE table (ID, Name, Duration, Description), perform


ADD, UPDATE,

// DELETE and READ operations)

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle; import


android.view.View; import
android.widget.EditText; import
android.widget.TextView;

import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {

@Override protected void onCreate(Bundle savedInstanceState)


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

MyDBClass mydb = new MyDBClass(this);

EditText name, duration, description; TextView txt =


findViewById(R.id.txtView); name = findViewById(R.id.name);
duration = findViewById(R.id.duration); description =
findViewById(R.id.description);

findViewById(R.id.addBtn).setOnClickListener(view ->
mydb.addRecord(name.getText().toString(), duration.getText().toString(),
description.getText().toString()));

findViewById(R.id.updateBtn).setOnClickListener(view ->
mydb.updateRecord(duration.getText().toString(), name.getText().toString()));
findViewById(R.id.deleteBtn).setOnClickListener(view ->
mydb.deleteRecord(name.getText().toString()));

findViewById(R.id.displayBtn).setOnClickListener(view -> {

ArrayList<CourseModel> list = mydb.getRecords();

String str = "ID Name Duration Description";

for (int i = 0; i < list.size(); i++) {

str += "\n" + list.get(i).id + " " + list.get(i).name + " " + list.get(i).duration + " " +
list.get(i).description;

txt.setText(str);
});
}

CourseModel.java package
com.subhdroid.lab_j15;

public class CourseModel {

String name, duration, description;

int id;

public CourseModel() {

MyDBClass.java package
com.subhdroid.lab_j15;

import android.content.ContentValues; import


android.content.Context; import android.database.Cursor; import
android.database.sqlite.SQLiteDatabase; import
android.database.sqlite.SQLiteOpenHelper; import
android.widget.Toast;

import androidx.annotation.Nullable;

import java.util.ArrayList;
public class MyDBClass extends SQLiteOpenHelper { private static final String
DBName = "LabDB"; private static final int DB_VERSION = 1;
Context context;

public MyDBClass(@Nullable Context context) { super(context, DBName, null,


DB_VERSION); this.context = context;
}

@Override public void onCreate(SQLiteDatabase sqLiteDatabase) {


sqLiteDatabase.execSQL("CREATE TABLE course(id INTEGER PRIMARY KEY AUTOINCREMENT,name
"+

"TEXT,duration TEXT,description TEXT)");

@Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

public void addRecord(String name, String duration, String description) {

SQLiteDatabase database = this.getWritableDatabase();

ContentValues values = new ContentValues(); values.put("name",


name); values.put("duration", duration); values.put("description",
description);

database.insert("course", null, values);

Toast.makeText(context, "Added successfully",


Toast.LENGTH_SHORT).show();

// database.close();

}
public ArrayList<CourseModel> getRecords() { SQLiteDatabase db =
this.getReadableDatabase();

Cursor cursor = db.rawQuery("SELECT * FROM course", null);

ArrayList<CourseModel> recordList = new ArrayList<>();

while (cursor.moveToNext()) {

CourseModel model = new CourseModel();

model.id = cursor.getInt(0); model.name =


cursor.getString(1); model.duration = cursor.getString(2);
model.description = cursor.getString(3);

recordList.add(model);

} return recordList;
}

public void updateRecord(String duration, String name) { SQLiteDatabase db =


this.getWritableDatabase();

ContentValues cv = new ContentValues(); cv.put("duration", duration);

db.update("course", cv, "name=?", new String[]{name});

Toast.makeText(context, "Updated successfully",


Toast.LENGTH_SHORT).show();

public void deleteRecord(String courseName) { SQLiteDatabase database =


this.getWritableDatabase();
database.delete("course", "name=?", new String[]{courseName});

Toast.makeText(context, "Deleted successfully",


Toast.LENGTH_SHORT).show();

Q16. Create an Android app, powered by Firebase Realtime database that supports: Adding Data to
Firebase Realtime database, Retrieving Data from Firebase and Deleting data from firebase data.

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="match_parent" android:gravity="center" android:orientation="vertical"
tools:context=".MainActivity">

<EditText android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="11dp" android:hint="Course
name" android:inputType="text" />

<EditText android:id="@+id/duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="11dp"
android:hint="Duration (in year)"
android:inputType="number" />

<EditText android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="11dp"
android:hint="Description" />

<androidx.appcompat.widget.AppCompatButton android:id="@+id/addBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Add Course" />

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

<androidx.appcompat.widget.AppCompatButton android:id="@+id/updateBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Update" />
<androidx.appcompat.widget.AppCompatButton android:id="@+id/deleteBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Delete" />

<androidx.appcompat.widget.AppCompatButton android:id="@+id/displayBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Display" />
</LinearLayout>

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

</LinearLayout>

MainActivity.java package
com.subhdroid.lab_j16;

import androidx.annotation.NonNull; import


androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle; import


android.os.Handler; import android.util.Log;
import android.widget.EditText; import
android.widget.TextView; import
android.widget.Toast;

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


com.google.firebase.database.DatabaseError; import
com.google.firebase.database.DatabaseReference; import
com.google.firebase.database.FirebaseDatabase; import
com.google.firebase.database.ValueEventListener;

import java.sql.Array; import


java.util.HashMap;

public class MainActivity extends AppCompatActivity {

DatabaseReference courseRef =
FirebaseDatabase.getInstance().getReference("course");

EditText name, duration, description;

TextView txt;

String record = "";

@Override protected void onCreate(Bundle savedInstanceState)


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

txt = findViewById(R.id.txtView); name =


findViewById(R.id.name); duration =
findViewById(R.id.duration); description =
findViewById(R.id.description);

findViewById(R.id.addBtn).setOnClickListener(view -> addRecord());

findViewById(R.id.updateBtn).setOnClickListener(view -> updateRecord());

findViewById(R.id.deleteBtn).setOnClickListener(view -> deleteRecord());

findViewById(R.id.displayBtn).setOnClickListener(view -> { getAllCourse();


Handler handler = new Handler(); handler.postDelayed(new Runnable() {
@Override public void run() {
txt.setText(record);
}

}, 3000);

});

private void addRecord() {

CourseModel courseModel = new CourseModel(name.getText().toString(),


duration.getText().toString(), description.getText().toString());

String courseID = courseRef.push().getKey();

courseRef.child(courseID).setValue(courseModel);

Toast.makeText(this, "Course added", Toast.LENGTH_SHORT).show();

private void deleteRecord() { courseRef.addValueEventListener(new ValueEventListener()


{
@Override

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

HashMap<String, Array> dataMap = (HashMap<String, Array>) dataSnapshot.getValue();


for (String key : dataMap.keySet()) {
courseRef.child(key).addValueEventListener(new ValueEventListener() {

@Override public void onDataChange(@NonNull DataSnapshot snapshot) {

CourseModel course = snapshot.getValue(CourseModel.class);

if (name.getText().toString().equals(course.getName()))
{ snapshot.getRef().removeValue();
Toast.makeText(MainActivity.this, "Record deleted",

Toast.LENGTH_SHORT).show();

@Override

public void onCancelled(@NonNull DatabaseError error) {

Log.d("DB Error : ", error.toString());

});

@Override

public void onCancelled(@NonNull DatabaseError error) {

Toast.makeText(getApplicationContext(), "Fail to get data.",


Toast.LENGTH_SHORT).show();

});

private void updateRecord() { courseRef.addValueEventListener(new ValueEventListener()


{
@Override

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

HashMap<String, Array> dataMap = (HashMap<String, Array>) dataSnapshot.getValue();


for (String key : dataMap.keySet()) {
courseRef.child(key).addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(@NonNull DataSnapshot snapshot) {

CourseModel course = snapshot.getValue(CourseModel.class); if


(name.getText().toString().equals(course.getName())) {
courseRef.child(key).child("duration").setValue(duration.getText().toString());

Toast.makeText(MainActivity.this, "Record Updated",

Toast.LENGTH_SHORT).show();

@Override

public void onCancelled(@NonNull DatabaseError error) { Log.d("DB Error :


", error.toString());
}

});

@Override

public void onCancelled(@NonNull DatabaseError error) {

Toast.makeText(getApplicationContext(), "Fail to get data.",


Toast.LENGTH_SHORT).show();

});

private void getAllCourse() {

courseRef.addValueEventListener(new ValueEventListener() {

@Override

public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

HashMap<String, Array> dataMap = (HashMap<String, Array>) dataSnapshot.getValue();

record = ""; for (String key : dataMap.keySet()) {


courseRef.child(key).addValueEventListener(new ValueEventListener() {

@Override public void onDataChange(@NonNull DataSnapshot snapshot) {


CourseModel course = snapshot.getValue(CourseModel.class);

String str = "\n" + course.getName() + " " + course.getDuration() +

" " + course.getDescription();

record += str;

@Override

public void onCancelled(@NonNull DatabaseError error) {

Log.d("DB Error : ", error.toString());

});

@Override

public void onCancelled(@NonNull DatabaseError error) {

Toast.makeText(getApplicationContext(), "Fail to get data.",


Toast.LENGTH_SHORT).show();

});

CourseModel.java package
com.subhdroid.lab_j16;

public class CourseModel {

String name, duration, description;


CourseModel(String name, String duration, String description) { this.name = name;
this.duration = duration; this.description = description;
}

public CourseModel() {

public String getName() { return name;


}

public void setName(String name) { this.name = name;


}

public String getDuration() { return duration;


}

public void setDuration(String duration) { this.duration = duration;


}

public String getDescription() { return description;


}

public void setDescription(String description) { this.description = description;


}

}
Q 17. Demonstrate WebView to display the web pages in an android application.

Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

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="match_parent" android:gravity="center" android:orientation="vertical"
tools:context=".MainActivity">

<WebView android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<androidx.appcompat.widget.AppCompatButton
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Go to
Google" />

<ProgressBar android:id="@+id/pgBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />

</LinearLayout>

MainActivity.java package
com.subhdroid.lab_j17;

//17. Demonstrate WebView to display the web pages in an android application.

import androidx.appcompat.app.AppCompatActivity; import


androidx.appcompat.widget.AppCompatButton;

import android.graphics.Bitmap; import


android.os.Bundle; import android.view.View;
import android.webkit.WebView; import
android.webkit.WebViewClient; import
android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {

WebView webView;

ProgressBar pgBar;

AppCompatButton btn;

@Override protected void onCreate(Bundle savedInstanceState)


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

webView = findViewById(R.id.webView); pgBar =


findViewById(R.id.pgBar); btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view)
{ webView.loadUrl("https://www.google.com");
pgBar.setVisibility(View.VISIBLE); webView.setWebViewClient(new
WebViewClient() {
@Override public void onPageStarted(WebView view, String url, Bitmap
favicon) { super.onPageStarted(view, url, favicon);
}

@Override public void onPageFinished(WebView view, String url) {


pgBar.setVisibility(View.GONE); btn.setVisibility(View.GONE);
super.onPageFinished(view, url);
}

});

});

}
@Override public void onBackPressed() {
if (webView.canGoBack())
{ webView.goBack();
} else {

super.onBackPressed();

Q 18. Write an android app to write JSON data into a file and read JSON data from created file.

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="match_parent" android:gravity="center" android:orientation="vertical"
tools:context=".MainActivity">

<EditText android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter name" />

<EditText android:id="@+id/mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter phone no" />

<androidx.appcompat.widget.AppCompatButton android:id="@+id/setDataBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Set Data" />

<androidx.appcompat.widget.AppCompatButton
android:id="@+id/getDataBtn" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Get Data" />

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

</LinearLayout>

MainActivity.java

package com.subhdroid.lab_j18;
//18. Write an android app to write JSON data into a file and read JSON data from created file.

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.widget.AppCompatButton;

import android.os.Bundle; import


android.widget.EditText; import
android.widget.TextView; import
android.widget.Toast;

import org.json.JSONException; import


org.json.JSONObject;

import java.io.BufferedReader; import


java.io.BufferedWriter; import java.io.File;
import java.io.FileReader; import
java.io.FileWriter; import java.io.IOException;

public class MainActivity extends AppCompatActivity {

AppCompatButton setDataBtn, getDataBtn;

EditText name, mobile;

TextView data;

@Override protected void onCreate(Bundle savedInstanceState)


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

name = findViewById(R.id.name); mobile =


findViewById(R.id.mobile); data = findViewById(R.id.data);

setDataBtn = findViewById(R.id.setDataBtn); getDataBtn =


findViewById(R.id.getDataBtn);
setDataBtn.setOnClickListener(view -> setData());

getDataBtn.setOnClickListener(view -> getData());

private void setData() {

JSONObject jsonObject = new JSONObject(); try {


jsonObject.put("Name", name.getText().toString());
jsonObject.put("Phone", mobile.getText().toString()); } catch (JSONException e)
{ e.printStackTrace();
}

String userString = jsonObject.toString(); try {


File file = new File(getApplicationContext().getFilesDir(),
"LAB_J18.json");

FileWriter fileWriter = new FileWriter(file);

BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);


bufferedWriter.write(userString);

bufferedWriter.close(); } catch
(IOException e) { e.printStackTrace();
}

Toast.makeText(this, "Data Set", Toast.LENGTH_SHORT).show();

private void getData() {

try {

File file = new File(getApplicationContext().getFilesDir(), "LAB_J18.json");

FileReader fileReader = new FileReader(file);

BufferedReader bufferedReader = new BufferedReader(fileReader);

StringBuilder stringBuilder = new StringBuilder(); String line =


bufferedReader.readLine(); while (line != null)
{ stringBuilder.append(line).append("\n"); line =
bufferedReader.readLine();
}

bufferedReader.close();

String response = stringBuilder.toString();

JSONObject jsonObject = new JSONObject(response); String rec =


"Name : " + jsonObject.get("Name"); rec += "\nPhone : " +
jsonObject.get("Phone"); data.setText(rec);

} catch (IOException e) { e.printStackTrace();

} catch (JSONException e) { e.printStackTrace();


}

}
Q19. Write an application to display a PDF as an image in React app using URL

Step 1: Create React App


npx create-react-app appname
cd appname
npm start
Step 2: Install react-pdf package.
npm install react-pdf
Step 3: First make a separate component PDF (name of the component, can be
anything) and render the PDF component in App.js.

App.js
import React from 'react';
import Pdf from './Pdf'

const App = ()=> {

return (
<div className="App">
//Rendering a pdf component
<Pdf />
</div>
);
}

export default App;

Step 4: In this section, we load the PDF and render it on your app.
Document: Loads a document passed using file prop.
File Prop: It tells what PDF should be displayed, In the above code, we pass URL to it.
URL: The URL consists of two parts here.
 The 1st part is due to preventing cors error, you may refer docs to read more
about the core.
1st part: https://cors-anywhere.herokuapp.com/
 The 2nd part is our actual URL of PDF.
2nd part: http://www.pdf995.com/samples/pdf.pdf
One more thing we need to do is ENABLE PDF.JS WORKER, you could use
pdf.worker.js from an external CDN.
onDocumentLoadSuccess: When the document gets successfully loaded we
set the state of page number to tells on which page number of pdf the user is.
Pdf.js: Now open the PDF component.

Pdf.js

Step 5: Now the last thing add NEXT and PREVIOUS buttons to PDF file.
Pdf.js: Here we added two buttons NEXT AND PREVIOUS and their functions
named previousPage() and nextPage() which change the state of the current
page.

import React, { useState } from 'react';


import { Document, Page,pdfjs } from 'react-pdf';

const url =
"https://cors-anywhere.herokuapp.com/http://
www.pdf995.com/samples/pdf.pdf"

export default function Test() {


pdfjs.GlobalWorkerOptions.workerSrc =
`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
const [numPages, setNumPages] = useState(null);
const [pageNumber, setPageNumber] = useState(1);

/*To Prevent right click on screen*/


document.addEventListener("contextmenu",
(event) => { event.preventDefault();
});

/*When document gets loaded


successfully*/ function
onDocumentLoadSuccess({ numPages })
{ setNumPages(numPages);
setPageNumber(1);
}

function changePage(offset)
{ setPageNumber(prevPageNumber =>
prevPageNumber + offset);
}

function
previousPage()
{ changePage(-
1);
}

function
nextPage()
{ changePag
e(1);
}
return (
<>
<div className="main">
<Document
file={url}
onLoadSuccess={onDocumentLoadSuccess}
>
<Page pageNumber={pageNumber} />
</Document>
<div>
<div className="pagec">
Page {pageNumber || (numPages ? 1 : '--')} of {numPages
|| '--'}
</div>
<div className="buttonc">
<button
type="button"
disabled={pageN
umber <= 1}
onClick={previo
usPage}
className="Pre"

>
Previous
</button>
<button
type="button"
disabled={pageNumber
>= numPages}
onClick={nextPage}

>
Next
</button>
</div>
</div>
</div>
</>
);
}

Q20. Develop simple flutter application to open a browser using Android SDK

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