Mobile Application File
Mobile Application File
Mobile Application File
PRACTICAL FILE
Procedure:
Creating a New project:
Open Android Studio and then click on File -> New -> New project.
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 }
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 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.
Then delete the code which is there and type the code as given below.
Code for Activity_second.xml:
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.
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;
15 String [] dept_array={"CSE","ECE","IT","Mech","Civil"};
16 String name,reg,dept;
17 @Override
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();
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");
t1.setText(name);
22
t2.setText(reg);
23
t3.setText(dept);
24
25 }
Result: Thus a Simple Android Application that uses Layout Managers and
Event Listeners is developed and executed successfully.
EXPERIMENT-3
Step-1
click NEXT.
Step-2
(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
Step-4
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() + ".");
}
});
}
}
Line 16: Here we created two float variable for as value1 and value2.
Line 45 – 50: We set onClickListener on Button1. If we click on Button1, EditText will display.
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.
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
if Add button is clicked before the “=” button then Add action will be performed as you can see
above.
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.
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 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>
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" >
13 <intent-filter>
15
<category android:name="android.intent.category.LAUNCHER" />
16
</intent-filter>
17
</activity>
18
</application>
19
</manifest>
20
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
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
{
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();
}
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;
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
}
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.
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
PreferenceFragmentCompat
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.
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:
Java
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
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
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"
// Kotlin
implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
implementation("androidx.navigation:navigation-ui-ktx:$nav_version")
// Testing Navigation
androidTestImplementation("androidx.navigation:navigation-testing:$nav_version")
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.
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.
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:
</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.
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.
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>
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.
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.
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:
Once you have all of your destinations in place, you can choose a start destination by doing the
following:
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.
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.
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>
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(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
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.
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")
}
}
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")
}
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.
Kotlin
EXPERIMENT – 7
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
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.
Fill the necessary details in the pop up window about the project. Edit the
project ID if required.
10. Also, the SHA1 certificate, can be given, of the app by following steps:
buildscript {
dependencies {
classpath 'com.google.gms:google-services:4.0.0'
}
dependencies {
compile 'com.google.firebase:firebase-core:16.0.0'
...
// Add to the bottom of the file
--------Thank You--------