Android 对listview数据的增删改查

Android listview是常用的数据展示控件。其中对数据的增删改查操作也是常用的功能,比如重新获取了新的数据,或者添加,删除某条记录等等更新都需要对listview的数据进行重新的加载。listview更新数据只需要调用到notifyDataSetChanged()方法,就可以实现对listview数据的更新。如果涉及到线程,则需要在UI的线程更新。

本文针对listview常用的操作进行listview item的数据实行增删改查的操作,主要界面如下。

源码下载:UpdateListView.zip

相关文件下载地址在Linux公社的1号FTP服务器里,下载地址:

FTP地址:ftp://www.linuxidc.com

用户名:

密码:

在 2011年LinuxIDC.com\8月\Android 对listview数据的增删改查

下载方法见这里

图-1 android 实现对listview数据的增删改查主要界面

Android 对listview数据的增删改查

本例只有一个UpdateListViewActivity类,相关的操作以及功能均在一个界面完成。对listview 数据的增删改查,实质就是对填充的数组(填充的数据)进行重新修改后,再次调用notifyDataSetChanged()方法进行更新。尽管如此,对数据使用起来还是比较生疏,下面的例子能加强对listview数据更新的理解。

UpdateListViewActivity.java类是程序的唯一的一个类,实现了对listview增删改查的操作,代码比较多,但理解并不比较复杂。

1.UpdateListViewActivity.java

package com.updatelistview.main;       import java.util.ArrayList;    import java.util.HashMap;       import android.app.Activity;    import android.app.AlertDialog;    import android.content.Context;    import android.content.DialogInterface;    import android.os.Bundle;    import android.view.LayoutInflater;    import android.view.View;    import android.view.View.OnClickListener;    import android.widget.Button;    import android.widget.EditText;    import android.widget.LinearLayout;    import android.widget.ListView;    import android.widget.SimpleAdapter;    import android.widget.Toast;       public class UpdateListViewActivity extends Activity {        // 控件        private Button addBtn;        private Button deleteBtn;        private Button editBtn;        private Button queryBtn;        private ListView listview;        // 数组        private SimpleAdapter listItemAdapter;        private ArrayList<HASHMAP<STRING, Object>> listItem = null;           /** Called when the activity is first created. */       @Override       public void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.main);               // 获取控件            addBtn = (Button) findViewById(R.id.add_id);            deleteBtn = (Button) findViewById(R.id.delete_id);            editBtn = (Button) findViewById(R.id.edit_id);            queryBtn = (Button) findViewById(R.id.query_id);            listview = (ListView) findViewById(R.id.show_result);               // 初始化数据            init();               // 设置控件事件监听            addBtn.setOnClickListener(addClick);            deleteBtn.setOnClickListener(deleteClick);            editBtn.setOnClickListener(editClick);            queryBtn.setOnClickListener(queryClick);           }           // 添加事件响应        OnClickListener addClick = new OnClickListener() {               @Override           public void onClick(View v) {                // TODO Auto-generated method stub                   // 加载输入框的布局文件                LayoutInflater inflater = (LayoutInflater) UpdateListViewActivity.this                       .getSystemService(Context.LAYOUT_INFLATER_SERVICE);                final LinearLayout layout = (LinearLayout) inflater.inflate(                        R.layout.input_add, null);                   // 弹出的对话框                   new AlertDialog.Builder(UpdateListViewActivity.this)                        /* 弹出窗口的最上头文字 */                       .setTitle("添加一条数据")                        /* 设置弹出窗口的图式 */                       .setIcon(android.R.drawable.ic_dialog_info)                        /* 设置弹出窗口的信息 */                       .setMessage("请输入添加的内容")                        .setView(layout)                        .setPositiveButton("确定",                                new DialogInterface.OnClickListener() {                                    public void onClick(                                            DialogInterface dialoginterface, int i) {                                           EditText inputStringr = (EditText) layout                                                .findViewById(R.id.input_add_string);                                           String str = inputStringr.getText()                                                .toString();                                           if (str == null || str.equals("")) {                                               Toast.makeText(getApplicationContext(),                                                    "添加的内容不能为空", Toast.LENGTH_SHORT)                                                    .show();                                        } else {                                            HashMap<STRING, Object> map = new HashMap<STRING, Object>();                                            map.put("viewspot", str);                                            map.put("add", R.drawable.right);                                            listItem.add(0, map);                                            // 如果在前面添加一条数据添加                                            // listItem.add(map);                                            listItemAdapter.notifyDataSetChanged();                                            Toast.makeText(                                                    UpdateListViewActivity.this,                                                    "添加的一条数据为:" + str + "",                                                    Toast.LENGTH_SHORT).show();                                           }                                       }                                })                        .setNegativeButton("取消",                                new DialogInterface.OnClickListener() { /* 设置跳出窗口的返回事件 */                                   public void onClick(                                            DialogInterface dialoginterface, int i) {                                        Toast.makeText(UpdateListViewActivity.this,                                                "取消了删除数据", Toast.LENGTH_SHORT)                                                .show();                                       }                                }).show();               }        };           // 删除事件响应        OnClickListener deleteClick = new OnClickListener() {               @Override           public void onClick(View v) {                // TODO Auto-generated method stub                   /**                * listItem.clear();清空所有数据                *                * */                  /*                * listItem.clear();                * listItemAdapter.notifyDataSetChanged();                */                  // 加载输入框的布局文件                LayoutInflater inflater = (LayoutInflater) UpdateListViewActivity.this                       .getSystemService(Context.LAYOUT_INFLATER_SERVICE);                final LinearLayout layout = (LinearLayout) inflater.inflate(                        R.layout.input_delete, null);                   // 弹出的对话框                   new AlertDialog.Builder(UpdateListViewActivity.this)                        /* 弹出窗口的最上头文字 */                       .setTitle("删除一条数据")                        /* 设置弹出窗口的图式 */                       .setIcon(android.R.drawable.ic_dialog_info)                        /* 设置弹出窗口的信息 */                       .setMessage("请输入删除的索引")                        .setView(layout)                        .setPositiveButton("确定",                                new DialogInterface.OnClickListener() {                                    public void onClick(                                            DialogInterface dialoginterface, int i) {                                           EditText inputNumber = (EditText) layout                                                .findViewById(R.id.input_delete_number);                                           String str = inputNumber.getText()                                                .toString();                                           if (str == null || str.equals("")) {                                               Toast.makeText(getApplicationContext(),                                                    "请输入一个数字", Toast.LENGTH_SHORT)                                                    .show();                                        } else {                                            int number = Integer.valueOf(str);                                               int size = listItem.size();                                               // 判断数字是否超出数组索引范围                                            if (number >= size) {                                                Toast.makeText(                                                        getApplicationContext(),                                                        "没有找到删除的数据索引",                                                        Toast.LENGTH_SHORT).show();                                               } else {                                                   String value = listItem.get(number)                                                        .toString();                                                listItem.remove(number);                                                listItemAdapter                                                        .notifyDataSetChanged();                                                Toast.makeText(                                                        UpdateListViewActivity.this,                                                        "删除的数据为:" + value + "",                                                        Toast.LENGTH_SHORT).show();                                               }                                        }                                       }                                })                        .setNegativeButton("取消",                                new DialogInterface.OnClickListener() { /* 设置跳出窗口的返回事件 */                                   public void onClick(                                            DialogInterface dialoginterface, int i) {                                        Toast.makeText(UpdateListViewActivity.this,                                                "取消了删除数据", Toast.LENGTH_SHORT)                                                .show();                                       }                                }).show();               }        };        // 修改事件响应        OnClickListener editClick = new OnClickListener() {               @Override           public void onClick(View v) {                // TODO Auto-generated method stub                // 加载输入框的布局文件                LayoutInflater inflater = (LayoutInflater) UpdateListViewActivity.this                       .getSystemService(Context.LAYOUT_INFLATER_SERVICE);                final LinearLayout layout = (LinearLayout) inflater.inflate(                        R.layout.input_edit, null);                   // 弹出的对话框                   new AlertDialog.Builder(UpdateListViewActivity.this)                        /* 弹出窗口的最上头文字 */                       .setTitle("修改一条数据")                        /* 设置弹出窗口的图式 */                       .setIcon(android.R.drawable.ic_dialog_info)                        /* 设置弹出窗口的信息 */                       .setMessage("请输入修改的索引及内容")                        .setView(layout)                        .setPositiveButton("确定",                                new DialogInterface.OnClickListener() {                                    public void onClick(                                            DialogInterface dialoginterface, int i) {                                           EditText inputEditNumber = (EditText) layout                                                .findViewById(R.id.input_edit_number);                                           String numberStr = inputEditNumber                                                .getText().toString();                                           EditText inputEditString = (EditText) layout                                                .findViewById(R.id.input_edit_string);                                           String editStr = inputEditString.getText()                                                .toString();                                           if (numberStr == null                                               || numberStr.equals("")) {                                               Toast.makeText(getApplicationContext(),                                                    "请输入要修改的索引", Toast.LENGTH_SHORT)                                                    .show();                                        } else {                                            int number = Integer.valueOf(numberStr);                                               int size = listItem.size();                                               // 判断数字是否超出数组索引范围                                            if (number >= size) {                                                Toast.makeText(                                                        getApplicationContext(),                                                        "没有找到修改的数据索引",                                                        Toast.LENGTH_SHORT).show();                                               } else {                                                   HashMap<STRING, Object> map = new HashMap<STRING, Object>();                                                map.put("viewspot", editStr);                                                map.put("add", R.drawable.right);                                                   listItem.set(number, map);                                                listItemAdapter                                                        .notifyDataSetChanged();                                                   Toast.makeText(                                                        UpdateListViewActivity.this,                                                        "数据修改为:" + editStr + "",                                                        Toast.LENGTH_SHORT).show();                                               }                                        }                                       }                                })                        .setNegativeButton("取消",                                new DialogInterface.OnClickListener() { /* 设置跳出窗口的返回事件 */                                   public void onClick(                                            DialogInterface dialoginterface, int i) {                                        Toast.makeText(UpdateListViewActivity.this,                                                "取消了修改数据", Toast.LENGTH_SHORT)                                                .show();                                       }                                }).show();               }        };           // 查询事件响应        OnClickListener queryClick = new OnClickListener() {               @Override           public void onClick(View v) {                // TODO Auto-generated method stub                // 查询数据                listItemAdapter.notifyDataSetChanged();            }        };           // 初始化数据        private void init() {               listItem = new ArrayList<HASHMAP<STRING, Object>>();            for (int i = 0; i < 12; i++) {                HashMap<STRING, Object> map = new HashMap<STRING, Object>();                map.put("viewspot""北京故宫,颐和园" + i);                map.put("add", R.drawable.right);                listItem.add(map);            }            listItemAdapter = new SimpleAdapter(getApplicationContext(), listItem,// 数据源                    R.layout.items, new String[] { "viewspot""add" }, new int[] {                            R.id.viewspot, R.id.add });            listview.setAdapter(listItemAdapter);           }       }  

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwgxdp.html