Easy Tutorial
❮ Hadoop Skills Android Tutorial Wallpapermanager ❯

2.4.4 Adapter Basics Lecture

Classification Android Basic Tutorial

Introduction to This Section

>

Starting from this section, the UI controls we are going to talk about are all related to Adapters. It is important to understand and learn to use this Adapter. The Adapter is an intermediate bridge that helps to fill in the data. In simple terms: it displays various data in an appropriate form on the view for users to see!


1. Simple Understanding of the MVC Pattern

>

Before starting to learn about Adapters, let's understand the concept of the MVC pattern: For example, large-scale commercial programs are usually developed by multiple people. Some are responsible for planning and designing the operation interface, while others are responsible for writing the program code. If the division of labor in the program project can be achieved, it is necessary to make suitable arrangements in the structure of the program. If the interface design and modification involve changes to the program code, then the division of labor between the two will cause difficulties in execution. A good program architect divides the entire program project into the three parts shown in the figure:

Relationship Diagram Analysis:

>

-Model : It can usually be understood as data, responsible for executing the core calculations and judgment logic of the program. It obtains data input by the user through the view, then queries relevant information from the database, performs calculations and judgments, and finally hands the results over to the view for display.

-View : The user's operation interface, in other words, it is the GUI. What kind of interface components to use, the arrangement and order of the components need to be designed.

-Controller : The controller, as a hub between the model and the view, is responsible for controlling the execution process of the program and the interaction between objects.

And this Adapter is the middle part of the Controller: Model (data) ---> Controller (how to display it) ---> View (user interface) This is a simple understanding of the simple MVC components!


2. Adapter Concept Analysis

Official Documentation: Adapter

First, let's take a look at its inheritance structure diagram:

That's the Adapter and its inheritance structure diagram. Next, let's introduce a few more Adapters that are actually used in development!

>

-BaseAdapter : An abstract class, in actual development, we will inherit this class and override the relevant methods. It is the most commonly used Adapter!

-ArrayAdapter : Supports generic operations, the simplest Adapter, can only display a line of text~

-SimpleAdapter : Also has good scalability, can customize various effects!

-SimpleCursorAdapter : Used to display a simple text type listView, usually used in databases, but a bit outdated, not recommended!

In fact, a BaseAdapter is enough to play with. As for the others, they are not used much in actual development, and we will explain them later when needed~


3. Code Examples:

Well, too much talk is not as good as writing code. Next, let's write a few simple Adapter examples to help us understand the convenience that Adapter brings to us. In addition, because the Adapter needs to be combined with ListView, GridView and other controls for explanation, some advanced usage will be discussed in the ListView section! Here, we will simply demonstrate the effect. In addition, the control used here is ListView, which will be explained in the next section. It doesn't matter if you don't understand it now!


1) ArrayAdapter Usage Example:

Running Effect Picture:

Code Implementation:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Data to be displayed
        String[] strs = {"Ji Shen", "B Shen", "Xiang Shen", "Cao Shen", "J Shen"};
        //Create ArrayAdapter
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this,android.R.layout.simple_expandable_list_item_1,strs);
        //Get the ListView object, set the Adapter for ListView by calling the setAdapter method
        ListView list_test = (ListView) findViewById(R.id.list_test);
        list_test.setAdapter(adapter);
    }
}

Some related things:

1. In addition to using arrays, we can also write them into an array resource file:

For example: Create an array resource XML file in res\values: arrays.xml:

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    &lt;string-array name="myarray">  
    <item>Chinese&lt;/item
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    List&lt;Map&lt;String, Object>> listitem = new ArrayList&lt;Map&lt;String, Object>>();
    for (int i = 0; i < names.length; i++) {
        Map&lt;String, Object> showitem = new HashMap&lt;String, Object>();
        showitem.put("touxiang", imgIds[i]);
        showitem.put("name", names[i]);
        showitem.put("says", says[i]);
        listitem.add(showitem);
    }

    // Create a SimpleAdapter
    SimpleAdapter myAdapter = new SimpleAdapter(getApplicationContext(), listitem, R.layout.list_item, new String[]{"touxiang", "name", "says"}, new int[]{R.id.imgtou, R.id.name, R.id.says});
    ListView listView = (ListView) findViewById(R.id.list_test);
    listView.setAdapter(myAdapter);
}

Alright, that's a simple usage of SimpleAdapter, quite interesting~


3) Example of SimpleCursorAdapter usage:

Although this is outdated, it's quite convenient for beginners who are not very familiar with SQLite! Remember the example of reading contacts we learned from ContentProvider before? Before, we displayed it through printing Log, now we display it on ListView with this SimpleCursorAdapter!

Implementation effect :

Code implementation :

First, write the layout for each item of listView:

list_item.xml :

<?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="match_parent"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/list_name"
        android:layout_width="0dp"
        android:layout_height="64dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Piggy"
        android:textColor="#0000FF"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/list_phone"
        android:layout_width="0dp"
        android:layout_height="64dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="13798989898"
        android:textColor="#EA5C4D"
        android:textSize="18sp" />

</LinearLayout>

Then the layout of activity_main is the same as before, it's just a simple ListView, and then

MainActivity.java :

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView list_test = (ListView) findViewById(R.id.list_test);
        // Read contacts
        Cursor cursor = getContentResolver()
                .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        SimpleCursorAdapter spcAdapter = new SimpleCursorAdapter(this,R.layout.list_item,cursor,
                new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER},
                new int[]{R.id.list_name,R.id.list_phone});
        list_test.setAdapter(spcAdapter);
    }
}

Finally, add a contact reading permission in AndroidManifest.xml!

&lt;uses-permission android:name="android.permission.READ_CONTACTS"/>

Q&A:

>

Q : Is it that simple? — A : Yes, directly get the Cursor, and then bind it, no need for you to write any SQL statements yourself! Q : You said this is outdated, so what can replace it? — A : The general practice is to override BaseAdapter yourself, after obtaining the data collection, bind it to the corresponding control! Q : Are there any precautions with this SimpleCursorAdapter? — A : Yes, when using SimpleCursorAdapter, the bound database table must have the id field, or as *id; and the data retrieved during binding must include this *id item, otherwise the following error will occur! java.lang.IllegalArgumentException: column ' id' does not exist


Summary of this section:

>

Alright, that's the basic explanation of Adapter, of course, the three Adapters we explained here, we actually... basically don't use in development, haha, except for SimpleAdapter which might be used occasionally, we usually override BaseAdapter!

❮ Hadoop Skills Android Tutorial Wallpapermanager ❯