Uploaded by baasim s

Android Journal

advertisement
INDEX
Contents
Practical – 1.................................................................................................................. 2
Aim: Create a Android App to Run Hello World Program............................................. 2
Practical – 2.................................................................................................................. 5
Aim: Create an android app that demonstrates working with TextView Elements...... 5
Practical - 3................................................................................................................. 11
Aim: Create an android app that demonstrates ActivityLifecycle.............................. 11
Practical – 4................................................................................................................ 14
Aim: Create an android app that demonstrates the use of Alert................................ 14
Practical – 5................................................................................................................ 17
Aim: Create an android app that demonstrates the use of anOptions Menu.............. 17
Practical – 6................................................................................................................ 21
Aim : Create an android app that demonstrate Screen Navigation............................ 21
Practical – 7................................................................................................................ 25
Aim: Create an android app to show Notifications.activity_main.xml....................... 25
Practical – 8................................................................................................................ 32
Aim: Create an android app to save user data in a database..................................... 32
Practical – 9................................................................................................................ 43
Aim: Simple Calculator app....................................................................................... 43
Practical – 10.............................................................................................................. 56
Aim: Create an android app to connect to the internet and useBroadcastReceiver... 56
Practical – 1
Aim: Create a Android App to Run Hello World Program.
Design:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
xmlns:app="http://schemas.android.com/apk/res-aut
o" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
MainActivity.java
package com.example.helloworld;
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);
}
}
Output :
Practical – 2
Aim: Create an android app that demonstrates working with TextView
Elements .
Design:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingStart="40dp"
android:orientation="vertical"
android:id="@+id/linearlayout"
tools:ignore="RtlSymmetry">
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="@string/name"
android:inputType="text"
android:selectAllOnFocus="true" />
<EditText
android:id="@+id/txtPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/password_0_to_9"
android:inputType="numberPassword" />
<EditText
android:id="@+id/txtEmai"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/txtDate
"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3
" android:ems="10"
android:hint="@string/date"
android:inputType="date"
tools:ignore="ObsoleteLayoutParam" />
<EditText
android:id="@+id/txtPhone
"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/phone_number"
android:inputType="phone"
android:textColorHint="#FE8DAB"/>
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/submit"
android:textSize="16sp"
android:textStyle="normal|bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginTop="25dp"
android:textSize="15sp"/>
</LinearLayout>
MainActivity.java
package com.example.edittextprogram;
import
android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
Button btnSubmit;
EditText name, password, email, dob, phoneno;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.txtName);
password = (EditText)findViewById(R.id.txtPwd);
email = (EditText)findViewById(R.id.txtEmai);
dob = (EditText)findViewById(R.id.txtDate);
phoneno= (EditText)findViewById(R.id.txtPhone);
btnSubmit =
(Button)findViewById(R.id.btnSend); result =
(TextView)findViewById(R.id.resultView);
btnSubmit.setOnClickListener(new View.OnClickListener()
{ @SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
if (name.getText().toString().isEmpty() ||
password.getText().toString().isEmpty() ||
email.getText().toString().isEmpty() ||
dob.getText().toString().isEmpty()
|| phoneno.getText().toString().isEmpty()) {
result.setText("Please Fill All the Details");
} else {
result.setText("Name - " + name.getText().toString() +
" \n" + "Password - " + password.getText().toString()
+ " \n" + "E-Mail - " + email.getText().toString()
+ " \n" + "DOB - " + dob.getText().toString()
+ " \n" + "Contact - " +
phoneno.getText().toString());
}
}
});
}
}
Output:
Practical - 3
Aim: Create an android app that demonstrates ActivityLifecycle.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://s
chemas.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="example.javatpoint.com.activitylifecycle.MainActivity
">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.java
package example.javatpoint.com.activitylifecycle;
import
android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart
invoked");
}
@Override
protected void onResume() {
super.onResume();
Log.d("lifecycle","onResume
invoked");
}
@Override
protected void onPause() {
super.onPause();
Log.d("lifecycle","onPause
invoked");
}
@Override
protected void onStop() {
super.onStop();
Log.d("lifecycle","onStop
invoked");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("lifecycle","onRestart
invoked");
}
@Override
protected void onDestroy()
{ super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
Output:
Practical – 4
Aim: Create an android app that demonstrates the use of Alert.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
xmlns:app="http://schemas.android.com/apk/res-aut
o" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="MainActivity">
<TextView
android:id="@+id/top_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/tap_test" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/top_message"
android:layout_marginTop="10dp"
android:text="@string/alert_button"
android:onClick="onClickShowAlert"
tools:ignore="OnClick" />
</RelativeLayout>
MainActivity.java
package com.example.helloworld;
import android.app.AlertDialog;
import android.content.DialogInterface;
import
android.support.v7.app.AlertDialog;
import
import
import
import
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClickShowAlert(View view) {
AlertDialog.Builder myAlertBuilder =
new
AlertDialog.Builder(MainActivity.this);
// Set the dialog title.
myAlertBuilder.setTitle(R.string.alert_title);
// Set the dialog message.
myAlertBuilder.setMessage(R.string.alert_message);
// Add the buttons.
myAlertBuilder.setPositiveButton(R.string.ok, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User clicked OK button.
Toast.makeText(getApplicationContext(),
R.string.pressed_ok,
Toast.LENGTH_SHORT).show();
}
});
myAlertBuilder.setNegativeButton(R.string.cancel, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// User cancelled the dialog.
Toast.makeText(getApplicationContext(),
R.string.pressed_cancel,
Toast.LENGTH_SHORT).show();
}
});
// Create and show the AlertDialog.
myAlertBuilder.show();
}
}
Output :
Practical – 5
Aim: Create an android app that demonstrates the use of anOptions
Menu.
Design:
Example_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:id="@+id/menu_bookmark"
android:title="@string/bookmark"
/>
<item android:id="@+id/menu_save"
android:title="@string/save"
/>
<item
android:id="@+id/menu_search"
android:title="@string/search"
/>
<item
android:id="@+id/menu_share"
android:title="@string/share"
/>
<item
android:id="@+id/menu_delete"
android:title="@string/delete"
/>
<item
android:id="@+id/menu_preferences"
android:title="@string/preferences"
/>
</menu>
MainActivity.java
package com.example.optionsmenu;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import
android.view.Menu;
import
android.view.Menu;
import
android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/* Initiating Menu XML file (menu.xml) */
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.example_menu, menu);
return true;
}
@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_bookmark:
Toast.makeText(this, "Bookmark is Selected",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_save:
Toast.makeText(this, "Save is Selected",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_search:
Toast.makeText(this, "Search is Selected",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_share:
Toast.makeText(this, "Share is Selected",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_delete: Toast.makeText(this,
"Delete is Selected",
Toast.LENGTH_SHORT).show();
return true;
case R.id.menu_preferences:
Toast.makeText(this, "Preferences is Selected",
Toast.LENGTH_SHORT).show();
return
true; default:
return super.onOptionsItemSelected(item); }}}
Output:
Practical – 6
Aim : Create an android app that demonstrate Screen Navigation.
activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--the root view must be the DrawerLayout-->
<androidx.drawerlayout.widget.DrawerLayout
tools:ignore="HardcodedText" tools:context=".MainActivity"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/my_drawer_layout"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
><Line arLayout android:layout_height="match_parent"
android:layout_width="match_parent"><TextView
android:layout_height="wrap_content"
android:layout_width="match_parent" android:textSize="18sp"
android:text="Screen Navigation" android:gravity="center"
android:layout_marginTop="128dp"/></LinearLayout>
<!--this the navigation view which draws and shows the
navigation drawer-->
<!--include the menu created in the menu folder-->
<com.google.android.material.navigation.NavigationView
android:layout_height="match_parent"
android:layout_width="wrap_content"
app:menu="@menu/navigation_menu"
android:layout_gravity="start"/></androidx.drawerlayout.widge
t.Dra werLayout>
Navigation_menu.xml
<?xml version="1.0" encoding="UTF-8"?>
-<menu tools:ignore="HardcodedText"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item android:title="My Account"
android:id="@+id/nav_account"
/>
<item android:title="Settings"
android:id="@+id/nav_settings"/>
<item android:title="Logout"
android:id="@+id/nav_logout"/
>
</menu>
main_activity.java
package com.example.screennavigation;
import androidx.annotation.NonNull;
import
androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import android.os.Bundle;
import android.view.MenuItem;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// drawer layout instance to toggle the menu icon to open
// drawer and back button to close drawer
drawerLayout =
findViewById(R.id.my_drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,
drawerLayout, R.string.nav_open, R.string.nav_close);
// pass the Open and Close toggle for the drawer layout listener
// to toggle the button
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// to make the Navigation drawer icon always appear on
the action bar
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpE
nabled(true);
}
// override the onOptionsItemSelected()
// function to implement
// the item click listener callback
// to open and close the navigation
// drawer when the icon is
clicked @Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true; }
return super.onOptionsItemSelected(item);
}}
Output :
Practical – 7
Aim: Create an android app to show Notifications.
activity_main.xml
<?xml version="1.0" encoding="utf8"?> <android.support.constraint.ConstraintLayout xmlns:android="h
ttp://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="example.javatpoint.com.androidnotification.Main
Activit y">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ANDROID
NOTIFICATION"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.091"
android:textAppearance="@style/Base.TextAppearance.AppCom
pat.M edium"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_marginBottom="112dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:text="Notify"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
activity_notification_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://s
chemas.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="example.javatpoint.com.androidnotification.Notificati
onView">
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent
"
android:layout_height="wrap_content"
android:gravity="center"
android:text="your detail of
notification..."
android:textAppearance="@style/Base.TextAppearance.Ap
pCom pat.Medium" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.096"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView2"
app:layout_constraintVertical_bias="0.206"
android:textAppearance="@style/Base.TextAppearance.AppCom
pat.Medium"/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
package example.javatpoint.com.androidnotification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import
android.support.v4.app.NotificationCompat;
import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import
android.view.View;
import
android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{ addNotification();
}
});
}
private void addNotification() {
NotificationCompat.Builder builder
=
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.messageicon) //set icon for
notification
notification
.setContentTitle("Notifications
Example") //set title of
.setContentText("This is a
notification message")//this
is notification message
.setAutoCancel(true) // makes auto cancel of notificati
on
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//set priority of notification
Intent notificationIntent = new Intent(this, NotificationView.class
);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//notification message will get at NotificationView
notificationIntent.putExtra("message", "This is a notification mes
sage");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystem
Service(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
}
NotificationView.java
package
example.javatpoint.com.androidnotification; import
android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class NotificationView extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_view);
textView = findViewById(R.id.textView);
//getting the notification message
String message=getIntent().getStringExtra("message");
textView.setText(message);
}
}
Output:
Practical – 8
Aim: Create an android app to save user data in a database.
Design:
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android
" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--Edit text to enter course name-->
<EditText
android:id="@+id/idEdtCourseName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter course Name" />
<!--edit text to enter course duration-->
<EditText
android:id="@+id/idEdtCourseDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Duration" />
<!--edit text to display course tracks-->
<EditText
android:id="@+id/idEdtCourseTracks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Tracks" />
<!--edit text for course description-->
<EditText
android:id="@+id/idEdtCourseDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Course Description" />
<!--button for adding new course-->
<Button
android:id="@+id/idBtnAddCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Add Course"
android:textAllCaps="false" />
</LinearLayout>
DBHandler.java
import
android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHandler extends SQLiteOpenHelper {
// creating a constant variables for our database.
// below variable is for our database name.
private static final String DB_NAME =
"coursedb";
// below int is our database version
private static final int DB_VERSION =
1;
// below variable is for our table name.
private static final String TABLE_NAME = "mycourses";
// below variable is for our id column.
private static final String ID_COL =
"id";
// below variable is for our course name column
private static final String NAME_COL = "name";
// below variable id for our course duration column.
private static final String DURATION_COL =
"duration";
// below variable for our course description column.
private static final String DESCRIPTION_COL = "description";
// below variable is for our course tracks column.
private static final String TRACKS_COL =
"tracks";
// creating a constructor for our database
handler. public DBHandler(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
// below method is for creating a database by running a sqlite
query
@Override
public void onCreate(SQLiteDatabase db) {
// on below line we are creating
// an sqlite query and we are
// setting our column names
// along with their data types.
String query = "CREATE TABLE " + TABLE_NAME + " ("
AUTOINCREMENT, "
+ ID_COL + " INTEGER PRIMARY KEY
+ NAME_COL + " TEXT,"
+ DURATION_COL + " TEXT,"
+ DESCRIPTION_COL + " TEXT,"
+ TRACKS_COL + " TEXT)";
// at last we are calling a exec sql
// method to execute above sql
query db.execSQL(query);
}
// this method is use to add new course to our sqlite database.
public void addNewCourse(String courseName, String
courseDuration, String courseDescription, String courseTracks) {
// on below line we are creating a variable for
// our sqlite database and calling writable method
// as we are writing data in our database.
SQLiteDatabase db =
this.getWritableDatabase();
// on below line we are creating a
// variable for content values.
ContentValues values = new ContentValues();
// on below line we are passing all values
// along with its key and value pair.
values.put(NAME_COL, courseName);
values.put(DURATION_COL, courseDuration);
values.put(DESCRIPTION_COL,
courseDescription); values.put(TRACKS_COL,
courseTracks);
// after adding all values we are passing
// content values to our table.
db.insert(TABLE_NAME, null, values);
// at last we are closing our
// database after adding
database. db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// this method is called to check if the table exists already.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
MainActivity.java
import android.os.Bundle;
import
android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
// creating variables for our edittext, button and dbhandler
private EditText courseNameEdt, courseTracksEdt,
courseDurationEdt,
courseDescriptionEdt; private
Button addCourseBtn; private
DBHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing all our variables.
courseNameEdt = findViewById(R.id.idEdtCourseName);
courseTracksEdt = findViewById(R.id.idEdtCourseTracks);
courseDurationEdt =
findViewById(R.id.idEdtCourseDuration);
courseDescriptionEdt =
findViewById(R.id.idEdtCourseDescription);
addCourseBtn = findViewById(R.id.idBtnAddCourse);
// creating a new dbhandler class
// and passing our context to it.
dbHandler = new DBHandler(MainActivity.this);
// below line is to add on click listener
for our add course
button.
addCourseBtn.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
fields.
// below line is to get data
from all edit text
String courseName =
courseNameEdt.getText().toString();
String courseTracks =
courseTracksEdt.getText().toString();
String courseDuration
= courseDurationEdt.getText().toString();
String courseDescription =
courseDescriptionEdt.getText().toString();
// validating if the text fields are empty or
not. if (courseName.isEmpty() &&
courseTracks.isEmpty() && courseDuration.isEmpty() &&
courseDescription.isEmpty()) {
Toast.makeText(MainActivity.this, "Please
enter all the data..", Toast.LENGTH_SHORT).show();
return;
}
new it.
// on below line we are calling
a method to add
// course to sqlite data and
pass all our values to
dbHandler.addNewCourse(cou
rseName,
courseDuration, courseDescription, courseTracks);
message.
// after adding the data we are
displaying a toast
, "Course has
Toast.makeText(MainActivity.this
been added.", Toast.LENGTH_SHORT).show();
courseNameEdt.setText("");
courseDurationEdt.setText("");
courseTracksEdt.setText("");
courseDescriptionEdt.setText("");
}
});
}
}
Output:
Practical – 9
Aim: Simple Calculator app
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/andr
oid"
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:background="#8BC34A"
android:backgroundTint="@android:color/darker_gray"
tools:context=".MainActivity">
<!-- Text View to display our basic heading of "calculator"-->
<TextView
android:layout_width="194dp"
android:layout_height="43dp"
android:layout_marginStart="114dp"
android:layout_marginLeft="114dp"
android:layout_marginTop="58dp"
android:layout_marginEnd="103dp"
android:layout_marginRight="103dp"
android:layout_marginBottom="502dp"
android:scrollbarSize="30dp"
android:text=" Calculator"
dy1"
android:textAppearance="@style/TextAp
pearance.AppCompat.Bo
android:textSize="30dp"
app:layout_constraintBottom_toBot
tomOf="parent"
app:layout_constraintEnd_toEndOf
="parent"
app:layout_constraintStart_toStart
Of="parent"
app:layout_constraintTop_toTopOf=
"parent" />
<!-- Edit Text View to input the values
-->
<EditText
android:id="@
+id/num1"
android:layout
_width="364d
p"
android:layout
_height="28d
p"
android:layout
_marginStart=
"72dp"
android:layout
_marginTop="
70dp"
android:layout
_marginEnd="
71dp"
android:layout
_marginBotto
m="416dp"
android:backg
round="@andr
oid:color/whit
e"
android:ems=
"10"
android:hint="
Number1(0)"
android:inputT
ype="number"
app:layout_constraintBottom_toBot
tomOf="parent"
app:layout_constraintEnd_toEndOf
="parent"
app:layout_constraintStart_toStart
Of="parent"
app:layout_constraintTop_toTopOf=
"parent" />
<!-- Edit Text View to input 2nd value-->
<EditText
android:id="@+id/num2"
android:layout_width="363dp"
android:layout_height="30dp"
android:layout_marginStart="72dp"
android:layout_marginTop="112dp"
android:layout_marginEnd="71dp"
android:layout_marginBottom="374dp"
android:background="@android:color/white
" android:ems="10"
android:hint="number2(0)"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Text View to display result -->
<TextView
android:id="@+id/result"
android:layout_width="356dp"
android:layout_height="71dp"
android:layout_marginStart="41dp"
android:layout_marginTop="151dp"
android:layout_marginEnd="48dp"
android:layout_marginBottom="287dp"
android:background="@android:color/white"
android:text="result"
android:textColorLink="#673AB7"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform 'sum' operation -->
<Button
android:id="@+id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_li
ght" android:onClick="doSum"
android:text="+"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform subtraction operation. -->
<Button
android:id="@+id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="210dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="113dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doSub"
android:text="-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform division. -->
<Button
android:id="@+id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="307dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_li
ght" android:onClick="doDiv"
android:text="/"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform multiplication. -->
<Button
android:id="@+id/mul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="356dp"
android:layout_marginEnd="307dp"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_li
ght" android:onClick="doMul"
android:text="x"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform a modulus function. -->
<Button
android:id="@+id/button"
android:layout_width="92dp"
android:layout_height="48dp"
android:layout_marginStart="113d
p"
android:layout_marginTop="356dp"
android:layout_marginEnd="206dp
"
android:layout_marginBottom="199dp"
android:backgroundTint="@android:color/holo_red_light"
android:onClick="doMod"
android:text="%(mod)"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- A button to perform a power function. -->
<Button
android:id="@+id/pow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="113dp"
android:layout_marginTop="292dp"
android:layout_marginEnd="210dp"
android:layout_marginBottom="263dp"
android:backgroundTint="@android:color/holo_red_li
ght" android:onClick="doPow"
android:text="n1^n2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
import android.os.Bundle;
import
android.view.View;
import android.widget.EditText;
import
android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText e1, e2;
TextView t1;
int num1, num2;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// a public method to get the input
numbers public boolean getNumbers() {
// defining the edit text 1 to e1
e1 = (EditText) findViewById(R.id.num1);
// defining the edit text 2 to e2
e2 = (EditText) findViewById(R.id.num2);
// defining the text view to t1
t1 = (TextView) findViewById(R.id.result);
// taking input from text box 1
String s1 = e1.getText().toString();
// taking input from text box 2
String s2 = e2.getText().toString();
// condition to check if box is not
empty if ((s1.equals(null) &&
s2.equals(null))
|| (s1.equals("") && s2.equals(""))) {
String result = "Please enter a value";
t1.setText(result);
return false;
} else {
// converting string to int.
num1 = Integer.parseInt(s1);
// converting string to int.
num2 = Integer.parseInt(s2);
}
return true;
}
// a public method to perform addition
public void doSum(View v) {
// get the input
numbers if
(getNumbers()) {
int sum = num1 + num2;
t1.setText(Integer.toString(sum));
}
}
// a public method to perform power
function public void doPow(View v) {
// get the input
numbers if
(getNumbers()) {
double sum = Math.pow(num1,
num2);
t1.setText(Double.toString(sum));
}
}
// a public method to perform subtraction
public void doSub(View v) {
// get the input
numbers if
(getNumbers()) {
int sum = num1 - num2;
t1.setText(Integer.toString(sum));
}
}
// a public method to perform
multiplication public void doMul(View v) {
// get the input
numbers if
(getNumbers()) {
int sum = num1 * num2;
t1.setText(Integer.toString(sum));
}
}
// a public method to perform
Division public void doDiv(View v) {
// get the input
numbers if
(getNumbers()) {
// displaying the text in text view assigned as t1
double sum = num1 / (num2 *
1.0);
t1.setText(Double.toString(sum));
}
}
// a public method to perform modulus
function public void doMod(View v) {
// get the input
numbers if
(getNumbers()) {
double sum = num1 % num2;
t1.setText(Double.toString(sum));
}
}
}
Output:
Practical – 10
Aim: Create an android app to connect to the internet and use
BroadcastReceiver.
customDialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/an
droid"
android:orientation="vertical"
android:layout_width="match_parent"
android:background="#024BFF"
android:gravity="center"
android:layout_height="match_parent">
<ImageView
android:layout_width="120dp"
android:layout_height="120dp"
android:src="@drawable/no_internet"
android:layout_gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ooops!"
android:gravity="center"
android:textColor="#FFF"
android:textSize="40sp"/>
<TextView
android:id="@+id/nettext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="No Internet Connection
found" android:textColor="#FFF"
android:textSize="15sp"
android:layout_marginBottom="10dp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ON YOUR DATA AND HIT RESTART"
android:textColor="#FFF"
android:textSize="15sp"
android:layout_marginBottom="10dp"
android:gravity="center"/>
<Button
android:id="@+id/restartapp"
android:layout_width="300dp"
android:layout_height="50dp"
android:text="Restart"
android:textSize="20sp"
android:background="@android:color/holo_green_light"/>
</LinearLayout>
NetworkUtil.java
package com.example.app2;
import
android.content.Context;
import android.net.ConnectivityManager;
import
android.net.NetworkInfo; class
NetworkUtil {
public static String getConnectivityStatusString(Context context) {
String status = null;
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
if (activeNetwork.getType() ==
ConnectivityManager.TYPE_WIFI) {
status = "Wifi
enabled"; return
status;
} else if (activeNetwork.getType() ==
ConnectivityManager.TYPE_MOBILE) {
status = "Mobile data
enabled"; return status;
}
} else {
status = "No internet is
available"; return status;
}
return status;
}
}
MyReceiver.java
import
android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import
android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver
{ Dialog dialog;
TextView nettext;
@Override
public void onReceive(final Context context, final Intent intent) {
String status =
NetworkUtil.getConnectivityStatusString(conte
xt); dialog = new
Dialog(context,android.R.style.Theme_NoTitleBar_Fullscr
een);
dialog.setContentView(R.layout.customdialog);
Button restartapp =
(Button)dialog.findViewById(R.id.restartapp);
nettext =(TextView)dialog.findViewById(R.id.nettext);
restartapp.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v) {
((Activity)
context).finish();
Log.d("clickedbutton","yes"
);
Intent i = new Intent(context, MainActivity.class);
context.startActivity(i);
}
});
Log.d("network",status);
if(status.isEmpty()||status.equals("No internet is
available")||status.equals("No Internet Connection")) {
status="No Internet Connection";
dialog.show();
}
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
MainActivity.java
import
android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity{
private BroadcastReceiver MyReceiver = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyReceiver = new MyReceiver();
broadcastIntent();
}
public void broadcastIntent() {
registerReceiver(MyReceiver, new
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(MyReceiver);
}
}
Output:
Download