SQLite 数据库的创建删除小程序
写这个小程序的时候有三个问题困扰了我。
1.数据库中创建表
最开始的时候我是这么创建表的:String sql = "create table MyTable(_id integer primary key autoincrement,username text,password text)";
然后发现经常报出MyTable已存在的错,这才意识到这样创建表会导致每次进入程序都会创建一下这个已经存在的表。
于是将sql改成了:String sql = "create table IF NOT EXISTS MyTable(_id integer primary key autoincrement,username text,password text)";
当然还有另外一种办法解决这个问题,即把创建表的代码放在catch中:
代码如下:
try { db.insert(......); } catch(SQLiteException se) { db.execSQL("create table MyTable(_id integer primary key autoincrement,username text,password text)"); }
2.SimpleCursorAdapter的使用
实际上SimpleCursorAdapter和其他Adapter的使用没有太大的区别,之所以造成困扰,是因为我在讲listview和adapter绑定完之后,加上了这么一句话cursor.close();
然后就出现了listview无法显示的问题。
查资料发现即使绑定完成之后,依然不能关闭cursor。
最好将cursor.close();和db.close();代码放在Activity的onDestroy();方法中。
3.给listview创建上下文目录
即点击listview的每一项可以弹出一个ContextMenu。
第一次写这个功能,所以特别提一下。
上代码:
listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { menu.add(0, ITEM1, 0, "修改本条记录"); menu.add(1, ITEM2, 0, "删除本条记录"); } });
@Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo(); selectId = menuInfo.position; switch(item.getItemId()) { case ITEM2: delete(selectId); if(cursor!=null) cursor.close(); initListView(); Toast.makeText(this, "test", Toast.LENGTH_SHORT).show(); break; case ITEM1: edit(); break; } return true; }
下面的代码是整个程序的代码:
package com.example.dbdemofirst; import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.widget.SimpleCursorAdapter; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class DbActivity extends Activity { private Button insert; private Button show; private EditText name; private EditText password; private ListView listview; private SQLiteDatabase db; private SimpleCursorAdapter sca; private Cursor cursor; private static final int ITEM1 = Menu.FIRST; private static final int ITEM2 = Menu.FIRST+1; private int selectId = 0; // private ArrayList<Map<String,String>> listdata = new ArrayList<Map<String,String>>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_db); insert = (Button)findViewById(R.id.insert); show = (Button)findViewById(R.id.show); name = (EditText)findViewById(R.id.name); password = (EditText)findViewById(R.id.password); listview = (ListView)findViewById(R.id.listview); initDataBase(); initListView(); insert.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { insert_second(); } }); show.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(cursor!=null) cursor.close(); initListView(); //query(); } }); listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { menu.add(0, ITEM1, 0, "修改本条记录"); menu.add(1, ITEM2, 0, "删除本条记录"); } }); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo(); selectId = menuInfo.position; switch(item.getItemId()) { case ITEM2: delete(selectId); if(cursor!=null) cursor.close(); initListView(); Toast.makeText(this, "test", Toast.LENGTH_SHORT).show(); break; case ITEM1: edit(); break; } return true; } private void edit() { // TODO Auto-generated method stub } //删除数据库中的指定项 private void delete(int id) { db.delete("MyTable", "_id=?",new String[]{String.valueOf(id)}); } //创建数据库 private void initDataBase() { db = SQLiteDatabase.openOrCreateDatabase(getFilesDir().getAbsolutePath()+"/mouse.db", null); String sql = "create table IF NOT EXISTS MyTable(_id integer primary key autoincrement,username text,password text)"; db.execSQL(sql); } //将数据插入数据库中 protected void insert() { String sql = "insert into MyTable(username,password) values(123,345)"; db.execSQL(sql); } //将数据插入数据库中,第二种方法 protected void insert_second() { ContentValues value = new ContentValues(); value.put("username", name.getText().toString()); value.put("password", password.getText().toString()); db.insert("MyTable", null, value); } //初始化ListView列表 @SuppressWarnings("deprecation") private void initListView() { cursor = db.query("MyTable", null, null, null, null, null, null); sca = new SimpleCursorAdapter(this, R.layout.listview_layout, cursor, new String[]{"username","password"},new int[]{R.id.listview_name,R.id.listview_password}); listview.setAdapter(sca); //cursor.close(); } // private void query() // { // Cursor cursor = db.query("MyTable", null, null, null, null, null, null); // if(cursor.moveToFirst()) // { // for(int i =0;i<cursor.getCount();i++) // { // int id = cursor.getInt(0); // String name = cursor.getString(1); // String password = cursor.getString(2); // // HashMap<String, String> item = new HashMap<String, String>(); // item.put("name", name); // item.put("password", password); // listdata.add(item); // cursor.moveToNext(); // } // cursor.close(); // } // // BaseAdapter ba = new BaseAdapter() // { // // @Override // public View getView(int position, View convertView, ViewGroup parent) // { // LinearLayout ll = (LinearLayout) convertView.inflate(DbActivity.this, R.layout.listview_layout, null); // TextView tv1 = (TextView) ll.findViewById(R.id.listview_name); // TextView tv2 = (TextView)ll.findViewById(R.id.listview_password); // // tv1.setText(listdata.get(position).get("name")); // tv2.setText(listdata.get(position).get("password")); // return ll; // } // // @Override // public long getItemId(int position) // { // return position; // } // // @Override // public Object getItem(int position) // { // return position; // } // // @Override // public int getCount() // { // return listdata.size(); // } // }; // // listview.setAdapter(ba); // } @Override protected void onDestroy() { super.onDestroy(); if(db!=null&&db.isOpen()) { db.close(); } if(cursor!=null) cursor.close(); } }
<LinearLayout 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" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:textSize="20sp" android:text="姓名"/> <EditText android:id="@+id/name" android:inputType="text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:textSize="20sp" android:text="密码"/> <EditText android:id="@+id/password" android:inputType="textPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp"/> </LinearLayout> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/insert" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_alignParentLeft="true" android:text="插入" /> <Button android:id="@+id/show" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_alignParentRight="true" android:text="刷新列表" /> </RelativeLayout> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/holo_blue_light" > <TextView android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:textSize="20sp" android:text="姓名" /> <TextView android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:textSize="20sp" android:text="密码" /> </RelativeLayout> <ListView android:id="@+id/listview" android:background="@android:color/holo_blue_light" android:layout_width="match_parent" android:layout_height="wrap_content" android:dividerHeight="1dp" > </ListView> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/listview_name" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:textSize="20sp" /> <TextView android:id="@+id/listview_password" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:textSize="20sp" /> </RelativeLayout> </LinearLayout>