public class MainActivity extends Activity { private ListView listview; private MySQLiteDatabaseUtils dbUtils;// 数据库连接工具类 private TextView empty; private Cursor cursor; private SimpleAdapter adapter; private SimpleCursorAdapter cursorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listview = (ListView) this.findViewById(R.id.listview); empty = (TextView) this.findViewById(R.id.empty); dbUtils = new MySQLiteDatabaseUtils();// 创建连接数据库对象 listview.setEmptyView(empty); registerForContextMenu(listview); reloadSqlDataListView(); } public void reloadSqlDataListView() { // 第一种用SimpleAdapter String sql = "select * from studentinfo order by sid desc"; List<Map<String, String>> data = dbUtils.selectList(sql, null); adapter = new SimpleAdapter(this, data, R.layout.listview_item, new String[] { "sname", "sex", "score" }, new int[] { R.id.name, R.id.sex, R.id.score }); listview.setAdapter(adapter); // 第二种:用SimpleCursorAdapter // 用SimpleCursorAdapter查询语句的主键必须写成如下,相当于 sid as _id,不写as就用空格代替 // 这样写会报如下错误:String sql = "select * from studentinfo"; // Caused by: java.lang.IllegalArgumentException: column '_id' does not // exist // String sql = // "select sid _id,sname,sex,score from studentinfo order by sid desc"; // cursor = dbUtils.selectCursor(sql, null); // cursorAdapter = new SimpleCursorAdapter(this, R.layout.listview_item, // cursor, new String[] { "sname", "sex", "score" }, new int[] { // R.id.name, R.id.sex, R.id.score }, // CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); // // OBSERVER观察者,数据有更新时会自动去更新 // listview.setAdapter(cursorAdapter); // loader数据加载器 } // 利用上下文菜单,更新、查找、删除。点中LsitView每个弹出上下文菜单,注意先注册LsitView @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; // 将选中的该位置的姓名显示在标题上 Map<String, String> mapitem = (Map<String, String>) adapter .getItem(info.position); menu.setHeaderTitle(mapitem.get("sname")); getMenuInflater().inflate(R.menu.contextmenu_listview_main, menu); } // 上下文菜单监听 @Override public boolean onContextItemSelected(MenuItem item) { // 获取当前记录的ID因为更新删除等都有用到 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Map<String, String> itemMap = (Map<String, String>) adapter .getItem(info.position); // 看情况是否要转数据类型:final int sid = Integer.parseInt(itemMap.get("sid")); final String sid = itemMap.get("sid"); switch (item.getItemId()) { case R.id.action_delete: AlertDialog.Builder builder = createDialogBuilder( R.drawable.ic_launcher, "删除提示:"); builder.setMessage("确认要删除吗?"); builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String sql = "delete from studentinfo where sid=?"; boolean flag = dbUtils.executeData(sql, new Object[] { sid }); if (flag) { Toast.makeText(MainActivity.this, "删除成功!", 100).show(); reloadSqlDataListView();// 删除完更新数据 } else { Toast.makeText(MainActivity.this, "删除失败!", 100).show(); } } }); builder.show(); break; case R.id.action_update: AlertDialog.Builder builder2 = createDialogBuilder( R.drawable.ic_launcher, "更新数据"); View view = getLayoutInflater().inflate(R.layout.dialog_insert, null); final EditText edit_name = (EditText) view .findViewById(R.id.editText_dialog_name); final EditText edit_sex = (EditText) view .findViewById(R.id.editText_dialog_sex); final EditText edit_score = (EditText) view .findViewById(R.id.editText_dialog_score); // 将布局给对话框 builder2.setView(view); // 修改数据首先要查询出数据,根据sid来查找数据,只查找一条所以用游标的那个来查询 String sql = "select*from studentinfo where sid=?"; Cursor cursor2 = dbUtils.selectCursor(sql, new String[] { sid }); cursor2.moveToFirst();// 游标一定要移动 Log.i("MainActivity", "cursor2.getColumnCount" + cursor2.getColumnCount()); edit_name .setText(cursor2.getString(cursor2.getColumnIndex("sname"))); edit_sex.setText(cursor2.getString(cursor2.getColumnIndex("sex"))); edit_score.setText(cursor2.getString(cursor2 .getColumnIndex("score"))); cursor2.close(); // 设置一确定按钮给它,到用来确定修改数据 builder2.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String sname = edit_name.getText().toString(); String sex = edit_sex.getText().toString(); String score = edit_score.getText().toString(); String sql = "update studentinfo set sname=?,sex=?,score=? where sid=?"; boolean flag = dbUtils.executeData(sql, new Object[] { sname, sex, score, sid }); if (flag) { Toast.makeText(MainActivity.this, "更新数据成功!", 100) .show(); reloadSqlDataListView();// 完更新数据 } else { Toast.makeText(MainActivity.this, "更新数据添加失败!", 100) .show(); } } }); builder2.show(); break; case R.id.action_none: break; } return super.onContextItemSelected(item); } // 添加数据用的是OptionMenu,即按菜单键添加 @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } // 点中菜单后添加数据的监听事件 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_insert: // 创建自定义对话框 AlertDialog.Builder builder = createDialogBuilder( R.drawable.ic_launcher, "添加数据!"); // 生成对话框的一个自定义布局,返回View,因为还要查找里面的控件 View view = getLayoutInflater().inflate(R.layout.dialog_insert, null); final EditText edit_name = (EditText) view .findViewById(R.id.editText_dialog_name); final EditText edit_sex = (EditText) view .findViewById(R.id.editText_dialog_sex); final EditText edit_score = (EditText) view .findViewById(R.id.editText_dialog_score); // 将布局给对话框 builder.setView(view); // 设置一确定按钮给它,到用来添加数据 builder.setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String sname = edit_name.getText().toString(); String sex = edit_sex.getText().toString(); String score = edit_score.getText().toString(); String sql = "insert into studentinfo(sname,sex,score)values(?,?,?)"; boolean flag = dbUtils.executeData(sql, new Object[] { sname, sex, score }); if (flag) { Toast.makeText(MainActivity.this, "添加成功!", 100).show(); reloadSqlDataListView();// 添加完更新数据 } else { Toast.makeText(MainActivity.this, "添加失败!", 100).show(); } } }); // 显示对话框 builder.show(); break; } return super.onOptionsItemSelected(item); } public Builder createDialogBuilder(int icLauncher, String title) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setIcon(icLauncher); builder.setNegativeButton("取消", null); return builder; } @Override protected void onDestroy() { super.onDestroy(); cursor.close(); dbUtils.destroy(); } } //主程序中用到的数据库操作类 public class MySQLiteDatabaseUtils { private static final String dbPtah = Environment .getExternalStorageDirectory() + File.separator + "student.db"; private SQLiteDatabase db; /** * 建立数据库连接的构造方法 */ public MySQLiteDatabaseUtils() { db = SQLiteDatabase.openDatabase(dbPtah, null, SQLiteDatabase.OPEN_READWRITE); } /** * 查询方法一:返回的是游标 * * @param sql * @param selectionArgs * @return */ public Cursor selectCursor(String sql, String[] selectionArgs) { Cursor cursor = db.rawQuery(sql, selectionArgs); return cursor; } /** * 查询方法二:返回的是lsit集合 * * @param sql * @param selectionArgs * @return */ public List<Map<String, String>> selectList(String sql, String[] selectionArgs) { Cursor cursor = db.rawQuery(sql, selectionArgs); return cursorToList(cursor); } /** * 封装游标数据到List * * @param cursor * @return */ public List<Map<String, String>> cursorToList(Cursor cursor) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); while (cursor.moveToNext()) {// 循环的是每一行数据 Map<String, String> map = new HashMap<String, String>(); for (int i = 0; i < cursor.getColumnCount(); i++) {// 这个循环的是每一行的列数 map.put(cursor.getColumnName(i), cursor.getString(i));// 键:key:存储每一行的字段,value:值就是内容 } list.add(map); } cursor.close(); return list; } /** * 增删查的方法 * * @param sql * @param bindArgs * :是 sql语句中要绑定(占位符)的参数值 * @return */ public boolean executeData(String sql, Object[] bindArgs) { try { if (bindArgs == null) { db.execSQL(sql); } else { db.execSQL(sql, bindArgs); } return true; } catch (SQLException e) { e.printStackTrace(); Log.i("MainActivity", "数据错误!!"); return false; } } // 关闭时销毁db public void destroy() { if (db != null) { db.close(); } } } //主布局 <RelativeLayout 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="${relativePackage}.${activityClass}" > <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/listview" android:text="没有数据!" /> </RelativeLayout> //自定义适配器ListView的布局 <TextView android:id="@+id/name" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" /> <TextView android:id="@+id/sex" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" /> <TextView android:id="@+id/score" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp" /> //修改添加数据的三个输入框 <EditText android:id="@+id/editText_dialog_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入姓名" > </EditText> <EditText android:id="@+id/editText_dialog_sex" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入性别" /> <EditText android:id="@+id/editText_dialog_score" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入分数" /> //上写文菜单分别是:删除、修改、不操作 //选项菜单:添加