Mobile Application File

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 59

MOBILE APPLICATION DEVELOPMENT LAB

PRACTICAL FILE

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING
PUNJABI UNIVERSITY
PATIALA-147001

Submitted By: Sahil Bansal Submitted To: Jaspreet Sir


Roll No. 12005055 Class- ECM 3rd Year
Content
1. Develop an Android application using various components, fonts and
colors.
2. Develop an Android application that uses Layout Managers and event
listeners.
3. Develop an Android application for basic calculator.
4. Develop an Android application to write data to the SD card.
5. Develop an Android application that uses Fragments.
6. Develop an Android application that uses Navigation component.
7. Develop an Android application that uses GPS location information.
8. Develop an Android application using various Firebase services.
EXPERIMENT-1
Aim: To develop a Simple Android Application that uses GUI components, Font and
Colours.

Procedure:
Creating a New project:
 Open Android Studio and then click on File -> New -> New project.

 Then type the Application name as “ex.no.1″ and click Next. 

 Then select the Minimum SDK as shown below and click Next.

 Then select the Empty Activity and click Next. 


 Finally click Finish.

 It will take some time to build and load the project.


 After completion it will look as given below.

Designing layout for the Android Application:


 Click on app -> res -> layout -> activity_main.xml.

 Now click on Text as shown below.


 Then delete the code which is there and type the code as given below.
Code for Activity_main.xml:
?
<?xml version="1.0" encoding="utf-8"?>
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
2     android:orientation="vertical"
3     android:layout_width="match_parent"
4     android:layout_height="match_parent">
5  
6     <TextView
        android:id="@+id/textView"
7         android:layout_width="match_parent"
8         android:layout_height="wrap_content"
9         android:layout_margin="30dp"
10         android:gravity="center"
        android:text="Hello World!"
11         android:textSize="25sp"
12         android:textStyle="bold" />
13  
14     <Button
15         android:id="@+id/button1"
16         android:layout_width="match_parent"
        android:layout_height="wrap_content"
17         android:layout_margin="20dp"
18         android:gravity="center"
19         android:text="Change font size"
20         android:textSize="25sp" />
    <Button
21
        android:id="@+id/button2"
22         android:layout_width="match_parent"
23         android:layout_height="wrap_content"
24         android:layout_margin="20dp"
25         android:gravity="center"
        android:text="Change color"
26         android:textSize="25sp" />
27 </LinearLayout>
Now click on Design and your application will look as given below.

 So now the designing part is completed.


Java Coding for the Android Application:
 Click on app -> java -> com.example.exno1 -> MainActivity.

 Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
?
1 package com.example.exno1;
2  
import android.graphics.Color;
3 import android.support.v7.app.AppCompatActivity;
4 import android.os.Bundle;
5 import android.view.View;
6 import android.widget.Button;
7 import android.widget.TextView;
8  
public class MainActivity extends AppCompatActivity
9 {
10     int ch=1;
11     float font=30;
12     @Override
13     protected void onCreate(Bundle savedInstanceState)
    {
14         super.onCreate(savedInstanceState);
15         setContentView(R.layout.activity_main);
16         final TextView t= (TextView) findViewById(R.id.textView);
17         Button b1= (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {
18             @Override
19             public void onClick(View v) {
20                 t.setTextSize(font);
21                 font = font + 5;
22                 if (font == 50)
                    font = 30;
23             }
24         });
25         Button b2= (Button) findViewById(R.id.button2);
26         b2.setOnClickListener(new View.OnClickListener() {
27             @Override
            public void onClick(View v) {
28                 switch (ch) {
29                     case 1:
30                         t.setTextColor(Color.RED);
31                         break;
                    case 2:
32                         t.setTextColor(Color.GREEN);
33                         break;
34                     case 3:
35                         t.setTextColor(Color.BLUE);
36                         break;
                    case 4:
37                         t.setTextColor(Color.CYAN);
38                         break;
39
                    case 5:
40                         t.setTextColor(Color.YELLOW);
41                         break;
42                     case 6:
43                         t.setTextColor(Color.MAGENTA);
44                         break;
                }
45                 ch++;
46                 if (ch == 7)
47                     ch = 1;
48             }
        });
49     }
50 }

 So now the Coding part is also completed.


 Now run the application to see the output.
Output:

Result:
              Thus a Simple Android Application that uses GUI components, Font and
Colours is developed and executed successfully.

EXPERIMENT-2
Aim:
        To develop a Simple Android Application that uses Layout Managers and Event
Listeners.
Procedure:
Creating a New project:
 Open Android Studio and then click on File -> New -> New project.

 Then type the Application name as “ex.no.2″ and click Next. 

 Then select the Minimum SDK as shown below and click Next.

 Then select the Empty Activity and click Next. 

 Finally click Finish.


 It will take some time to build and load the project.
 After completion it will look as given below.

Creating Second Activity for the Android Application:


 Click on File -> New -> Activity -> Empty Activity.

 Type the Activity Name as SecondActivity and click Finish button.


 Thus Second Activity For the application is created.
Designing Layout for Main Activity:
 Click on app -> res -> layout -> activity_main.xml.

 Now click on Text as shown below.

 Then delete the code which is there and type the code as given below.
Code for Activity_main.xml:
?
1 <?xml version="1.0" encoding="utf-8"?>

2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
3
    android:layout_width="match_parent"
4
    android:layout_height="match_parent"
5
    tools:context=".MainActivity"> 
6
    <LinearLayout
7
        android:layout_width="match_parent"
8         android:layout_height="100dp">
9         <TextView
10             android:id="@+id/textView"

11             android:layout_width="match_parent"

12             android:layout_height="wrap_content"

            android:layout_margin="30dp"
13
            android:text="Details Form"
14
15             android:textSize="25sp"

16             android:gravity="center"/>

17     </LinearLayout> 

    <GridLayout
18
        android:id="@+id/gridLayout"
19
        android:layout_width="match_parent"
20
        android:layout_height="match_parent"
21
        android:layout_marginTop="100dp"
22         android:layout_marginBottom="200dp"
23         android:columnCount="2"

24         android:rowCount="3">

25         <TextView

26             android:id="@+id/textView1"

            android:layout_width="wrap_content"
27
            android:layout_height="wrap_content"
28
            android:layout_margin="10dp"
29
            android:layout_row="0"
30
            android:layout_column="0"
31             android:text="Name"
32             android:textSize="20sp"

33             android:gravity="center"/> 

34         <EditText

35             android:id="@+id/editText"

36             android:layout_width="wrap_content"

            android:layout_height="wrap_content"
37
            android:layout_margin="10dp"
38
            android:layout_row="0"
39
            android:layout_column="1"
40
            android:ems="10"/> 
41
        <TextView
42             android:id="@+id/textView2"
43             android:layout_width="wrap_content"
44             android:layout_height="wrap_content"

45             android:layout_margin="10dp"

46             android:layout_row="1"

            android:layout_column="0"
47
            android:text="Reg.No"
48
49             android:textSize="20sp"

50             android:gravity="center"/> 

51         <EditText

            android:id="@+id/editText2"
52
            android:layout_width="wrap_content"
53
            android:layout_height="wrap_content"
54
            android:layout_margin="10dp"
55
            android:layout_row="1"
56             android:layout_column="1"
57             android:inputType="number"

58             android:ems="10"/> 

59         <TextView

60             android:id="@+id/textView3"

61             android:layout_width="wrap_content"

            android:layout_height="wrap_content"
62
            android:layout_margin="10dp"
63
            android:layout_row="2"
64
            android:layout_column="0"
65
            android:text="Dept"
66             android:textSize="20sp"
67             android:gravity="center"/> 
68         <Spinner
69             android:id="@+id/spinner"

70             android:layout_width="wrap_content"

71             android:layout_height="wrap_content"

            android:layout_margin="10dp"
72
            android:layout_row="2"
73
            android:layout_column="1"
74
            android:spinnerMode="dropdown"/> 
75
    </GridLayout> 
76
    <Button
77
        android:id="@+id/button"
78
        android:layout_width="wrap_content"
79         android:layout_height="wrap_content"
80         android:layout_alignParentBottom="true"

81         android:layout_centerInParent="true"

82         android:layout_marginBottom="150dp"
        android:text="Submit"/> 
83
</RelativeLayout>

 Now click on Design and your activity will look as given below.

 So now the designing part of Main Activity is completed.


Designing Layout for Second Activity:
 Click on app -> res -> layout -> activity_second.xml.

 Now click on Text as shown below.

 Then delete the code which is there and type the code as given below.
Code for Activity_second.xml:

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

2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
3
    android:layout_width="match_parent"
4
    android:layout_height="match_parent"
5
    tools:context="com.example.devang.exno2.SecondActivity"
6
    android:orientation="vertical"
7
    android:gravity="center"> 
8     <TextView
9         android:id="@+id/textView1"

10         android:layout_width="wrap_content"

11         android:layout_height="wrap_content"

12         android:layout_margin="20dp"

        android:text="New Text"
13
        android:textSize="30sp"/> 
14
    <TextView
15
        android:id="@+id/textView2"
16
        android:layout_width="wrap_content"
17
        android:layout_height="wrap_content"
18         android:layout_margin="20dp"
19         android:text="New Text"

20         android:textSize="30sp"/> 

21     <TextView

22         android:id="@+id/textView3"

23         android:layout_width="wrap_content"

        android:layout_height="wrap_content"
24
        android:layout_margin="20dp"
25
        android:text="New Text"
26
        android:textSize="30sp"/> 
27
</LinearLayout>

 Now click on Design and your activity will look as given below.

 So now the designing part of Second Activity is also completed.


Java Coding for the Android Application:
Java Coding for Main Activity:
 Click on app -> java -> com.example.exno2 -> MainActivity.

 Then delete the code which is there and type the code as given below.
Code for MainActivity.java:

1 package com.example.exno2; 

2 import android.content.Intent;

3 import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
4
import android.view.View;
5
import android.widget.ArrayAdapter;
6
import android.widget.Button;
7
import android.widget.EditText;
8
import android.widget.Spinner; 
9
public class MainActivity extends AppCompatActivity { 
10
    //Defining the Views
11     EditText e1,e2;
12     Button bt;

13     Spinner s; 

14     //Data for populating in Spinner

15     String [] dept_array={"CSE","ECE","IT","Mech","Civil"}; 

16     String name,reg,dept; 

17     @Override

18     protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
19
        setContentView(R.layout.activity_main); 
20
        //Referring the Views
21
        e1= (EditText) findViewById(R.id.editText);
22
        e2= (EditText) findViewById(R.id.editText2); 
23
        bt= (Button) findViewById(R.id.button); 
24
        s= (Spinner) findViewById(R.id.spinner); 
25
        //Creating Adapter for Spinner for adapting the data from array to Spinner
26
        ArrayAdapter adapter= new ArrayAdapter(MainActivity.this,android.R.layout.simple
27
        s.setAdapter(adapter); 
28
        //Creating Listener for Button
29
        bt.setOnClickListener(new View.OnClickListener() {
30             @Override
31             public void onClick(View v) { 
32                 //Getting the Values from Views(Edittext & Spinner)

33                 name=e1.getText().toString();

34                 reg=e2.getText().toString();

35                 dept=s.getSelectedItem().toString(); 

36                 //Intent For Navigating to Second Activity

37                 Intent i = new Intent(MainActivity.this,SecondActivity.class); 

                //For Passing the Values to Second Activity


38
                i.putExtra("name_key", name);
39
                i.putExtra("reg_key",reg);
40
                i.putExtra("dept_key", dept); 
41
                startActivity(i); 
42
            }
43
        });
44
    }
45 }

 So now the Coding part of Main Activity is completed.


Java Coding for Second Activity:
 Click on app -> java -> com.example.exno2 -> SecondActivity.
 Then delete the code which is there and type the code as given below.
Code for SecondActivity.java:
?
1 package com.example.exno2; 

2 import android.content.Intent;

3 import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
4
import android.widget.TextView; 
5
public class SecondActivity extends AppCompatActivity { 
6
    TextView t1,t2,t3; 
7
    String name,reg,dept; 
8
    @Override
9
    protected void onCreate(Bundle savedInstanceState) {
10
        super.onCreate(savedInstanceState);
11
        setContentView(R.layout.activity_second); 
12
        t1= (TextView) findViewById(R.id.textView1);
13
        t2= (TextView) findViewById(R.id.textView2);
14
        t3= (TextView) findViewById(R.id.textView3); 
15         //Getting the Intent
16         Intent i = getIntent(); 
17         //Getting the Values from First Activity using the Intent received

18         name=i.getStringExtra("name_key");

19         reg=i.getStringExtra("reg_key");

20         dept=i.getStringExtra("dept_key"); 

21         //Setting the Values to Intent

        t1.setText(name);
22
        t2.setText(reg);
23
        t3.setText(dept); 
24
25     }

 So now the Coding part of Second Activity is also completed.


 Now run the application to see the output.
Output:

                 
Result: Thus a Simple Android Application that uses Layout Managers and
Event Listeners is developed and executed successfully.

EXPERIMENT-3

Aim - Develop an Android application for basic calculator.

Step-1

 Open your Android Studio

 Click on Start a New Android Studio Project.

 Give your Application Name CrunchifyCalculator and leave other fields blank as it is, then

click NEXT.


Step-2

 Select the Minimum SDK API 15: Android 4.0.3(IceCreamSandwich). I selected API 15

(IceCreamSandwich) because it covers almost 94% device and it has almost all the features. If

you want to cover 100% device then you can select API 8: Android 2.2(Froyo).

Step-3

 Select the Empty Activity and click NEXT.


 Leave the activity name MainActivity as it is and leave everything as it is. Click
Finish.

Step-4

 After clicking Finish, it takes around ~2 minutes to build Activity and files.

 Here is a final project structure for your application.


Step-5

 Now we have to add our Java code in our MainActivity.java file.


 So open you MainActivity.java file from left side of IDE (app  -> java ->
com.crunchify.tutorials.crunchifycalculator -> MainActivity.java)
You can find the explanation of highlighted line below the code.

package com.crunchify.tutorials.crunchifycalculator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
Button button0, button1, button2, button3, button4, button5, button6,
button7, button8, button9, buttonAdd, buttonSub, buttonDivision,
buttonMul, button10, buttonC, buttonEqual;
EditText crunchifyEditText;
float mValueOne, mValueTwo;
boolean crunchifyAddition, mSubtract, crunchifyMultiplication, crunchifyDivision;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button0 = (Button) findViewById(R.id.button0);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
button6 = (Button) findViewById(R.id.button6);
button7 = (Button) findViewById(R.id.button7);
button8 = (Button) findViewById(R.id.button8);
button9 = (Button) findViewById(R.id.button9);
button10 = (Button) findViewById(R.id.button10);
buttonAdd = (Button) findViewById(R.id.buttonadd);
buttonSub = (Button) findViewById(R.id.buttonsub);
buttonMul = (Button) findViewById(R.id.buttonmul);
buttonDivision = (Button) findViewById(R.id.buttondiv);
buttonC = (Button) findViewById(R.id.buttonC);
buttonEqual = (Button) findViewById(R.id.buttoneql);
crunchifyEditText = (EditText) findViewById(R.id.edt1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "2");
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "3");
}
});
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "4");
}
});
button5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "5");
}
});
button6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "6");
}
});
button7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "7");
}
});
button8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "8");
}
});
button9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "9");
}
});
button0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + "0");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (crunchifyEditText == null) {
crunchifyEditText.setText("");
} else {
mValueOne = Float.parseFloat(crunchifyEditText.getText() + "");
crunchifyAddition = true;
crunchifyEditText.setText(null);
}
}
});
buttonSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(crunchifyEditText.getText() + "");
mSubtract = true;
crunchifyEditText.setText(null);
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(crunchifyEditText.getText() + "");
crunchifyMultiplication = true;
crunchifyEditText.setText(null);
}
});
buttonDivision.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueOne = Float.parseFloat(crunchifyEditText.getText() + "");
crunchifyDivision = true;
crunchifyEditText.setText(null);
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mValueTwo = Float.parseFloat(crunchifyEditText.getText() + "");
if (crunchifyAddition == true) {
crunchifyEditText.setText(mValueOne + mValueTwo + "");
crunchifyAddition = false;
}
if (mSubtract == true) {
crunchifyEditText.setText(mValueOne - mValueTwo + "");
mSubtract = false;
}
if (crunchifyMultiplication == true) {
crunchifyEditText.setText(mValueOne * mValueTwo + "");
crunchifyMultiplication = false;
}
if (crunchifyDivision == true) {
crunchifyEditText.setText(mValueOne / mValueTwo + "");
crunchifyDivision = false;
}
}
});
buttonC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText("");
}
});
button10.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
crunchifyEditText.setText(crunchifyEditText.getText() + ".");
}
});
}
}

Let’s understand code little-bit more.

 Line 11 – 14: Here we created the reference of Buttons and EditText.

 Line 16: Here we created two float variable for as value1 and value2.

 Line 21: We override the method onCreate() which is the method of Activity class.

 Line 45 – 50: We set onClickListener on Button1. If we click on Button1, EditText will display.

 We have implemented the same logic for every button.

 Line 115 – 127: Here we have set the click listener on Add button.

 Here we put the condition as, if we EditText is Null then we set EditText as empty value. Else we

add the two value which are clicked before add button clicked and after add button clicked.

 We also set the crunchifyAddition Boolean value to True. This true represent that add button

is clicked and this will be used when user click “=” button.

 We implement the same logic for other buttons also like buttonSub, ButtonMul, buttonDivision.

 Line 156 – 183: Here we set clickListener on “=” button. Here we put condition like if user

click Add button the crunchifyAddition value is set True on the click listener of Add button.

 According to that, corresponding action will be performed respective to button clicked.


if (crunchifyAddition == true) {
crunchifyEditText.setText(mValueOne + mValueTwo + "");
crunchifyAddition = false;
}

if Add button is clicked before the “=” button then Add action will be performed as you can see
above.

 After the action performed, we set the crunchifyAddition value to false, so that we can

perform Add action again.


Below is the layout file, with help to design front end for the calculator:

<?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/relative1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/edt1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/button4"
android:layout_alignRight="@+id/button4"
android:layout_below="@+id/edt1"
android:layout_marginTop="94dp"
android:text="1" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toLeftOf="@+id/button3"
android:layout_toStartOf="@+id/button3"
android:text="2" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_centerHorizontal="true"
android:text="3" />
<Button
android:id="@+id/button4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_toLeftOf="@+id/button2"
android:text="4" />
<Button
android:id="@+id/button5"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button4"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:text="5" />
<Button
android:id="@+id/button6"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button3"
android:layout_alignStart="@+id/button3"
android:layout_below="@+id/button3"
android:text="6" />
<Button
android:id="@+id/button7"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button4"
android:layout_toLeftOf="@+id/button2"
android:text="7" />
<Button
android:id="@+id/button8"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button5"
android:layout_alignStart="@+id/button5"
android:layout_below="@+id/button5"
android:text="8" />
<Button
android:id="@+id/button9"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button6"
android:layout_alignStart="@+id/button6"
android:layout_below="@+id/button6"
android:text="9" />
<Button
android:id="@+id/buttonadd"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/edt1"
android:layout_alignRight="@+id/edt1"
android:layout_alignTop="@+id/button3"
android:layout_marginLeft="46dp"
android:layout_marginStart="46dp"
android:layout_toRightOf="@+id/button3"
android:text="+" />
<Button
android:id="@+id/buttonsub"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/buttonadd"
android:layout_alignLeft="@+id/buttonadd"
android:layout_alignRight="@+id/buttonadd"
android:layout_alignStart="@+id/buttonadd"
android:layout_below="@+id/buttonadd"
android:text="-" />
<Button
android:id="@+id/buttonmul"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/buttonsub"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignStart="@+id/buttonsub"
android:layout_below="@+id/buttonsub"
android:text="*" />
<Button
android:id="@+id/button10"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button7"
android:layout_toLeftOf="@+id/button2"
android:text="." />
<Button
android:id="@+id/button0"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button8"
android:layout_alignStart="@+id/button8"
android:layout_below="@+id/button8"
android:text="0" />
<Button
android:id="@+id/buttonC"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button9"
android:layout_alignStart="@+id/button9"
android:layout_below="@+id/button9"
android:text="C" />
<Button
android:id="@+id/buttondiv"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/buttonmul"
android:layout_alignLeft="@+id/buttonmul"
android:layout_alignRight="@+id/buttonmul"
android:layout_alignStart="@+id/buttonmul"
android:layout_below="@+id/buttonmul"
android:text="/" />
<Button
android:id="@+id/buttoneql"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/buttondiv"
android:layout_alignLeft="@+id/button10"
android:layout_alignRight="@+id/buttondiv"
android:layout_alignStart="@+id/button10"
android:layout_below="@+id/button0"
android:layout_marginTop="37dp"
android:text="=" />
</RelativeLayout>

Now, all things should works fine and we are ready to run our calculator android app.
To run our app I used my mobile, you can use emulator or your device.

Running our Calculator Android App


 Click on Android device manager. After selecting your custom device in Android
device manager window, click START.

 Click on Run button.

 Choose Your device or emulator and click OK.

 Now you can see calculator android app running as this screenshot.

EXPERIMENT-4

Aim:
        To develop a Android Application that writes data to the SD Card.

Procedure:
Creating a New project:
 Open Android Studio and then click on File -> New -> New project.

 Then type the Application name as “ex.no.9″ and click Next. 

 Then select the Minimum SDK as shown below and click Next.


 Then select the Empty Activity and click Next. 

 Finally click Finish.

 It will take some time to build and load the project.


 After completion it will look as given below.
Designing layout for the Android Application:
 Click on app -> res -> layout -> activity_main.xml.

 Now click on Text as shown below.

 Then delete the code which is there and type the code as given below.
Code for Activity_main.xml:
?
1 <?xml version="1.0" encoding="utf-8"?>

2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
3
    android:layout_height="match_parent"
4
    android:layout_margin="20dp"
5
    android:orientation="vertical">
6
 
7
    <EditText
        android:id="@+id/editText"
8
        android:layout_width="match_parent"
9
        android:layout_height="wrap_content"
10
        android:singleLine="true"
11
        android:textSize="30dp" />
12
 
13     <Button
14         android:id="@+id/button"
15         android:layout_width="match_parent"

16         android:layout_height="wrap_content"

17         android:layout_margin="10dp"

        android:text="Write Data"
18
        android:textSize="30dp" />
19
 
20
    <Button
21
        android:id="@+id/button2"
22
        android:layout_width="match_parent"
23         android:layout_height="wrap_content"
24         android:layout_margin="10dp"
25         android:text="Read data"

26         android:textSize="30dp" />

27  

28     <Button

        android:id="@+id/button3"
29
        android:layout_width="match_parent"
30
        android:layout_height="wrap_content"
31
        android:layout_margin="10dp"
32
        android:text="Clear"
33
        android:textSize="30dp" />
34
 
35 </LinearLayout>

 Now click on Design and your application will look as given below.


 So now the designing part is completed.
Adding permissions in Manifest for the Android
Application:
 Click on app -> manifests -> AndroidManifest.xml

 Now include the WRITE_EXTERNAL_STORAGE permissions in the


AndroidManifest.xml file as shown below

Code for AndroidManifest.xml:


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

2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.exno9" >
3
 
4
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-per
5
 
6
    <application
7
        android:allowBackup="true"
8
        android:icon="@mipmap/ic_launcher"
9
        android:label="@string/app_name"
10         android:supportsRtl="true"
11         android:theme="@style/AppTheme" >

12         <activity android:name=".MainActivity" >

13             <intent-filter>

14                 <action android:name="android.intent.action.MAIN" />

15  
                <category android:name="android.intent.category.LAUNCHER" />
16
            </intent-filter>
17
        </activity>
18
    </application>
19
</manifest>
20

 So now the Permissions are added in the Manifest.


Java Coding for the Android Application:
 Click on app -> java -> com.example.exno9 -> MainActivity.

 Then delete the code which is there and type the code as given below.
Code for MainActivity.java:
1 package com.example.exno9;

2  

3 import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
4
import android.view.View;
5
import android.widget.Button;
6
import android.widget.EditText;
7
import android.widget.Toast;
8
 
9 import java.io.BufferedReader;

10 import java.io.File;

import java.io.FileInputStream;
11
import java.io.FileOutputStream;
12
import java.io.InputStreamReader;
13
 
14
public class MainActivity extends AppCompatActivity
15
{
16     EditText e1;
17     Button write,read,clear;
18     @Override

19     protected void onCreate(Bundle savedInstanceState)

20     {

        super.onCreate(savedInstanceState);
21
        setContentView(R.layout.activity_main);
22
 
23
        e1= (EditText) findViewById(R.id.editText);
24
        write= (Button) findViewById(R.id.button);
25
        read= (Button) findViewById(R.id.button2);
26         clear= (Button) findViewById(R.id.button3);
27
 
28         write.setOnClickListener(new View.OnClickListener()
29         {

30             @Override

31             public void onClick(View v)

            {
32
                String message=e1.getText().toString();
33
                try
34
                {
35
                    File f=new File("/sdcard/myfile.txt");
36
                    f.createNewFile();
37                     FileOutputStream fout=new FileOutputStream(f);
38                     fout.write(message.getBytes());

39                     fout.close();

40                     Toast.makeText(getBaseContext(),"Data Written in SDCARD",Toast.LENG

                }
41
                catch (Exception e)
42
43                 {

44                     Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_LONG).s

                }
45
            }
46
        });
47
 
48
        read.setOnClickListener(new View.OnClickListener()
49
        {
50             @Override
51             public void onClick(View v)

52             {

53                 String message;

54                 String buf = "";

                try
55
                {
56
                    File f = new File("/sdcard/myfile.txt");
57
                    FileInputStream fin = new FileInputStream(f);
58
                    BufferedReader br = new BufferedReader(new InputStreamReader(fin));
59                     while ((message = br.readLine()) != null)
60                     {
61                         buf += message;

62                     }

63                     e1.setText(buf);

                    br.close();
64
                    fin.close();
65
                    Toast.makeText(getBaseContext(),"Data Recived from SDCARD",Toast.LE
66
                }
67
                catch (Exception e)
68                 {
69                     Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG)
70                 }

71             }

72         });

73  
        clear.setOnClickListener(new View.OnClickListener()
74
        {
75
            @Override
76
            public void onClick(View v)
77
            {
78
                e1.setText("");
79
            }
80
        });
81
    }

 So now the Coding part is also completed.


 Now run the application to see the output.
Output:

 
Result:
              Thus Android Application that writes data to the SD Card is developed and
executed successfully.

EXPERIMENT -5
AIM - Develop an Android application that uses Fragments

A fragment represents a modular portion of the user interface within an activity. A fragment has its
own lifecycle, receives its own input events, and you can add or remove fragments while the
containing activity is running.

This document describes how to create a fragment and include it in an activity.


Setup your environment
Fragments require a dependency on the AndroidX Fragment library. You need to add the Google
Maven repository to your project's settings.gradle file in order to include this dependency.

Groovy

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        ...
  }
}

To include the AndroidX Fragment library to your project, add the following dependencies in your
app's build.gradle file:

Groovy

dependencies {
    def fragment_version = "1.5.4"

    // Java language implementation


    implementation "androidx.fragment:fragment:$fragment_version"
    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
}

Create a fragment class


To create a fragment, extend the AndroidX Fragment class, and override its methods to insert your
app logic, similar to the way you would create an Activity class. To create a minimal fragment that
defines its own layout, provide your fragment's layout resource to the base constructor, as shown
in the following example:

Java

class ExampleFragment extends Fragment {


    public ExampleFragment() {
        super(R.layout.example_fragment);
  }
}
DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog
helper methods in the Activity class, as fragments automatically handle the creation and cleanup of
the Dialog. See Displaying dialogs with DialogFragment for more details.

PreferenceFragmentCompat

Displays a hierarchy of Preference objects as a list. You can use PreferenceFragmentCompat to create a


settings screen for your app.
Add a fragment to an activity
Generally, your fragment must be embedded within an AndroidX FragmentActivity to contribute a
portion of UI to that activity's layout. FragmentActivity is the base class for AppCompatActivity, so if
you're already subclassing AppCompatActivity to provide backward compatibility in your app, then
you do not need to change your activity base class. You can add your fragment to the activity's
view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment
container in your activity's layout file and then programmatically adding the fragment from within
your activity. In either case, you need to add a FragmentContainerView that defines the location
where the fragment should be placed within the activity's view hierarchy. It is strongly
recommended to always use a FragmentContainerView as the container for fragments,
as FragmentContainerView includes fixes specific to fragments that other view groups such
as FrameLayout do not provide.

Add a fragment via XML

To declaratively add a fragment to your activity layout's XML, use a FragmentContainerView element.

Here's an example activity layout containing a single FragmentContainerView:

<!-- res/layout/example_activity.xml -->


<androidx.fragment.app.FragmentContainerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.example.ExampleFragment" />

The android:name attribute specifies the class name of the Fragment to instantiate. When the activity's
layout is inflated, the specified fragment is instantiated, onInflate() is called on the newly
instantiated fragment, and a FragmentTransaction is created to add the fragment to
the FragmentManager.

Note: You can use the class attribute instead of android:name as an alternative way to specify


which Fragment to instantiate.

Add a fragment programmatically

To programmatically add a fragment to your activity's layout, the layout should include
a FragmentContainerView to serve as a fragment container, as shown in the following example:

<!-- res/layout/example_activity.xml -->


<androidx.fragment.app.FragmentContainerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Unlike the XML approach, the android:name attribute isn't used on the FragmentContainerView here, so


no specific fragment is automatically instantiated. Instead, a FragmentTransaction is used to
instantiate a fragment and add it to the activity's layout. While your activity is running, you can
make fragment transactions such as adding, removing, or replacing a fragment. In
your FragmentActivity, you can get an instance of the FragmentManager, which can be used to create
a FragmentTransaction. Then, you can instantiate your fragment within your
activity's onCreate() method using FragmentTransaction.add(), passing in the View Group ID of the
container in your layout and the fragment class you want to add and then commit the transaction,
as shown in the following example:

Java

public class ExampleActivity extends AppCompatActivity {


    public ExampleActivity() {
        super(R.layout.example_activity);
  }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                .setReorderingAllowed(true)
                .add(R.id.fragment_container_view, ExampleFragment.class, null)
                .commit();
    }
  }
}

Note: You should always use setReorderingAllowed(true) when performing a FragmentTransaction.


For more information on reordered transactions, see Fragment transactions.In the previous example, note
that the fragment transaction is only created when savedInstanceState is null. This is to ensure that the
fragment is added only once, when the activity is first created. When a configuration change occurs and the
activity is recreated, savedInstanceState is no longer null, and the fragment does not need to be added a
second time, as the fragment is automatically restored from the savedInstanceState.

If your fragment requires some initial data, arguments can be passed to your fragment by
providing a Bundle in the call to FragmentTransaction.add(), as shown below:

Java

public class ExampleActivity extends AppCompatActivity {


    public ExampleActivity() {
        super(R.layout.example_activity);
  }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            Bundle bundle = new Bundle();
            bundle.putInt("some_int", 0);

            getSupportFragmentManager().beginTransaction()
                .setReorderingAllowed(true)
                .add(R.id.fragment_container_view, ExampleFragment.class, bundle)
                .commit();
    }
  }
}
The arguments Bundle can then be retrieved from within your fragment by calling requireArguments(), and the
appropriate Bundle getter methods can be used to retrieve each argument.
Java

class ExampleFragment extends Fragment {


    public ExampleFragment() {
        super(R.layout.example_fragment);
  }
    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        int someInt = requireArguments().getInt("some_int");
        ...
  }
}

EXPERIMENT – 6
AIM- Develop an Android application that uses Navigation
component.
Set up your environment
Note: The Navigation component requires Android Studio 3.3 or higher and is dependent on Java 8 language
features.

To include Navigation support in your project, add the following dependencies to your
app's build.gradle file:

Kotlin

dependencies {
  val nav_version = "2.5.3"

  // Java language implementation


  implementation("androidx.navigation:navigation-fragment:$nav_version")
  implementation("androidx.navigation:navigation-ui:$nav_version")

  // Kotlin
  implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
  implementation("androidx.navigation:navigation-ui-ktx:$nav_version")

  // Feature module Support


  implementation("androidx.navigation:navigation-dynamic-features-fragment:$nav_version")

  // Testing Navigation
  androidTestImplementation("androidx.navigation:navigation-testing:$nav_version")

  // Jetpack Compose Integration


  implementation("androidx.navigation:navigation-compose:$nav_version")
}
For information on adding other Architecture Components to your project, see Adding components
to your project.

Create a navigation graph


Navigation occurs between your app's destinations—that is, anywhere in your app to which users
can navigate. These destinations are connected via actions.

A navigation graph is a resource file that contains all of your destinations and actions. The graph
represents all of your app's navigation paths.

Figure 1 shows a visual representation of a navigation graph for a sample app containing six
destinations connected by five actions. Each destination is represented by a preview thumbnail,
and connecting actions are represented by arrows that show how users can navigate from one
destination to another.

Figure 1. A navigation graph that shows


previews of six different destinations that are connected via five actions.

1. Destinations are the different content areas in your app.


2. Actions are logical connections between your destinations that represent paths that users can take.

To add a navigation graph to your project, do the following:

1. In the Project window, right-click on the res directory and select New > Android Resource File. The New
Resource File dialog appears.
2. Type a name in the File name field, such as "nav_graph".
3. Select Navigation from the Resource type drop-down list, and then click OK.

When you add your first navigation graph, Android Studio creates a navigation resource directory
within the res directory. This directory contains your navigation graph resource file ( nav_graph.xml,
for example).

Note: When adding a navigation graph to your project, if you haven't already added navigation dependencies to your
app's build.gradle file, Android Studio displays a prompt and offers to add the dependencies for you. Note,
however, that Android Studio 3.4 adds the non-KTX 1.0.0 versions of the dependencies, so be sure to replace these
values if you are using Kotlin or intend to use version 2.0.0 or higher.

Navigation Editor
After adding a graph, Android Studio opens the graph in the Navigation Editor. In the Navigation
Editor, you can visually edit navigation graphs or directly edit the underlying XML.

Figure 2. The Navigation Editor

1. Destinations panel: Lists your navigation host and all destinations currently in the Graph Editor.
2. Graph Editor: Contains a visual representation of your navigation graph. You can switch
between Design view and the underlying XML representation in the Text view.
3. Attributes: Shows attributes for the currently-selected item in the navigation graph.

Click the Text tab to see the corresponding XML, which should look similar to the following
snippet:

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


<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/nav_graph">

</navigation>

The <navigation> element is the root element of a navigation graph. As you add destinations and
connecting actions to your graph, you can see the
corresponding <destination> and <action> elements here as child elements. If you have nested
graphs, they appear as child <navigation> elements.

Add a NavHost to an activity


One of the core parts of the Navigation component is the navigation host. The navigation host is
an empty container where destinations are swapped in and out as a user navigates through your
app.

A navigation host must derive from NavHost. The Navigation component's


default NavHost implementation, NavHostFragment, handles swapping fragment destinations.

Note: The Navigation component is designed for apps that have one main activity with multiple fragment
destinations. The main activity is associated with a navigation graph and contains a NavHostFragment that is
responsible for swapping destinations as needed. In an app with multiple activity destinations, each activity has its
own navigation graph.

Add a NavHostFragment via XML

The XML example below shows a NavHostFragment as part of an app's main activity:
<?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">

    <androidx.appcompat.widget.Toolbar
        .../>

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"

        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        .../>

</androidx.constraintlayout.widget.ConstraintLayout>

Note the following:

 The android:name attribute contains the class name of your NavHost implementation.


 The app:navGraph attribute associates the NavHostFragment with a navigation graph. The navigation graph
specifies all of the destinations in this NavHostFragment to which users can navigate.
 The app:defaultNavHost="true" attribute ensures that your NavHostFragment intercepts the system Back button.
Note that only one NavHost can be the default. If you have multiple hosts in the same layout (two-pane
layouts, for example), be sure to specify only one default NavHost.

You can also use the Layout Editor to add a NavHostFragment to an activity by doing the following:

1. In your list of project files, double-click on your activity's layout XML file to open it in the Layout Editor.
2. Within the Palette pane, choose the Containers category, or alternatively search for "NavHostFragment".
3. Drag the NavHostFragment view onto your activity.
4. Next, in the Navigation Graphs dialog that appears, choose the corresponding navigation graph to
associate with this NavHostFragment, and then click OK.

Add destinations to the navigation graph


You can create a destination from an existing fragment or activity. You can also use the
Navigation Editor to create a new destination or create a placeholder to later replace with a
fragment or activity.

In this example, let's create a new destination. To add a new destination using the Navigation
Editor, do the following:

1. In the Navigation Editor, click the New Destination icon  , and then click Create new destination.
2. In the New Android Component dialog that appears, create your fragment. For more information on
fragments, see the fragment documentation.

Back in the Navigation Editor, notice that Android Studio has added this destination to the graph.

Figure 3 shows an example of a destination and a placeholder destination.

Figure 3. A destination and a placeholder

For other ways to add destinations to your navigation graph, see Create destinations.

Anatomy of a destination
Click on a destination to select it, and note the following attributes in the Attributes panel:

 The Type field indicates whether the destination is implemented as a fragment, activity, or other custom
class in your source code.
 The Label field contains the user-readable name of the destination. This might be surfaced to the UI—for
example, if you connect the NavGraph to a Toolbar using setupWithNavController(). For this reason, it is
recommended that you use resource strings for this value.
 The ID field contains the ID of the destination which is used to refer to the destination in code.
 The Class dropdown shows the name of the class that is associated with the destination. You can click this
dropdown to change the associated class to another destination type.

Click the Text tab to show the XML view of your navigation graph. The XML contains the
same id, name, label, and layout attributes for the destination, as shown below:

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


<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    app:startDestination="@id/blankFragment">
    <fragment
        android:id="@+id/blankFragment"
        android:name="com.example.cashdog.cashdog.BlankFragment"
        android:label="@string/label_blank"
        tools:layout="@layout/fragment_blank" />
</navigation>

Designate a screen as the start destination


The start destination is the first screen users see when opening your app, and it's the last screen
users see when exiting your app. The Navigation editor uses a house icon   to indicate the
start destination.

Once you have all of your destinations in place, you can choose a start destination by doing the
following:

1. In the Design tab, click on the destination to highlight it.


2. Click the Assign start destination button  . Alternatively, you can right-click on the
destination and click Set as Start Destination.

Connect destinations
An action is a logical connection between destinations. Actions are represented in the navigation
graph as arrows. Actions usually connect one destination to another, though you can also
create global actions that take you to a specific destination from anywhere in your app.

With actions, you're representing the different paths that users can take through your app. Note
that to actually navigate to destinations, you still need to write the code to perform the navigation.
This is covered in the Navigate to a destination section later in this topic.

You can use the Navigation Editor to connect two destinations by doing the following:

1. In the Design tab, hover over the right side of the destination that you want users to navigate
from. A circle appears over the right side of the destination, as shown in figure 4.

Figure 4. A destination with an action connection circle

2. Click and drag your cursor over the destination you want users to navigate to, and release. The
resulting line between the two destinations represents an action, as shown in figure 5.

Figure 5. Connecting destinations with an action

3. Click on the arrow to highlight the action. The following attributes appear in the Attributes panel:
 The Type field contains “Action”.
 The ID field contains the ID for the action.
 The Destination field contains the ID for the destination fragment or activity.

4. Click the Text tab to toggle to the XML view. An action element is now added to the source
destination. The action has an ID and a destination attribute that contains the ID of the next
destination, as shown in the example below:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    app:startDestination="@id/blankFragment">
    <fragment
        android:id="@+id/blankFragment"
        android:name="com.example.cashdog.cashdog.BlankFragment"
        android:label="@string/label_blank"
        tools:layout="@layout/fragment_blank" >
        <action
            android:id="@+id/action_blankFragment_to_blankFragment2"
            app:destination="@id/blankFragment2" />
    </fragment>
    <fragment
        android:id="@+id/blankFragment2"
        android:name="com.example.cashdog.cashdog.BlankFragment2"
        android:label="@string/label_blank_2"
        tools:layout="@layout/fragment_blank_fragment2" />
</navigation>

In your navigation graph, actions are represented by <action> elements. At a minimum, an action


contains its own ID and the ID of the destination to which a user should be taken.

Navigate to a destination
Navigating to a destination is done using a NavController, an object that manages app navigation
within a NavHost. Each NavHost has its own corresponding NavController. You can retrieve
a NavController by using one of the following methods:

Kotlin:

 Fragment.findNavController()

 View.findNavController()

 Activity.findNavController(viewId: Int)

Java:

 NavHostFragment.findNavController(Fragment)

 Navigation.findNavController(Activity, @IdRes int viewId)

 Navigation.findNavController(View)
When creating the NavHostFragment using FragmentContainerView or if manually adding
the NavHostFragment to your activity via a FragmentTransaction, attempting to retrieve
the NavController in onCreate() of an Activity via Navigation.findNavController(Activity, @IdRes int) will fail.
You should retrieve the NavController directly from the NavHostFragment instead.

Kotlin

val navHostFragment =
        supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController

Ensure type-safety by using Safe Args

The recommended way to navigate between destinations is to use the Safe Args Gradle plugin.
This plugin generates simple object and builder classes that enable type-safe navigation and
argument passing between destinations.

Note: For other ways to navigate, see Navigate to a destination.

To add Safe Args to your project, include the following classpath in your top level build.gradle file:

Kotlin

buildscript {
    repositories {
        google()
  }
    dependencies {
        val nav_version = "2.5.3"
        classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
  }
}

You must also apply one of two available plugins.

To generate Java language code suitable for Java or mixed Java and Kotlin modules, add this line
to your app or module's build.gradle file:

Kotlin

plugins {
    id("androidx.navigation.safeargs")
}

Alternatively, to generate Kotlin code suitable for Kotlin-only modules add:

Kotlin

plugins {
    id("androidx.navigation.safeargs.kotlin")
}
You must have android.useAndroidX=true in your gradle.properties file as per Migrating to AndroidX.

After you enable Safe Args, the plugin generates code that contains classes and methods for each
action you've defined. For each action, Safe Args also generates a class for each originating
destination, which is the destination from which the action originates. The generated class name is
a combination of the originating destination class name and the word "Directions". For example, if
the destination is named SpecifyAmountFragment, the generated class is
named SpecifyAmountFragmentDirections. The generated class contains a static method for each
action defined in the originating destination. This method takes any defined action parameters as
arguments and returns a NavDirections object that you can pass to navigate().

As an example, assume we have a navigation graph with a single action that connects the
originating destination, SpecifyAmountFragment, to a receiving destination, ConfirmationFragment.

Safe Args generates a SpecifyAmountFragmentDirections class with a single


method, actionSpecifyAmountFragmentToConfirmationFragment() that returns a NavDirections object. This
returned NavDirections object can then be passed directly to navigate(), as shown in the following
example:

Kotlin

override fun onClick(view: View) {


    val action =
        SpecifyAmountFragmentDirections
            .actionSpecifyAmountFragmentToConfirmationFragment()
    view.findNavController().navigate(action)
}

EXPERIMENT – 7

Aim - Develop an Android application that uses GPS location information.


With the incorporation of GPS devices in smartphones, Location Based Services (LBS) have become
pretty hot the past few years. The iPhone was the first to give a huge boost to this kind of applications
and now Android continues on the same path. In this tutorial, I will show you how to build your first
LBS application for Android. The first step is retrieving the user’s current location and then using his
coordinates to provide data for that location.In general, the user’s pinpointing on the map is feasible in
one of the following ways:
1. Using the GPS device that comes with the mobile
2. Using the ID of the Cell that the user is currently served by
The first one is much easier and more accurate (since the second provides only an approximation).
Since these days a big number of phones do have GPS devices onboard, we will use the first way. The
Android SDK’s emulator can emulate changes in the user’s location and provide dummy data for his
coordinates.
Let’s get started by creating a new Android Project in Eclipse. I gave it the fancy name
“AndroidLbsGeocodingProject” and used the properties as shown in the following image:
Note that I used the Android 1.5 platform version and “3” as the SDK’s min version. The application is
not going to use any of the new super-duper APIs, so I decided to go with one of the first versions for
backwards compatibility. It is generally a good idea to support as many versions as possible. You can
find information regarding the platform versions and their corresponding market share here.
To start with, we will only add a button which will trigger the retrieval of the current location’s
coordinates from a location provider. Thus, the “main.xml” file for the application’s interface will be as
simple as this:
01
02 <?xml version="1.0" encoding="utf-8"?>
03 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
04     android:layout_width="fill_parent"
05     android:layout_height="fill_parent"
06     >
07 <Button
08  android:id="@+id/retrieve_location_button"
 android:text="Retrieve Location"
09  android:layout_width="wrap_content"
10  android:layout_height="wrap_content"
11  />
12 </LinearLayout>
13
In order to get started with the location capabilities of the Android API, the first step is to take
reference of the LocationManager class, which provides access to the system location services. This is
done via the getSystemService of our activity (actually it inherits it from the Context parent class).
Then, we request updates of the device’s location using the method requestLocationUpdates. In that
method, we provide the name of the preferred location provider (in our case GPS), the minimum time
interval for notifications (in milliseconds), the minimum distance interval for notifications (in meters)
and finally a class implementing the LocationListener interface. That interface declares methods for
handling changes in the user’s location as well as changes in the location provider’s status. All the
above can be translated into code as below:
01 package com.javacodegeeks.android.lbs;
02  
import android.app.Activity;
03 import android.content.Context;
04 import android.location.Location;
05 import android.location.LocationListener;
06 import android.location.LocationManager;
07 import android.os.Bundle;
import android.view.View;
08 import android.view.View.OnClickListener;
09 import android.widget.Button;
10 import android.widget.Toast;
11  
12 public class LbsGeocodingActivity extends Activity {
13      
14     private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
15     private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
16      
    protected LocationManager locationManager;
17
     
18     protected Button retrieveLocationButton;
19      
20     @Override
21     public void onCreate(Bundle savedInstanceState) {
22          
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.main);
25  
        retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);
26
         
27         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
28          
29         locationManager.requestLocationUpdates(
30                 LocationManager.GPS_PROVIDER,
31                 MINIMUM_TIME_BETWEEN_UPDATES,
32                 MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                new MyLocationListener()
33         );
34          
35     retrieveLocationButton.setOnClickListener(new OnClickListener() {
36             @Override
37             public void onClick(View v) {
38                 showCurrentLocation();
            }
39     });       
40          
41     }   
42  
43     protected void showCurrentLocation() {
44  
45         Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PRO
46  
        if (location != null) {
47
            String message = String.format(
48                     "Current Location \n Longitude: %1$s \n Latitude: %2$s",
49                     location.getLongitude(), location.getLatitude()
50             );
51             Toast.makeText(LbsGeocodingActivity.this, message,
                    Toast.LENGTH_LONG).show();
52         }
53  
54     }  
55  
56     private class MyLocationListener implements LocationListener {
57  
58         public void onLocationChanged(Location location) {
59             String message = String.format(
                    "New Location \n Longitude: %1$s \n Latitude: %2$s",
60                     location.getLongitude(), location.getLatitude()
61             );
62             Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show()
63         }
64  
        public void onStatusChanged(String s, int i, Bundle b) {
65             Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
66                     Toast.LENGTH_LONG).show();
67         }
68  
69         public void onProviderDisabled(String s) {
70             Toast.makeText(LbsGeocodingActivity.this,
                    "Provider disabled by the user. GPS turned off",
71                     Toast.LENGTH_LONG).show();
72         }
73  
74         public void onProviderEnabled(String s) {
75             Toast.makeText(LbsGeocodingActivity.this,
                    "Provider enabled by the user. GPS turned on",
76
                    Toast.LENGTH_LONG).show();
77         }
78  
79     }
80 }
For the LocationListener interface, we implemented the MyLocationListener inner class. The methods
in that class just use Toasts to provide info about the GPS status or any location changes. The only
interface element is a Button which gets hooked up with a OnClickListener and when it is clicked, the
showCurrentLocation method is invoked. Then, the getLastKnownLocation of the LocationManager
instance is executed returning the last known Location. From a Location object we can get information
regarding the user’s altitude, latitude, longitude, speed etc. In order to be able to run the above code,
the necessary permissions have to be granted. These are:
 ACCESS_FINE_LOCATION
 ACCESS_MOCK_LOCATION
 ACCESS_COARSE_LOCATION

Include those in the AndroidManifest.xml file, which will be as follows:


01 <?xml version="1.0" encoding="utf-8"?>
02  
03 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.javacodegeeks.android.lbs"
04       android:versionCode="1"
05       android:versionName="1.0">
06        
07     <application android:icon="@drawable/icon" android:label="@string/app_name">
08         <activity android:name=".LbsGeocodingActivity"
09                   android:label="@string/app_name">
            <intent-filter>
10                 <action android:name="android.intent.action.MAIN" />
11                 <category android:name="android.intent.category.LAUNCHER" />
12             </intent-filter>
13         </activity>
14  
15     </application>
16      
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
17  <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
18  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
19      
20     <uses-sdk android:minSdkVersion="3" />
21  
22 </manifest>
Next, use the AVD Manager in order to create a new Android device and make sure that GPS support
is included in the features:
Next, use “Run–> Run Configurations…” to create a new configuration for the project:

If you hit Run, the emulator is started, but nothing will really happen when the button is clicked. That
is because when the emulator starts, there is no last known location to be retrieved
(the Location instance that is returned is null).
We have to feed the emulator with some dummy data. Go to the DDMS view of Eclipse and look for
the “Emulation Control” tab. There, among other things, you will find the “Location Controls” section,
which can send mock location data to the emulator. In the “Manual” tab, just hit the “Send” button,
there are already some coordinates set up.

When the data are sent to the emulator’s GPS device, our listener will be triggered and the current
location will be printed in the screen in the form of a Toast notification.
Now, a last known location exists, so if you hit the “Retrieve Location” button, a not null location will
be fetched and the coordinates will again be printed in the screen:

That’s it. 
EXPERIMENT – 8

AIM-Develop an Android application using various Firebase services.


There are various services offered online such as storage, online processing, realtime
database, authorisation of user etc. Google developed a platform called Firebase that
provide all these online services. It also gives a daily analysis of usage of these services
along with the details of user using it.
To simplify, it can be said that Firebase is a mobile and web application development
platform. It provides services that a web application or mobile application might require.
Anyone can easily include firebase to there application and it will make their online work
way easier than it was used to be.
There are two ways to add firebase to any Android app:
Using Firebase Assistant
Below are the steps to include Firebase to Android project in Android studio:
1. Update the android studio (>= 2.2)
2. Create a new project in the firebase by clicking on the Add project.
3. Now open the android studio and click on Tools in the upper left corner.

4. Now click on the Firebase option in the drop down menu.

5. A menu will appear on the right side of screen. It will show various services that
Firebase offers. Choose the desired service.
6. Now Click on the Connect to Firebase option in the menu of desired service.

7. Add the dependencies of your service by clicking on the Add [YOUR SERVICE


NAME] to the app option. (In the image below, the Firebase cloud messaging
service is chosen)
Manually adding firebase

In this, the steps involve:


8. Create a firebase project
 Create a project by clicking on create project in the firebase console.

 Fill the necessary details in the pop up window about the project. Edit the
project ID if required.

 Click on create project to finally create it.


9. Now add this project to the android app
 Click on the Add firebase to your android app option on the starting
window.
 A prompt will open where to enter the package name of the app.
 Now the app is connected to the Firebase. Now all the cloud based as well
server based services can be easily used in the app.
 Now the app will be registered with firebase.

10. Also, the SHA1 certificate, can be given, of the app by following steps:

11. Go to android studio project


12.  ↳ gradle
13.    ↳ root folder
14.      ↳ Tasks
15.        ↳ Android
16.          ↳ signingReport
           ↳ copy paste SHA1 from console
17. Now download the google-services.json file and place it in the root
directory of the android app.

18. Now add the following in the project.


 Adding the sdk in the project.
Add the following code to the PROJECT-LEVELbuild.gradle of the app.

buildscript {

  dependencies {

    classpath 'com.google.gms:google-services:4.0.0'

  }

 Add the following code to APP-LEVEL build.gradle of the app.

dependencies {

  compile 'com.google.firebase:firebase-core:16.0.0'

...
// Add to the bottom of the file

apply plugin: 'com.google.gms.google-services'

19. Now Sync the Gradle by clicking on sync now.


20. After adding the above code(sdk), run the app to send the verification to the
Firebase console.

--------Thank You--------

You might also like