功能:用SQLitem完成数据库的动态增删改查功能,数据的存储于访问 SQLite数据库编程 SimpleCursorAdapter和上下文菜单基本用法
开发平台:Android Studio 3.0.1
整体框架:
见代码及注释:
MainActivity.java:
package com.example.test_4application; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private static int DB_VERSION=1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bt1=(Button) findViewById(R.id.button1); Button bt2=(Button) findViewById(R.id.button2); Button bt3=(Button) findViewById(R.id.button3); Button bt4=(Button) findViewById(R.id.button4); Button bt5=(Button) findViewById(R.id.button5); Button bt6=(Button) findViewById(R.id.button6); TextView tv=(TextView)findViewById(R.id.textView1); View.OnClickListener listener=new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.button1: createdb(); break; case R.id.button2: Person person=new Person(); person.name="wustzz"; person.age=39; insert(person); break; case R.id.button3: deleteById(1); break; case R.id.button4: Person person1=new Person(); person1.name="wustzz"; person1.age=39; updateById(1,person1); break; case R.id.button5: find(); break; } } }; bt1.setOnClickListener(listener); bt2.setOnClickListener(listener); bt3.setOnClickListener(listener); bt4.setOnClickListener(listener); bt5.setOnClickListener(listener); bt6.setOnClickListener(listener); } public void createdb(){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); //调用getWritableDatabase()或getReadableDatabase()才会真正创建或打开 SQLiteDatabase db=helper.getWritableDatabase(); db.close(); //操作完成后关闭数据库连接 Toast.makeText(getApplicationContext(), "数据库创建成功", Toast.LENGTH_SHORT).show(); } public void insert(Person person){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("INSERT INTO person VALUES (NULL, ? , ? )", new Object[ ] { person.name, person.age } ); db.close(); Toast.makeText(getApplicationContext(), "记录添加成功", Toast.LENGTH_SHORT).show(); } public void deleteById(int id){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL( "Delete from person where id= ? " , new Object[ ]{id} ); db.close(); Toast.makeText(getApplicationContext(), "记录删除成功", Toast.LENGTH_SHORT).show(); } public void updateById(int id, Person person){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL("Update person set name= ? , age= ? where id= ? ", new Object[ ]{ person.name,person.age, id } ); db.close(); Toast.makeText(getApplicationContext(), "记录修改成功", Toast.LENGTH_SHORT).show(); } public void find(){ /* DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,DB_VERSION); SQLiteDatabase db=helper.getWritableDatabase(); Cursor cursor = db.rawQuery( "SELECT * FROM person where age>?", new String[]{"10"} ); TextView tv=(TextView)findViewById(R.id.textView_list); //简单用TextView显示一下数据 tv.setText("查询到"+cursor.getCount()+"条记录(当前数据库版本号="+DB_VERSION+")"); while (cursor.moveToNext()) { //遍历结果集 int id = cursor.getInt(cursor.getColumnIndex("id") ); String name = cursor.getString(cursor.getColumnIndex("name") ); int age = cursor.getInt(cursor.getColumnIndex("age") ); tv.setText(tv.getText()+"\n"+"id="+id+",name="+name+",age="+age); } cursor.close(); //关闭cursor db.close(); //关闭数据库连接 */ Intent it = new Intent( MainActivity.this, ShowActivity.class ); startActivity(it); } }
上述的删改都是静态删改,且都未指定要删改的对象,读者自己可以指定id来删改。删改功能后面有动态删改实现,不同代码指定,直接在界面上完成。
activity_main.xml 代码:
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="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="创建数据库和表" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="添加记录" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="删除记录" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="修改记录" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="查询记录" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <Button android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="更新数据库" /> LinearLayout> <TextView android:id="@+id/textView_list" android:layout_width="match_parent" android:layout_height="match_parent" android:text="TextView" android:textSize="24sp" /> LinearLayout>
DBHelper.java 代码(创建数据库和表):
package com.example.test_4application; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by lenovo on 2018/4/28. */ public class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS person (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(20)," + "age SMALLINT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS person"); //删除数据表,谨慎使用 onCreate(db); //重新建表 } }
Person.java 代码(创建数据模型):
package com.example.test_4application; /** * Created by lenovo on 2018/4/28. */ public class Person { public int id; public String name; public int age; public Person(){ } public Person(String name, int age) { this.name = name; this.age = age; } }
//本实验定义人的基本信息数据模型类Person
ShowActivity.java 代码:
package com.example.test_4application; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; public class ShowActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1); SQLiteDatabase db=helper.getWritableDatabase(); Cursor cursor = db.rawQuery( "SELECT id as _id, name,age FROM Person",null); String[] from = { "_id", "name", "age" }; int[] to = { R.id.txtID, R.id.txtName, R.id.txtAge }; SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.listview, cursor, from, to);//使用SimpleCursorAdapter填充ListView
//cursor.close();不能close(),否则SimpleCursorAdapter将不能从Cursor中读取数据显示 ListView li=(ListView)findViewById(R.id.listView1); li.setAdapter(adapter); TextView tv=(TextView)findViewById(R.id.textView_rem); tv.setText("查询到"+cursor.getCount()+"条记录"); ListView list1=(ListView)findViewById(R.id.listView1); registerForContextMenu( list1 ); //将上下文菜单注册到ListView上 Button bt1= (Button)findViewById(R.id.button_add); //注意id值 bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent intent=new Intent(ShowActivity.this,InsertActivity.class); startActivityForResult(intent, 100); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==100) if(resultCode==RESULT_OK){ onCreate(null); } // 100表明是来自于InsertActivity的回传 if(requestCode==200) //200表明是来自于InsertActivity的回传 if(resultCode==RESULT_OK) { onCreate(null); //ShowActivity重新执行onCreate,即完成刷新 } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.setHeaderTitle("操作"); getMenuInflater().inflate(R.menu.managa, menu); } @Override public boolean onContextItemSelected(MenuItem item) { //添加上下文菜单选中项方法 switch ( item.getItemId() ) { case R.id.delete: delete(item); //代码见后 return true; case R.id.update : update(item); //代码见后 return true; default: return false; } }
//删除:根据id值作为删除记录的条件
public void delete(MenuItem item){ final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); if(info.id>0){ new AlertDialog.Builder(this).setTitle("删除" + info.id) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1); SQLiteDatabase db=helper.getWritableDatabase(); db.execSQL( "Delete from person where id= ? ", new Object[ ]{ info.id } ); db.close(); Toast.makeText(getApplicationContext(), "记录删除成功", Toast.LENGTH_SHORT).show(); onCreate(null); //重新加载一次Activity,刷新 } }) .setNegativeButton("取消", null) .show(); } }
//修改:将id值及其他字段的值传到UpdateActivity显示和修改 将当前选中行的id、name、age字段值送到UpdateActivity中去修改,后者回传信息public void update(MenuItem item){ final AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); Intent intent = new Intent(ShowActivity. this, UpdateActivity. class); Bundle bundle= new Bundle(); bundle.putString( "id", String. valueOf(info. id)); bundle.putString( "username",((TextView)info. targetView.findViewById(R.id. txtName)).getText().toString()); bundle.putString( "age",((TextView)info. targetView.findViewById(R.id. txtAge)).getText().toString()); intent.putExtras(bundle); startActivityForResult(intent, 200); }}
activity_show.xml 代码:
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="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:layout_weight="1" android:orientation="horizontal"> <TextView android:id="@+id/textView_rem" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="8" /> <Button android:id="@+id/button_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="添加" android:textSize="24sp" /> LinearLayout> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" /> LinearLayout>
InsertActivity.java 代码:
package com.example.test_4application; import android.app.Activity; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class InsertActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_insert); Button bt1= (Button)findViewById(R.id.newRec); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { EditText et1=(EditText)findViewById(R.id.editText1); EditText et2=(EditText)findViewById(R.id.editText2); Person person=new Person(et1.getText().toString(), Integer.parseInt(et2.getText().toString())); insert(person); setResult(RESULT_OK, null); //不回传intent可设为null finish(); } }); } public void insert(Person person){ DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1); SQLiteDatabase db=helper.getWritableDatabase(); String sql="INSERT INTO person VALUES (NULL, ?, ?)"; db.execSQL(sql, new Object[ ] { person.name, person.age } ); db.close(); Toast.makeText(getApplicationContext(), "记录添加成功", Toast.LENGTH_SHORT).show(); } }
avtivity_insert.xml 代码:
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="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="姓名" android:textSize="24sp" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:inputType="textPersonName" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="年龄" android:textSize="24sp" /> <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:inputType="textPersonName" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <Button android:id="@+id/newRec" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="保存" android:textSize="24sp" /> <Button android:id="@+id/button_cancel1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="取消" android:textSize="24sp" /> LinearLayout> LinearLayout>
UpdateActivity.java 代码:
package com.example.test_4application; import android.app.Activity; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class UpdateActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); Intent intent=getIntent(); Bundle bundle=intent.getExtras(); String id=bundle.getString("id"); String name=bundle.getString("username"); String age=bundle.getString("age"); final EditText et1=(EditText)findViewById(R.id.editText3); final EditText et2=(EditText)findViewById(R.id.editText4); final EditText et3=(EditText)findViewById(R.id.editText5); et1.setText(id); et2.setText(name); et3.setText(age); //显示ShowActivity传来的id、name、age字段值 Button bt1= (Button)findViewById(R.id.button_save); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { DBHelper helper = new DBHelper(getApplicationContext(), "test.db", null,1); SQLiteDatabase db=helper.getWritableDatabase(); //更新数据,id值不能修改 db.execSQL("Update person set name= ? , age=? where id=?", new Object[ ]{ et2.getText().toString(),et3.getText().toString(),et1.getText().toString() } ); db.close(); Toast.makeText(getApplicationContext(), "记录修改成功", Toast.LENGTH_SHORT).show(); setResult(RESULT_OK, null); finish(); //不能少 } }); Button bt2= (Button)findViewById(R.id.button_cancel2); bt2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { finish(); } }); //取消按钮 } }
avtivity_update.xml 代码:
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="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="编号" android:textSize="24sp" /> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:inputType="textPersonName" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="姓名" android:textSize="24sp" /> <EditText android:id="@+id/editText4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:inputType="textPersonName" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="80dp" android:orientation="horizontal"> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="年龄" android:textSize="24sp" /> <EditText android:id="@+id/editText5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:inputType="textPersonName" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <Button android:id="@+id/button_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="保存" android:textSize="24sp" /> <Button android:id="@+id/button_cancel2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="取消" android:textSize="24sp" /> LinearLayout> LinearLayout>
listview.xml 代码:
xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <TextView android:id="@+id/txtAge" android:layout_width="50dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text=" age" android:textSize="20dp" /> <TextView android:id="@+id/txtName" android:layout_width="100dip" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text=" name" android:textSize="20dp" /> <TextView android:id="@+id/txtID" android:layout_width="100dip" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="id" android:textSize="20dp" /> LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <ListView android:id="@+id/ListView1" android:layout_width="match_parent" android:layout_height="match_parent" /> LinearLayout> LinearLayout>
//ListView使用SimpleCursorAdapter适配器填充:(用于显示数据库数据)该适配器允许将一个Cursor(查询结果集)的数据列绑定到ListView自定义布局中的TextView 或 ImageView组件上
//此处补充ShowActivity中SimpleCursorAdapter用法,见下图
managa.xml 代码:
xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/delete" android:title="删除">item> <item android:id="@+id/update" android:title="修改">item> menu>//ListView添加ContextMenu (ShowActivity中用到) 方法: 在res下新建menu目录(2)在menu目录下新建一个manage.xml文件
运行截图:
图一
图二
图三
图四
图五
用法: 打开app 主页面为图一,除了删除和修改按钮功能没实现(放在其他界面实现),其他都已实现,点击查询记录,回跳转到图二界面,点击图二界面的添加按钮既会调到图三的添加数据界面,用户可自行输入数据,点击保存就可以保存到数据库,并且刷新图二显示界面,将新添加的记录一并显示出来,长按图二中的每一行中的任意数据,会出现图四对数据操作的界面,点击操作功能即可进入相应界面进行删除或修改,图五为进行修改界面,点击保存即可保存到数据库,并刷新图二。
本人使用android 6.0 手机,功能都可以实现.