0% found this document useful (0 votes)
24 views37 pages

IT487 - M5 - Ch14 and Ch16 - STD

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

IT487 - M5 - Ch14 and Ch16 - STD

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

‫الجامعة السعودية االلكترونية‬

‫الجامعة السعودية االلكترونية‬

‫‪26/12/2021‬‬
College of Computing and
Informatics
Bachelor of Science in Computer
Science
IT487
Mobile Application Development
IT487
Mobile Application Development

Module 5
Android Dialog Window & Adapters and Recyclers
Contents
1.Dialog windows.
2.RecyclerView and RecyclerAdapter.
3.Adding RecyclerView, RecyclerAdapter.
4.Running the app.
Weekly Learning
Outcomes
1. Explain how to use Android Dialog windows in
app.
2. Explain how to use RecyclerView and
RecyclerAdapter.
Required Reading
1. Chapter 14 & Chapter 16 (Android Programming for
Beginners 3rd Edition, 2021 by John Horton , Packt
Publishing Ltd.)
Dialog windows
Dialog window
• → Dialog window is pop-up window to display notification or confirmation messages to the user.
• → Dialogs in Android are sophisticated classes that consists of layouts and other specific User
Interface (UI) elements.
• → The best way to create a dialog window in Android is to use the DialogFragment class.
• Creating the Dialog Demo project: create a new project in Android Studio named “Dialog
Demo” with Empty Activity template.
• Coding a DialogFragment class: Create a new JAVA class and refer it as “MyDialog” in same
package that has the MainActivity.java file.
• Change the class declaration to extend DialogFragment
public class MyDialog extends DialogFragment {
}
• Import the DialogFragment class: Add the code in the MyDialog.java file
package com.example.dialogdemo;
import androidx.fragment.app.DialogFragment;
public class MyDialog extends DialogFragment {
}
Dialog window
• Add the following highlighted code to override the onCreateDialog method
public class MyDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class because this dialog has a simple UI
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
}
}
• You will need to import the Dialog, Bundle, and AlertDialog classes
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;

• The onCreateDialog method will be called by Android via code in the MainActivity class.
• Declare and Initialize AlertDialog.Builder object.
• The getActivity method is part of the Fragment / DialogFragment class and it returns a
reference to Activity, which will create DialogFragment. In this case, that is our
MainActivity class.
Configure DialogFragment: Chaining

• Chaining: is the process of calling more than one method in a sequence (single
line) on the same object instead of calling multiple methods with the same object
reference separately.
• Similar to writing multiple lines of code in a concise manner.
• Example: When a Toast message is created and added a .show() method to
the end of it.
Toast.makeText (this, "our message", Toast.LENGTH_SHORT).show(); // with
chaining (1 line)
Toast toast = Toast.makeText (this, "Hello", Toast.LENGTH_SHORT); //
WithOUT chaining ( 2 lines)
toast.show();
Configure DialogFragment: Chaining

• Add the code (which uses chaining) inside the onCreateDialog method
// Dialog will have “Dialog Window" as the title
builder.setMessage(“Dialog Window")
// An OK button that does nothing
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Nothing happening here
}
});
// Create the object and return it
return builder.create();
• Import the Dialog interface class
import android.content.DialogInterface
• Builder.setMessage: sets the main message for the user in the dialog window.
• .setPositiveButton: sets the “OK” as the text of the button which is the argument in this
method.
• DialogInterface.onClickListener: handles any click on the button.
• return statement: takes the control to MainActivity class.
• Then, fully configured dialog window is created.
Using the DialogFragment class
• Add a button to our layout. Perform the following steps:
1. Switch to the activity_main.xml tab and then switch to the Design tab.
2. Drag a Button onto the layout and set its “id” attribute to button.
3. Click on the Infer Constraints button to constrain the button in the location to be placed.
4. Adding the following code to onCreate method • onClick method creates a new
Button button = (Button) findViewById(R.id.button); instance of MyDialog and calls its
button.setOnClickListener( show method.
new View.OnClickListener() { • The show method needs a
@Override reference to FragmentManager
public void onClick(View v) { class, which we can get with
MyDialog myDialog = new MyDialog(); getSupportFragmentManager
myDialog.show(getSupportFragmentManager(), "123");
method.
• *FragmentManager is a class that
} tracks and controls all Fragment
} instances for an activity.
); • *getSupportFragmentManager: is
uses to support older devices by
extending the AppCompatActivity
class
• We also pass in an identifier: "123".
Using the DialogFragment class
• classes to import for this code:
import android.view.View;
import android.widget.Button;
• Output of the code:
String Resources
• In Android, almost everything is a resource.
• *Defining resources that you can then access in your app is an essential part of Android
development.
• Resources are used for anything from defining colors, images, layouts and string values.
• Everything is defined in resource files and then can be referenced within your application's
code.
• For every piece of text, you want to display within your application (i.e the label of a button, or
the text inside a TextView), you should first define the text in the res/values/strings.xml
file.
• Each entry is a key (representing the id of the text) and a value (the text itself).
• For example, if I want a button to display “Click Me", I might add the following string resource to
res/values/strings.xml:
<resources>
<string name="app_name">My Application</string>
<string name=“buttonText">Click Me</string>
</resources>
• If we reference the string resource for buttonText, the default will be for “Click Me" to be
displayed.
String Resources and Naming Conventions
• Naming conventions: are the conventions or rules used for naming the
variables, methods, and classes in the code.
• When a variable is a member of a class, name of the variable is prefixed with a
lowercase m.
• String Resources: used to avoid hardcoding text in user layouts.
Adapters and Recyclers (Chapter 16)
Objectives
• Looking at the theory of adapters and binding them to our UI
• Implementing the layout with RecyclerView
• Laying out a list item for use in RecyclerView
• Implementing the adapter with RecyclerAdapter
• Binding the adapter to RecyclerView
• Storing notes in ArrayList and displaying them in RecyclerView
Problem with displaying lots of widgets
• A ScrollView elements allows users to scroll through a list of views
that occupy more space than the physical display.
• *ScrollView can be used to populate view such as CardView and
TextView widgets.
• Example: We could create the TextView widgets dynamically in
Java code and then add the TextView widgets to a LinearLayout
contained in a ScrollView. However, this is imperfect.
• Imagine you have a list of 1000 items and you want to show them in a
scrollable list in your application, if you use a ScrollView, it creates
1000 views at once and will keep all of them in memory.
• This approach can cause a memory leak or at least the user won’t
be able to scroll items smoothly.
• Android device might simply run out of memory: handling the
scrolling of a vast number of widgets and their data. ScrollView
Solution to the problem of displaying lots of widgets-RecyclerView
• *The display of elements in a list or grids is a very common pattern in mobile applications.
• The user sees a collection of items and can scroll through them.
• The collection of items can be a list, a grid, an array or another structured representations of data.
• RecyclerView widget makes it easy to efficiently display large sets of data.
• RecyclerView widget is a container for displaying large data sets that can be scrolled very
efficiently by maintaining a limited number of views.
• This improvement is achieved by recycling the views which are out of the visibility of the user.
• For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and
3 would be cleared from the memory to reduce memory consumption.
Solution to the problem of displaying lots of widgets-RecyclerView
1. Add a single widget called RecyclerView to the UI layout.
2. Interact with RecyclerView with a special type of class called
RecyclerAdapter class.
3. Extend and customize RecyclerAdapter class, to control the
data from ArrayList instance and Display it in RecyclerView.
Create a RecyclerView
• To display data in a RecyclerView, you need the following items:
1. Data to display: create the data locally through List, ArrayList, database.
2. RecyclerView: for the scrolling list that contains data.
3. Layout manager It manages the arrangement of data contained within RecyclerView. This
layout manager could be vertical, horizontal, or a grid. You will use a vertical
LinearLayoutManager.
4. Item Layout: Its layout filled with one item of data from ViewHolder.
5. An adapter. Use an extension of RecyclerView.Adapter to connect your data to the
RecyclerView. It prepares the data item and how will be displayed in a ViewHolder. *When the
data changes, the adapter updates the contents of the respective list item view in the
RecyclerView.
6. A ViewHolder. Use an extension of RecyclerView.ViewHolder to contain the information for
displaying one View item using the item's layout.
Activity Adapter Data
RecycleView
LayoutManager ViewHolder Item

Item Layout
Create a List in Android using RecyclerView
• First of all, create a new Android Project in Android Studio and select Empty Activity for
now. Name the project RecycleViewExample.
• Go to activity_main.xml and write the following code in it. Here, we have added a
RecyclerView to the view hierarchy inside LinearLayout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_course"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
</LinearLayout>
Create a List in Android using RecyclerView
• Creating a new class named Course.java.
• Objects of this class will contain the data fields which
we want to store and display in the RecyclerView.
• Now write the following code in the Course.java class.
public class Course {
private String mCourse_name;
private String mCourse_id;
private String mCourse_time; • The Course class has attributes:
public Course(String cid, String cname, String ctime) { mCourse_name ,mCourse_id, mCourse_time
this.mCourse_id = cid; • These attributes represents course id, course name
this.mCourse_time = ctime;
and course time fields of data item.
this.mCourse_name = cname;
} • public Course(String cid, String cname, String
public String getmCourse_name() { ctime) is class constructor.
return mCourse_name; • getmCourse_id(), getmCourse_name() and
}
public String getmCourse_id() { getmCourse_time() are three methods uses to
return mCourse_id; return the value of the attributes.
}
public String getmCourse_time() {
return mCourse_time;
}
}
Create a List in Android using RecyclerView-view
• Now, create a row layout file to contain a view of data item inside the RecyclerView.
• Create a new layout file named row_course.xml and write the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">

<TextView
android:id="@+id/txt_course_name"
android:layout_width="match_parent" view
android:layout_height="wrap_content"
android:text="txt_course_name"
android:textColor="@android:color/black"
android:textSize="22sp" />

<TextView
android:id="@+id/txt_course_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="txt_course_id"
android:textSize="22sp" />

<TextView
android:id="@+id/txt_course_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="txt_course_time"
android:textSize="18sp" />

<TextView
android:id="@+id/border_line"
android:layout_width="398dp"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:background="#808080" />
</LinearLayout>
Create a List in Android using RecyclerView - ViewHolder
• Now, we will create a ViewHolder class.
• ViewHolder is a class which holds the data items that is to be shown in the UI for each view
inside the RecyclerView.
• Create a new
public class class named
CourseViewHolder CourseViewHolder.java and write the following code in it.
extends
RecyclerView.ViewHolder { //1
private TextView mtxtCourseName; //2 1. CourseViewHolder extend the
private TextView mtxtCourseId; RecyclerView.ViewHolder to contain the information for
private TextView mtxtCourseTime; displaying one View item using the item's layout.
public CourseViewHolder(View itemView) { //3
super(itemView); 2. Three local variables for course name, course id, and
mtxtCourseName = course time to reference txt_course_name,
itemView.findViewById(R.id.txt_course_name); txt_course_id and txt_course_time widgets inside of java
mtxtCourseId = class.
itemView.findViewById(R.id.txt_course_id); 3. Class contractor initializes the CourseViewHolder by
mtxtCourseTime =
calling the super of RecyclerView.ViewHolder. Then, it
itemView.findViewById(R.id.txt_course_time);
} make a reference to the three widgets of row_course.xml
public void setCourseName(String courseName) { // 4 layout inside of the class.
this.mtxtCourseName.setText(courseName); 4. setCourseName, setCourseID and setCourseTime
} uses to fill the view of RecyclerView Holder with the data
public void setCourseID(String courseId) { items; course name, course id and course time.
this.mtxtCourseId.setText(courseId);
}
public void setCourseTime(String courseTime) {
this.mtxtCourseTime.setText(courseTime);
}
}
Create a List in Android using RecyclerView - adapter
• *Views and Data sources are different things. They need an interface to communicate with each other.
• Adapter is a just a class which is tasked to act as a bridge between the data item and the view inside of
RecycleView.
• It works as a iterator and picks one data item from the data source and shows it into the View using the
ViewHolder until all the data items are traversed.
• To achieve this, create a new Java class named CourseAdapter.java and write the following
code in it.
public class CourseAdapter extends RecyclerView.Adapter <CourseViewHolder> {
private Context context;
private ArrayList<Course> courseList;
public CourseAdapter(Context context, ArrayList<Course> courseList) { //
contractor
this.context = context;
this.courseList = courseList;
}
}
• *The Adapter class has two members — namely courseList of type ArrayList which will contain
the data that needs to be loaded in the view and context which is the context of the Activity that
uses the adapter object.
*Create a List in Android using RecyclerView - adapter
• After that, you will notice an error in the class header. We need to implement the default
RecyclerView methods, Click in the class header. It will show an option named “Implement
methods”, click on it. Then, you will find 3 methods as “onCreateViewHolder()”,
“onBindViewHolder()” and “getItemCount()” in popup menu. Click OK to auto-generate the required
methods.
Create a List in Android using RecyclerView - adapter
• This process adds the following three methods:
• onCreateViewHolder(): RecyclerView calls this method whenever it needs to create a new
ViewHolder to represent data item. The method creates and initializes the ViewHolder and its
associated View.
• onBindViewHolder(): RecyclerView calls this method to associate a ViewHolder with data item.
The method fetches the appropriate data and uses the data to fill in the view holder's layout.
• getItemCount(): RecyclerView calls this method to returns the total number of items in the data
set held by the adapter. RecyclerView uses this method to determine when there are no more
items that can be displayed. Initially it returns 0.
@Override
public CourseViewHolder onCreateViewHolder( ViewGroup parent, int
viewType) {
return null;
}

@Override
public void onBindViewHolder( CourseViewHolder holder, int
position) {
}

@Override
public int getItemCount() {
return 0;
}
Create a List in Android using RecyclerView - onCreateViewHolder()
• Add the following code inside onCreateViewHolder()
• The onCreateViewHolder() method is similar to the onCreate() method. It inflates the item
row_course layout and returns a ViewHolder with the layout and the adapter.
• LayoutInflater reads a layout XML description and converts it into the corresponding View items.

@Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_course, parent,
false);
return new CourseViewHolder(view);
}
Create a List in Android using RecyclerView - onBindViewHolder()
• Add the following code inside onBindViewHolder()
• The onBindViewHolder() method connects your data to the ViewHolder.
• It associates the data item with the ViewHolder for a given position in the RecyclerView.
• This method is called iteratively for every item in the list, and we need to define here what to do with
our data. In our example, we retrieve the data for RecyclerView position that is to be shown in the UI
for each view inside the RecyclerView using setCourseName, setCourseName and setCourseID
methods.
@Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
Course course = courseList.get(position);
holder.setCourseName(course.getmCourse_name());
holder.setCourseName(course.getmCourse_id());
holder.setCourseID(course.getmCourse_time());
}
Data item onBindViewHol row_course.xml layout
der
Create a List in Android using RecyclerView - getItemCount()
• Add the following code inside getItemCount()
• The getItemCount() returns to number of data items available for displaying in courseList.

@Override
public int getItemCount() {
return courseList.size();
}
Create a List in Android using RecyclerView - MainActivity
• Add the following code inside of MainActivity
• MainActivity class has two members:
• courseList which we want to hold the list of course objects and
• rvCourse which is just an object of RecyclerView type (used to handle operations on RecyclerView).

public class MainActivity extends AppCompatActivity {


private ArrayList<Course> mCourseList;
private RecyclerView rvCourse;

• Then, Add the following code inside of onCreate method

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
generateData();
setData();
}
Create a List in Android using RecyclerView - MainActivity
• Add the following method inside of MainActivity
private void init() {
mCourseList = new ArrayList<>();
rvCourse = findViewById(R.id.rv_course);
}

• This init() method initializes the class members courseList and rvCourse with their a new
ArrayList and RecyclerView respectively.
Create a List in Android using RecyclerView - MainActivity
• Add also the following method inside of MainActivity

private void generateData() {


mCourseList.add(new Course("Mobile Application Development", "IT448", "4:00
PM - 5:00 PM"));
mCourseList.add(new Course("Web Design", "IT404", "5:00 PM - 6:00 PM"));
mCourseList.add(new Course("Computer Organization", "IT233", "6:00 PM - 7:00
PM"));
mCourseList.add(new Course("Business Computer Languages", "IT401", "7:00
PM - 8:00 PM"));
mCourseList.add(new Course("Computer Networks", "IT210", "8:00 PM - 9:00
PM"));
mCourseList.add(new Course("Operating Systems", "IT241", "9:00 PM - 10:00
PM"));
}

• In generateData() method, we added some sample course data to the courseList which we’ll
use in our adapter.
Create a List in Android using RecyclerView - MainActivity
• Add also the following method inside of MainActivity

private void setData() {


rvCourse.setLayoutManager(new LinearLayoutManager(this));
rvCourse.setAdapter(new CourseAdapter(this, mCourseList));
}

• In setData() method, we set a LayoutManager for RecyclerView.


• As we mentioned before, LayoutManager is used in the RecyclerView to position items accordingly.
Specifically, LinearLayoutManager sets items linearly.
• In our example, we used LinearLayoutManager because we want to display list in linearly and this
layout manager has vertical view as default.
• In this method, we set an adapter. Use an extension of RecyclerView.Adapter to connect your data
to the RecyclerView.
Create a List in Android using RecyclerView - MainActivity
• You can now run the app and the result should be something like the screens below.

Scroll
down
Thank
You

You might also like