Lesson 51. SimpleAdapter, Adding and Deleting Records


In this lesson:

– we use SimpleAdapter to build the list
– add and delete entries in the list

How to Display Data Using SimpleAdapter we know. Now let’s try to change this data. Let’s make a list with an opportunity removal and addition records. We will add a button and delete it using the context menu.

Let’s create a project:

Project name: P0511_SimpleAdapterData
Build Target: Android 2.3.3
Application name: SimpleAdapterData
Package name: ru.startandroid.develop.p0511simpleadapterdata
Create Activity: MainActivity

screen main.xml:



    
    
    

Add button and list. It is interesting to note the property onClick buttons. Then it will become clear that it is.

Layout for a list item item.xml:



    
    
    
    

Picture and text.

code MainActivity.java:

package ru.startandroid.develop.p0511simpleadapterdata;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

  private static final int CM_DELETE_ID = 1;

  // имена атрибутов для Map
  final String ATTRIBUTE_NAME_TEXT = "text";
  final String ATTRIBUTE_NAME_IMAGE = "image";

  ListView lvSimple;
  SimpleAdapter sAdapter;
  ArrayList> data;
  Map m;

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // упаковываем данные в понятную для адаптера структуру
    data = new ArrayList>();
    for (int i = 1; i < 5; i++) {
      m = new HashMap();
      m.put(ATTRIBUTE_NAME_TEXT, "sometext " + i);
      m.put(ATTRIBUTE_NAME_IMAGE, R.drawable.ic_launcher);
      data.add(m);
    }

    // массив имен атрибутов, из которых будут читаться данные
    String[] from = { ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_IMAGE };
    // массив ID View-компонентов, в которые будут вставлять данные
    int[] to = { R.id.tvText, R.id.ivImg };

    // создаем адаптер
    sAdapter = new SimpleAdapter(this, data, R.layout.item, from, to);

    // определяем список и присваиваем ему адаптер
    lvSimple = (ListView) findViewById(R.id.lvSimple);
    lvSimple.setAdapter(sAdapter);
    registerForContextMenu(lvSimple);
  }

  public void onButtonClick(View v) {
    // создаем новый Map
    m = new HashMap();
    m.put(ATTRIBUTE_NAME_TEXT, "sometext " + (data.size() + 1));
    m.put(ATTRIBUTE_NAME_IMAGE, R.drawable.ic_launcher);
    // добавляем его в коллекцию
    data.add(m);
    // уведомляем, что данные изменились
    sAdapter.notifyDataSetChanged();
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(0, CM_DELETE_ID, 0, "Удалить запись");
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    if (item.getItemId() == CM_DELETE_ID) {
      // получаем инфу о пункте списка
      AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) item.getMenuInfo();
      // удаляем Map из коллекции, используя позицию пункта в списке
      data.remove(acmi.position);
      // уведомляем, что данные изменились
      sAdapter.notifyDataSetChanged();
      return true;
    }
    return super.onContextItemSelected(item);
  }
}

In the method onCreate we create a collection of Map objects, arrays of mappings, create an adapter and a list, add the possibility of a context menu for the list.

method onButtonClick – we specified it in main.xml in the property onClick buttons. And now when you press the button, this method is executed. No separate click handler is required.

In this method, we create a new Map, add it to the data collection and announce that the data has changed and we need to update the list.

method onCreateContextMenu – creating a context menu. Let’s create only one item – to delete a record.

IN onContextItemSelected click on the shortcut menu. When the context menu is called, the object it was called for sends information about itself to the menu. We use getMenuInfo method to get information on a list item for which the context menu was called. The AdapterContextMenuInfo object contains View, id, and list item information. We use the item to remove the corresponding Map from the collection. We then report that the data has changed.

We’ll save everything and run it.

The screen shows a shortcut menu that is displayed when you long-press a list item. It shows a list and a button for adding records.

Entries are added and deleted. I did not start editing. The principle is the same there. Do you get a Map and change its attributes.

The code shows that to update the list it is necessary to change the data used by the adapter and call its method-message.

In the next lesson:

– we use SimpleCursorAdapter to build the list
– add and delete entries in the list




Discuss in the forum [89 replies]

Leave a Comment