You are on page 1of 21

D20MCA11140

Ques. 1: Create an android application that can tell whether the entered string is an Armstrong
number or not. Also add a clear all functionality which will be clearing all the components
including inputs and outputs.
Ans. 1:
Program:
Step 1: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is
the code for the activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

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:background="@color/teal_200">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Armstrong Number or Not"

android:textColor="@color/black"

android:textSize="26sp"

app:layout_constraintBottom_toTopOf="@+id/textView"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent"

app:layout_constraintVertical_bias="0.491" />

1
D20MCA11140

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter a number to check Armstrong Number"
android:textColor="@color/black"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.494"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.4" />

<EditText
android:id="@+id/etNum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="ENTER THE NUMBER"
android:inputType="number"
app:layout_constraintEnd_toEndOf="@+id/textView"
app:layout_constraintStart_toStartOf="@+id/textView"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<Button
android:id="@+id/btnCheck"
android:layout_width="149dp"
android:layout_height="50dp"
android:layout_margin="10dp"
android:layout_marginTop="16dp"
android:backgroundTint="@color/black"
android:text="Check"
android:textColor="@color/teal_700"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/etNum"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="@+id/etNum"
app:layout_constraintTop_toBottomOf="@+id/etNum"
app:layout_constraintVertical_bias="0.113" />

</androidx.constraintlayout.widget.ConstraintLayout>

2
D20MCA11140

Step 2: Working with the MainActivity.kt file


Go to the MainActivity.kt file and refer to the following code. Below is the code for
the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Here we will bind the views and write the logic of the app.

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.Button

import android.widget.EditText

import android.widget.Toast

import java.lang.Math.pow

import kotlin.math.pow

class MainActivity : AppCompatActivity() {

lateinit var btnCheck : Button

lateinit var etNum : EditText

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

supportActionBar?.hide()

// Binding the views

btnCheck = findViewById(R.id.btnCheck)

etNum = findViewById(R.id.etNum)

btnCheck.setOnClickListener {

val n = etNum.text.toString().length

val num = etNum.text.toString().toInt()

var temp = num

var result = 0

while (temp != 0){

val remainder = temp % 10

3
D20MCA11140

val remainder = temp % 10

result +=
(remainder.toDouble().pow(n.toDouble())).toInt()

temp /= 10

if (result == num)

Toast.makeText(this,"Armstrong
Number",Toast.LENGTH_SHORT).show()

else

Toast.makeText(this,"Not an Armstrong
Number",Toast.LENGTH_SHORT).show()

Output:

4
D20MCA11140

Ques. 2: Build an Android application behaves that like student information system and able to
register a student by input Roll No, Name, Sex, and Mobile no from user and store it into an object.
Ans. 2:
Program:

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

<androidx.constraintlayout.widget.ConstraintLayout

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:background="@color/teal_200">

<EditText

android:id="@+id/txtItem"

android:layout_width="240dp"

android:layout_height="wrap_content"

android:hint="@string/hintTxtItem"

android:inputType="sno" />

<EditText

android:id="@+id/txtItem1"

android:layout_width="240dp"

android:layout_height="wrap_content"

android:hint="@string/hintTxtItem1"

android:inputType="Name" />

5
D20MCA11140

<EditText
android:id="@+id/txtItem2"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:hint="@string/hintTxtItem2"
android:inputType="Mobileno " />

<Button
android:id="@+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap-content"
android:text="@string/lblBtnAdd"
app:layout_toRightOf="@+id/txtItem" />
<Button
android:id="@+id/btnAdd1"
android:layout_width="fill_parent"
android:layout_height="wrap-content"
android:text="@string/lblBtnAdd"
app:layout_toRightOf="@+id/txtItem" />
<Button
android:id="@+id/btnAdd2"
android:layout_width="fill_parent"
android:layout_height="wrap-content"
android:text="@string/lblBtnAdd"
app:layout_toRightOf="@+id/txtItem" />

</androidx.constraintlayout.widget.ConstraintLayout>

6
D20MCA11140
import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.Button

import android.widget.EditText

import android.widget.Toast

import java.lang.Math.pow

import kotlin.math.pow

class MainActivity : AppCompatActivity() {

lateinit var btnCheck : Button

lateinit var etNum : EditText

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

supportActionBar?.hide()

// Binding the views

btnCheck = findViewById(R.id.btnCheck)

etNum = findViewById(R.id.etNum)

btnCheck.setOnClickListener {

val n = etNum.text.toString().length

val num = etNum.text.toString().toInt()

var temp = num

var result = 0

while (temp != 0){

7
D20MCA11140
val remainder = temp % 10

result +=
(remainder.toDouble().pow(n.toDouble())).toInt()

temp /= 10

if (result == num)

Toast.makeText(this,"Armstrong
Number",Toast.LENGTH_SHORT).show()

else

Toast.makeText(this,"Not an Armstrong
Number",Toast.LENGTH_SHORT).show()

8
D20MCA11140

Ques. 3: Create an android application that will use Alert dialog box for taking confirmation from
users for action to move to Login or Register activity.

Ans. 3:
<?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:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Press The Back Button of Your Phone."

android:textStyle="bold"

android:textSize="30dp"

android:gravity="center_horizontal"

android:layout_marginTop="180dp"

/>

</RelativeLayout>

9
D20MCA11140

package org.geeksforgeeks.navedmalik.alertdialog;

import android.content.DialogInterface;

import android.support.v7.app.AlertDialog;

import android.support.v7.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);

// Declare the onBackPressed method

// when the back button is pressed

// this method will call

@Override

public void onBackPressed()

// Create the object of

// AlertDialog Builder class

AlertDialog.Builder builder

= new AlertDialog

.Builder(MainActivity.this);

10
D20MCA11140

// Set the message show for the Alert time

builder.setMessage("Do you want to exit ?");

// Set Alert Title

builder.setTitle("Alert !");

// Set Cancelable false

// for when the user clicks on the outside

// the Dialog Box then it will remain show

builder.setCancelable(false);

// Set the positive button with yes name

// OnClickListener method is use of

// DialogInterface interface.

builder

.setPositiveButton(

"Yes",

new DialogInterface

.OnClickListener() {

@Override

public void onClick(DialogInterface dialog,

int which)

// When the user click yes button

// then app will close

finish();

11
D20MCA11140

});

// Set the Negative button with No name

// OnClickListener method is use

// of DialogInterface interface.

builder

.setNegativeButton(

"No",

new DialogInterface

.OnClickListener() {

@Override

public void onClick(DialogInterface dialog,

int which)

// If user click no

// then dialog box is canceled.

dialog.cancel();

});

// Create the Alert dialog

AlertDialog alertDialog = builder.create();

// Show the Alert Dialog box

alertDialog.show();

12
D20MCA11140

Ques. 4: Build a menu based application that will provide options to switch color of theme.

Ans. 4:
Open themes.xml (night). In the Project pane select Android, go to app > res > values > themes >
themes.xml (night).

Change colorPrimary to the light variant of the primary color you selected, @color/green_light.

Change colorPrimaryVariant to @color/green.

Change colorSecondary to @color/blue_light.

Change colorSecondaryVariant to @color/blue_light. Note that colorSecondaryVariant could be the same


color as colorSecondary.

When you're done, your themes.xml (night) file should look like this:

<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Application theme for dark theme. -->
<style name="Theme.TipTime"
parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/green_light</item>
<item name="colorPrimaryVariant">@color/green</item>
<item name="colorOnPrimary">@color/black</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">@color/blue_light</item>
<item name="colorSecondaryVariant">@color/blue_light</item>
<item name="colorOnSecondary">@color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor"
tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>

At this point, the original colors defined in colors.xml, for example, purple_200, aren't used anymore so
you can delete them.

13
D20MCA11140

14
D20MCA11140

Ques. 6: Create an activity that allow you to move forward and backward through all tabs.
Ans. 6:

1. Create a base Fragment Class

public class BaseFragment extends Fragment {


AppMainTabActivity mActivity;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivity = (AppMainTabActivity) this.getActivity();
}

public void onBackPressed(){


}

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


}
}

2. Create some Tab identifiers, accessible everywhere in project

public class AppConstants{


public static final String TAB_A = "tab_a_identifier";
public static final String TAB_B = "tab_b_identifier";

//Your other constants, if you have them..


}

3. Ok, Main Tab Activity- Please go through comments in code..

15
D20MCA11140
public class AppMainFragmentActivity extends FragmentActivity{
/* Your Tab host */
private TabHost mTabHost;

/* A HashMap of stacks, where we use tab identifier as keys..*/


private HashMap<String, Stack<Fragment>> mStacks;

/*Save current tabs identifier in this..*/


private String mCurrentTab;

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.app_main_tab_fragment_layout);

/*
* Navigation stacks for each tab gets created..
* tab identifier is used as key to get respective stack for each tab
*/
mStacks = new HashMap<String, Stack<Fragment>>();
mStacks.put(AppConstants.TAB_A, new Stack<Fragment>());
mStacks.put(AppConstants.TAB_B, new Stack<Fragment>());

mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setOnTabChangedListener(listener);
mTabHost.setup();

initializeTabs();
}
private View createTabView(final int id) {
View view = LayoutInflater.from(this).inflate(R.layout.tabs_icon, null);
ImageView imageView = (ImageView) view.findViewById(R.id.tab_icon);
imageView.setImageDrawable(getResources().getDrawable(id));
return view;
}

public void initializeTabs(){


/* Setup your tab icons and content views.. Nothing special in this..*/
TabHost.TabSpec spec = mTabHost.newTabSpec(AppConstants.TAB_A);
mTabHost.setCurrentTab(-3);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.tab_home_state_btn));
mTabHost.addTab(spec);

spec = mTabHost.newTabSpec(AppConstants.TAB_B);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.tab_status_state_btn));
mTabHost.addTab(spec);
}

16
D20MCA11140

/*Comes here when user switch tab, or we do programmatically*/


TabHost.OnTabChangeListener listener = new
TabHost.OnTabChangeListener() {
public void onTabChanged(String tabId) {
/*Set current tab..*/
mCurrentTab = tabId;

if(mStacks.get(tabId).size() == 0){
/*
* First time this tab is selected. So add first fragment of that tab.
* Dont need animation, so that argument is false.
* We are adding a new fragment which is not present in stack. So add to stack is true.
*/
if(tabId.equals(AppConstants.TAB_A)){
pushFragments(tabId, new AppTabAFirstFragment(), false,true);
}else if(tabId.equals(AppConstants.TAB_B)){
pushFragments(tabId, new AppTabBFirstFragment(), false,true);
}
}else {
/*
* We are switching tabs, and target tab is already has atleast one fragment.
* No need of animation, no need of stack pushing. Just show the target fragment
*/
pushFragments(tabId, mStacks.get(tabId).lastElement(), false,false);
}
}
};
/* Might be useful if we want to switch tab programmatically, from inside any of the fragment.*/
public void setCurrentTab(int val){
mTabHost.setCurrentTab(val);
}

/*
* To add fragment to a tab.
* tag -> Tab identifier
* fragment -> Fragment to show, in tab identified by tag
* shouldAnimate -> should animate transaction. false when we switch tabs, or adding first fragment to a tab
* true when when we are pushing more fragment into navigation stack.
* shouldAdd -> Should add to fragment navigation stack (mStacks.get(tag)). false when we are switching
tabs (except for the first time)
* true in all other cases.
*/
public void pushFragments(String tag, Fragment fragment,boolean
shouldAnimate, boolean shouldAdd){
if(shouldAdd)
mStacks.get(tag).push(fragment);
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if(shouldAnimate)
ft.setCustomAnimations(R.anim.slide_in_right,
R.anim.slide_out_left);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();
}

17
D20MCA11140

public void popFragments(){


/*
* Select the second last fragment in current tab's stack..
* which will be shown after the fragment transaction given below
*/
Fragment fragment = mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() - 2);

/*pop current fragment from stack.. */


mStacks.get(mCurrentTab).pop();

/* We have the target fragment in hand.. Just show it.. Show a standard navigation animation*/
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();
}
@Override
public void onBackPressed() {
if(mStacks.get(mCurrentTab).size() == 1){
// We are already showing first fragment of current tab, so when back pressed, we will finish this activity..
finish();
return;
}

/* Each fragment represent a screen in application (at least in my requirement, just like an activity used to
represent a screen). So if I want to do any particular action
* when back button is pressed, I can do that inside the fragment itself. For this I used AppBaseFragment, so
that each fragment can override onBackPressed() or onActivityResult()
* kind of events, and activity can pass it to them. Make sure just do your non navigation (popping) logic in
fragment, since popping of fragment is done here itself.
*/
((AppBaseFragment)mStacks.get(mCurrentTab).lastElement()).onBackPressed();

/* Goto previous fragment in navigation stack of this tab */


popFragments();
}

/*
* Imagine if you wanted to get an image selected using ImagePicker intent to the fragment. Ofcourse I could
have created a public function
* in that fragment, and called it from the activity. But couldn't resist myself.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(mStacks.get(mCurrentTab).size() == 0){
return;
}

/*Now current fragment on screen gets onActivityResult callback..*/


mStacks.get(mCurrentTab).lastElement().onActivityResult(requestCode, resultCode, data);
}
}

18
D20MCA11140

4. AppTabAFirstFragment.java (First fragment in Tab A, simliar for all Tabs)

public class AppTabAFragment extends BaseFragment {


private Button mGotoButton;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_layout, container, false);

mGoToButton = (Button) view.findViewById(R.id.goto_button);


mGoToButton.setOnClickListener(listener);

return view;
}

private OnClickListener listener = new View.OnClickListener(){


@Override
public void onClick(View v){
/* Go to next fragment in navigation stack*/
mActivity.pushFragments(AppConstants.TAB_A, new AppTabAFragment2(),true,true);
}
}
}

19
D20MCA11140

Ques. 7: Create a media player application in android which will be able to play, pause and stop
audio file.
Ans. 7:

<?xml
version="1.0"
encoding="utf-
8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.aasemjs.audioplayer.MainActivity">

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

<Button
android:text="Play"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnPlay"
android:onClick="playSong" />

<Button
android:text="Pause"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnPause"
android:onClick="pauseSong" />

<Button
android:text="Stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnStop"

20
D20MCA11140

package
com.aasemjs.audioplayer;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

MediaPlayer mp;

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

mp=MediaPlayer.create(this, R.raw.abc);
}

public void playSong(View v){


mp.start();
}

public void pauseSong(View v) {

Output:

21

You might also like