How to use list in android

Using lists in Android wth ListView — Tutorial

This tutorial describes how to use ListView together with activities and fragments in Android.

1. Using lists in Android

The display of elements in a list is a very common pattern in mobile applications. The user sees a list of items and can scroll through them. Such an activity is depicted in the following picture.

Typically the user interacts with the list via the toolbar, for example, via a button which refreshes the list. Individual list items can be selected. This selection can update the toolbar or can trigger a detailed screen for the selection. The following graphic sketches that. On the selection of a list item another activity is started.

2. Android and the ListView widget

2.1. Views for handling lists

Android provides the ListView and the ExpandableListView classes which are capable of displaying a scrollable list of items. The ExpandableListView class supports a grouping of items.

2.2. Possible input types for lists

The input of a list (items in the list) can be arbitrary Java objects. The adapter extracts the correct data from the data object and assigns this data to the views in the row of the ListView .

These items are typically called the data model of the list. An adapter can receive data as input.

2.3. Adapters

An adapter manages the data model and adapts it to the individual entries in the widget. An adapter extends the BaseAdapter class.

Every line in the widget displaying the data consists of a layout which can be as complex as you want. A typical line in a list has an image on the left side and two text lines in the middle as depicted in the following graphic.

A layout file for such a line might look like the following.

The adapter would inflate the layout for each row in its getView() method and assign the data to the individual views in the row.

The adapter is assigned to the ListView via the setAdapter method on the ListView object.

Adapters are not only used by ListView , but also by other views which extend AdapterView as, for example, Spinner , GridView , Gallery and StackView .

2.4. Filtering and sorting

The filtering and sorting of the data is handled by the adapter. You need to implement the logic in your custom adapter implementation.

2.5. Data updates in the adapter

The notifyDataSetChanged() method on the adapter is called if the data has changed or if new data is available.

The notifyDataSetInvalidated() method is called if the data is not available anymore.

2.6. Listener

To react to selections in the list, set an OnItemClickListener to your ListView .

3. Default adapter

3.1. Default platform adapter

Android provides default adapter implementations; the most important are ArrayAdapter and CursorAdapter . ArrayAdapter can handle data based on Arrays or java.util.List . SimpleCursorAdapter can handle database related data.

3.2. Using ArrayAdapter

The ArrayAdapter class can handle a list or arrays of Java objects as input. Every Java object is mapped to one row. By default, it maps the toString() method of the object to a view in the row layout.

You can define the ID of the view in the constructor of the ArrayAdapter otherwise the android.R.id.text1 ID is used as default.

The ArrayAdapter class allows to remove all elements in its underlying data structure with the clear() method call. You can then add new elements via the add() method or a Collection via the addAll() method.

You can also directly modify the underlying data structure and call the notifyDataSetChanged() method on the adapter to notify it about the changes in data.

If you want to change the data in your adapter, the underlying data structure must support this operation. This is, for example, the case for the ArrayList class, but not for arrays.
Читайте также:  Android textview get height

3.3. ListView example with ArrayAdapter

The following listing shows a layout file called activity_listviewexampleactivity.xml which includes a ListView .

The following example shows the usage of the ListView view in an activity. It uses a default layout from the Android platform for the row layout. It also demonstrates the removal of list items and uses animations for the removal.

4. Custom adapter implementations

4.1. Developing a custom adapter

The ArrayAdapter is limited as it supports only the mapping of toString() to one view in the row layout. To control the data assignment and to support several views, you have to create your custom adapter implementation.

For this you would extend an existing adapter implementation or subclass the BaseAdapter class directly.

Frequently you extend ArrayAdapter to write a custom adapter, as this is simpler than extending BaseAdapter directly.

4.2. Preparing a row for the list

The adapter needs to create a layout for each row of the list. The ListView instance calls the getView() method on the adapter for each data element. In this method the adapter creates the row layout and maps the data to the views in the layout.

This root of the layout is typically a ViewGroup (layout manager) and contains several other views, e.g., an ImageView and a TextView . The following graphic shows a list with different layouts for odd and even rows.

Within the getView() method you would inflate an XML based layout and then set the content of the individual views based on the Java object for this row. To inflate the XML layout file, you can use the LayoutInflator system service.

This layout inflator service can get accessed via the getLayoutInflator() method of the activity or via the context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) method call.

After the adapter inflated the layout, it searches for the relevant views in the layout and fills them with the data. The individual elements in the layout can be found via the findViewById() method call on the top level view.

4.3. Example for a custom adapter

The following code shows an implementation of a custom adapter. This adapter assumes that you have two png files (no.png and ok.png) in one of your directory]]res/drawable folders. The coding inflates an XML layout file, finds the relevant views in the layout and sets their content based on the input data.

4.4. Updating the data model from the adapter

The row can also contain views which interact with the underlying data model via the adapter. For example, you can have a Checkbox in your row layout and if the Checkbox is selected, the underlying data is changed.

5. ListActivity and ListFragment

5.1. Default container for using ListView

Android provides specialized fragment and activity classes to simplify list handling.

The classes are the ListActivity class, if you want to use lists in activities, and the ListFragment class, if you want to use lists in fragments.

You do not have to assign a layout to these elements. If you do not define a layout, the activity or fragment contains a single ListView by default. ListActivity and ListFragment also allow you to override a onListItemClick() method for handling selection of list items.

Both classes allow you to set the adapter to the default ListView via the setListAdapter() method.

The following example code shows a simple ListFragment implementation.

The next example code demonstrates the usage of a ListActivity .

5.2. ListActivity and custom layout

You can use a custom layout with ListActivity or ListFragment . In this case the fragment or activity searches in the provided layout for a ListView with the predefined android:id attribute set to @android:id/list . This usage is demonstrated by the following code snippet.

If you do not use this ID or do not include a ListView into your layout, the application crashes once you try to display the activity or the fragment.

5.3. Placeholder for an empty list

You can also use a view with the @android:id/empty ID in your layout. The corresponding activity and fragment shows this view automatically if the ListView is empty and hides it otherwise. For example, you could display an error message in such a view.

6. Exercise: Using ListView and ListActivity

The following exercise demonstrates how to use a ListView in an ListActivity . You use the predefined ArrayAdapter class and an existing Android layout for the rows.

Create a new Android project called de.vogella.android.listactivity with the activity called MyListActivity .

Change MyListActivity class based on the following code example. Note that the setContentView() method is not used.

7. Exercise: ListActivity with custom layout

In our example your will define your layout for the rows and use it in your adapter.

Create the rowlayout.xml layout file in the directory]]res/layout folder of the de.vogella.android.listactivity project.

Change your activity so that it uses the new layout.

8. Tutorial: Implementing your customer adapter

The following uses two images «no.png» and «ok.png». I placed them in the «res/drawable-mdpi» folder. You must create your own icons. In case you do not find any icons just copy «icon.png» and use a drawing program to change it a little bit and create a second one.

Читайте также:  Уровень строительный лазерный для андроид

Create the class MySimpleArrayAdapter which will serve as our adapter.

To use this adapter, change the activity to the following.

If you run this example you should get a list with different icons for the certain elements.

9. ListViews and performance

9.1. Motivation

Performance is especially important on Android as users expect fast reaction times. Compared to desktop computers an Android device is relatively slow from the hardware perspective.

This part describes how to reduce these operations to implement your custom list adapter efficiently. The default Android adapters like ArrayAdapter are already performance optimized.

9.2. Time consuming operations

Every view which gets inflated from an XML layout file will result in a Java object. Inflating layouts and creating Java objects are expensive with regards to time and memory consumption.

In addition using the findViewById() method is relatively time consuming, even though it is not as bad as XML inflating.

9.3. Avoiding layout inflation and object creation

A ListView typically contains more data than the number of displayed rows. If the user scrolls the list, then the rows and their associated views will be scrolled out of the visible area. The Java objects which represent the rows can be reused for newly visible rows.

If Android determines that a row is not visible anymore, it allows the getView() of the adapter method to reuse the associated view via the convertView parameter.

The adapter can assign new data to the views contained in the view hierarchy of the convertView . This avoids inflating an XML file and creating new Java objects.

In case Android cannot reuse a row, the Android system passes null to the convertView parameter. Therefore the adapter implementation needs to check for this.

9.4. View holder pattern

A ViewHolder implementation allows to avoid the findViewById() method in an adapter.

A ViewHolder class is typically a static inner class in your adapter which holds references to the relevant views in your layout. This reference is assigned to the row view as a tag via the setTag() method.

If we receive a convertView object, we can get the instance of the ViewHolder via the getTag() method and assign the new attributes to the views via the ViewHolder reference.

While this sounds complex this is approximately 15 % faster than using the findViewById() method.

9.5. Example

The following code shows a performance optimized adapter implementation which reuses existing views and implements the holder pattern.

10. Storing the selection of a view

By default a ListView has no selection mode active. You can activate it via the setChoiceMode() method call. Pass ListView.CHOICE_MODE_MULTIPLE for multiple selections or ListView.CHOICE_MODE_SINGLE for single selections to this method.

To get the selected items of a ListView , use the getCheckedItemPosition() for a single selection method or listView.getCheckedItemPositions() for multiple selections. If you have stable ID, you could also use the getCheckedItemIds() method to get the selected IDs.

Android already provides a default layout for this: the android.R.layout.simple_list_item_multiple_choice layout which contains a configured CheckedTextView view.

The following activities demonstrate how to use these selection modes. If you use these modes, the ListView stores the selected values. It is not persisted in your data model.

Источник

How to Create Dynamic ListView in Android using Firebase Firestore?

ListView is one of the most used UI components in Android which you can find across various apps. So we have seen listview in many different apps. In the previous article, we have seen implementing ListView in Android using Firebase Realtime Database. Now in this article, we will take a look at the implementation of ListView using Firebase Firestore in Android. Now, let’s move towards the implementation of this project.

What we are going to build in this project?

We will be building a simple ListView application in which we will be displaying a list of courses along with images in our ListView. We will fetch all the data inside our ListView from Firebase Firestore. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.

Step by Step Implementation

Step 1: Create a new Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Connect your app to Firebase

After creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.

Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen.

Читайте также:  Отследить андроид по гугл аккаунту

After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.

After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App.

Step 3: Working with the AndroidManifest.xml file

For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it.

Step 4: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

Step 5: Now we will create a new Java class for storing our data

For reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app’s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it.

Step 6: Create a layout file for our item of ListView

Navigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_lv_item and add the below code to it.

Step 7: Now create an Adapter class for our ListView

For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it and Click on New > Java class and name your java class as CoursesLVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.

Step 8: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

After adding the above code add the data to Firebase Firestore in Android.

Step 9: Adding the data to Firebase Firestore in Android

Search for Firebase in your browser and go to that website and you will get to see the below screen.

After clicking on Go to Console option. Click on your project which is shown below.

After clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen.

After clicking on the Create Database option you will get to see the below screen.

Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen.

Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console.

You have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for “name” and one filed for “imgUrl” and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added.

Similarly, add more images by clicking on the “Add document” button.

After adding these images run your app and you will get to see the output on the below screen.

Источник

Оцените статью