1.首先看一下界面效果和功能
长按选中item会弹出删除和修改选项,删除就会删掉选中的item
2.实现思路
3.具体实现
package android.jim.com.dbstorage; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.sqliteDatabase; /** * Created by huangjim on 7/22/2015. */ public class DBStorageDemo { private Context mContext; private sqliteDatabase msqliteDatabase; //public final String DATABASE_NAME="userInfo"; public final static String TABLE_NAME="users2"; public final static String USER_NAME="userName"; public final static String USER_ADDRESS = "userAddress"; public DBStorageDemo(Context _Context){ this.mContext=_Context; } //创建和打开数据库 public void openOrCreateDatabase(){ MyDatabaSEOpenHelper openHelper=new MyDatabaSEOpenHelper(mContext,TABLE_NAME,null,1); msqliteDatabase=openHelper.getReadableDatabase(); } //关闭数据库 public void closeUser(){ msqliteDatabase.close(); //msqliteDatabase=null; } //添加用户 public long insertUser(Users users){ if (msqliteDatabase!=null&&users!=null) { ContentValues _ContentValues = new ContentValues(); _ContentValues.put(USER_NAME,users.getUserName()); _ContentValues.put(USER_ADDRESS,users.getUserAddress()); return msqliteDatabase.insert(TABLE_NAME,"",_ContentValues); } /* msqliteDatabase.execsql("insert into TABLE_NAME values(null,?.?)",new String[]{users.getUserName(),users.getUserAddress()});*/ return -1; } //返回整个表的游标 public Cursor selectAll(){ //return msqliteDatabase.rawQuery("select * from TABLE_NAME",null); if (msqliteDatabase!=null) { return msqliteDatabase.query(TABLE_NAME,new String[]{"_id",USER_NAME,USER_ADDRESS},null); }else { return null; } } //查询用户用 public Cursor selectUser( String selection,String[] selectionArgs,String groupBy,String having,String orderBy){ if (msqliteDatabase!=null) { return msqliteDatabase.query(TABLE_NAME,new String[]{USER_NAME,selection,selectionArgs,groupBy,having,orderBy); }else { return null; } } //删除用户 public void deleteUser(int itemId){ if (msqliteDatabase!=null) { msqliteDatabase.execsql("delete from "+ TABLE_NAME +" where _id= "+ Integer.toString(itemId)); //closeUser(); //msqliteDatabase.delete(TABLE_NAME,"_id =?",new String[]{String.valueOf(itemId)}); } } //更新用户信息 public void updateUser(int itemId,Users users){ if (msqliteDatabase!=null){ //msqliteDatabase.execsql("update "+TABLE_NAME+" set userName= "+users.getUserName()+" set userAddress= "+users.getUserAddress()+" where _id= "+ Integer.toString(itemId)); ContentValues contentValues=new ContentValues(); contentValues.put(USER_NAME,users.getUserName()); contentValues.put(USER_ADDRESS,users.getUserAddress()); msqliteDatabase.update(TABLE_NAME,contentValues,"_id=?",new String[]{Integer.toString(itemId)}); } } }
其中在openOrCreateDatabase中调用了sqliteOpenHelper类来初始化数据库,这个类的实现非常简单
package android.jim.com.dbstorage; import android.content.Context; import android.database.sqlite.sqliteDatabase; import android.database.sqlite.sqliteOpenHelper; /** * Created by huangjim on 7/22/2015. */ public class MyDatabaSEOpenHelper extends sqliteOpenHelper { public MyDatabaSEOpenHelper(Context context,String name,sqliteDatabase.CursorFactory factory,int version) { super(context,name,factory,version); } @Override public void onCreate(sqliteDatabase db) { db.execsql("create table " + DBStorageDemo.TABLE_NAME + "(_id integer primary key autoincrement," + DBStorageDemo.USER_NAME + " varchar(50)," + DBStorageDemo.USER_ADDRESS + " varchar(250))"); } @Override public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) { } }
这里直接继承了ListActivity,其中长按删除和编辑用到的方法是根据当前item的id找到对应数据在数据库里的_id,然后删除数据库里的内容,再把数据库的内容显示出来。
package android.jim.com.dbstorage; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.DialogInterface; import android.database.Cursor; import android.os.Bundle; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends ListActivity { private DBStorageDemo dbStorageDemo; //private Users users; private final int USERDIALOG_ID = 2345; private final int ITEM_MODIFY = 1; private final int ITEM_DELETE = 2; private final int ITEM_ADD = 3; private final int ITEM_QUERY = 4; private int listPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); dbStorageDemo = new DBStorageDemo(this); dbStorageDemo.openOrCreateDatabase(); //启动时显示的内容 displayList(); //注册上下文菜单 registerForContextMenu(getListView()); } private void displayList() { Cursor cursor = dbStorageDemo.selectAll(); if (cursor != null) { SimpleCursorAdapter adapter = new SimpleCursorAdapter(MainActivity.this,android.R.layout.simple_expandable_list_item_2,cursor,new String[]{dbStorageDemo.USER_NAME,dbStorageDemo.USER_ADDRESS},new int[]{android.R.id.text1,android.R.id.text2}); setListAdapter(adapter); } } //创建菜单 @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(1,ITEM_ADD,1,"增加"); menu.add(2,ITEM_QUERY,2,"查询"); //getMenuInflater().inflate(R.menu.menu_main,menu); //return super.onCreateOptionsMenu(menu); return true; } //选中菜单事件 @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == ITEM_ADD) { //显示一个dialog showDialog(USERDIALOG_ID); } //return super.onOptionsItemSelected(item); return true; } //创建一个dialog @Override protected Dialog onCreateDialog(int id) { if (id == USERDIALOG_ID) { AlertDialog dialog = new AlertDialog.Builder(MainActivity.this) .setTitle("添加用户") .setIcon(R.drawable.ic_launcher) .setView(LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_dialog,null)) .setPositiveButton("确定",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int which) { AlertDialog alertDialog = (AlertDialog) dialog; EditText editName = (EditText) alertDialog.findViewById(R.id.et_userName); EditText editAddress = (EditText) alertDialog.findViewById(R.id.et_userAddress); Users users = new Users(); users.setUserName(editName.getText().toString()); users.setUserAddress(editAddress.getText().toString()); dbStorageDemo.insertUser(users); dialog.dismiss(); displayList(); editName.setText(""); editAddress.setText(""); } }) .setNegativeButton("取消",int which) { dialog.dismiss(); showToast("你点了取消!"); } }) .show(); return dialog; } return null; } private void showToast(String msg) { Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show(); } @Override protected Dialog onCreateDialog(int id,Bundle args) { if (id == 123) { View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_dialog,null); EditText editName = (EditText) view.findViewById(R.id.et_userName); EditText editAddress = (EditText) view.findViewById(R.id.et_userAddress); editName.setText(args.getString("name","null")); editAddress.setText(args.getString("address","null")); AlertDialog dialog = new AlertDialog.Builder(MainActivity.this) .setTitle("修改内容") .setIcon(R.drawable.ic_launcher) .setView(view) .setPositiveButton("确定",int which) { AlertDialog alertDialog = (AlertDialog) dialog; EditText editName = (EditText) alertDialog.findViewById(R.id.et_userName); EditText editAddress = (EditText) alertDialog.findViewById(R.id.et_userAddress); Users users = new Users(); users.setUserName(editName.getText().toString()); users.setUserAddress(editAddress.getText().toString()); int itemId = getDatabaseID(listPosition); dbStorageDemo.updateUser(itemId,users); dialog.dismiss(); displayList(); } }) .setNegativeButton("取消",int which) { dialog.dismiss(); showToast("你点了取消!"); } }).show(); } return super.onCreateDialog(id,args); } //创建上下文菜单并指定itemId @Override public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu,v,menuInfo); menu.add(1,ITEM_MODIFY,"编辑"); menu.add(1,ITEM_DELETE,"删除"); } //长按菜单响应函数 并获取选中的listview行内容 @Override public boolean onContextItemSelected(MenuItem item) { ContextMenu.ContextMenuInfo info = item.getMenuInfo(); AdapterView.AdapterContextMenuInfo contextMenuInfo = (AdapterView.AdapterContextMenuInfo) info; //选中行位置 listPosition = contextMenuInfo.position; //响应事件 switch (item.getItemId()) { //得到_id删除选中的item case ITEM_DELETE: dbStorageDemo.deleteUser(getDatabaseID(listPosition)); //showToast(listPosition + ""); displayList(); break; //调用dialog,并在dialog中加入当前item的数据,修改item的内容 case ITEM_MODIFY: ListView listView = getListView(); View view = listView.getChildAt(listPosition); String name = ((TextView) view.findViewById(android.R.id.text1)).getText().toString(); String address = ((TextView) view.findViewById(android.R.id.text2)).getText().toString(); Bundle bundle = new Bundle(); bundle.putString("name",name); bundle.putString("address",address); showDialog(123,bundle); break; } return super.onContextItemSelected(item); } //根据listview中item的id找到对应的数据库中的_id并返回 private int getDatabaseID(int position) { ListView listView = getListView(); View view = listView.getChildAt(position); //得到选中item的数据 String name = ((TextView) view.findViewById(android.R.id.text1)).getText().toString(); String address = ((TextView) view.findViewById(android.R.id.text2)).getText().toString(); showToast(name); Cursor cursor = dbStorageDemo.selectAll(); //遍历数据库找到跟item内容相同的信息 while (cursor.moveToNext()) { //得到数据库的数据 String deleteName = cursor.getString(cursor.getColumnIndex(dbStorageDemo.USER_NAME)); String deleteAddress = cursor.getString(cursor.getColumnIndex(dbStorageDemo.USER_ADDRESS)); if (name.equals(deleteName) && address.equals(deleteAddress)) { //返回第一列即_id return cursor.getInt(0); } } return -1; } }
其中在增加用户的时候用了一个User类来传递内容
package android.jim.com.dbstorage; /** * Created by huangjim on 7/22/2015. */ public class Users { private String userName; private String userAddress; public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }在数据库操作类里已经把查询的方法写进去了,太耗时间就没写了。水平有限,如有不正确的地方请多多指出。