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="輸入分數" /> //上寫文菜單分別是:刪除、修改、不操做 //選項菜單:添加