MainActivity.java
package com.walker.exp6; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; 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.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MainActivity extends AppCompatActivity { private DBAdapter db; private Button bt_add; private ListView listview; private SimpleAdapter simpleAdapter; Map<String, Object> item = new HashMap<String, Object>(); private List<Map<String, Object>> Datas = new ArrayList<Map<String, Object>>(); private int position; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt_add = findViewById(R.id.btn_add); listview = findViewById(R.id.listview); bt_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //test Intent intent = new Intent(MainActivity.this, AddActivity.class); startActivity(intent); finish(); } }); db = new DBAdapter(MainActivity.this); db.open(); display(); //设置监听 listview.setOnCreateContextMenuListener(this); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); //添加两个ITEM menu.add(0, 1, 0, "更新"); menu.add(0, 2, 0, "删除"); //得到长按的position AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; position = info.position; } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int pos = (int) listview.getAdapter().getItemId(menuInfo.position); //得到对应的map对象 Map<String, Object> stu = Datas.get(pos); switch (item.getItemId()) { case 1://更新 Intent intent = new Intent(MainActivity.this, AddActivity.class); startActivity(intent); break; case 2://删除 //1). 删除数据表对应的数据 db.deleteOneData((Integer) stu.get("id")); //2). 删除List对应的数据 Datas.remove(pos); //3). 通知更新列表 simpleAdapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "ID:" + stu.get("id") + "删除成功", Toast.LENGTH_SHORT).show(); break; default: break; } return super.onContextItemSelected(item); } @Override protected void onRestart() { super.onRestart(); // display(); // simpleAdapter.notifyDataSetChanged(); } public void display() { String[] from = {"id", "class", "number", "name"}; //Item布局文件中的子view的id的数组 int[] to = {R.id.tv_id1, R.id.tv_class1, R.id.tv_number1, R.id.tv_name1}; // /设置适配器 simpleAdapter = new SimpleAdapter(this, Datas, R.layout.item_view, from, to); listview.setAdapter(simpleAdapter); Student[] students = db.queryAllData(); if (students == null) { return; } String cl; String num; String na; int id; for (int i = 0; i < students.length; i++) { cl = students[i].getClas(); num = students[i].getNumber(); na = students[i].getName(); id = students[i].getID(); //Toast.makeText(MainActivity.this,cl+num+na,Toast.LENGTH_SHORT).show(); Map<String, Object> item = new HashMap<String, Object>(); item.put("id", id); item.put("class", cl); item.put("number", num); item.put("name", na); Datas.add(item); simpleAdapter.notifyDataSetChanged(); } } }
AddActivity.java
package com.walker.exp6; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.HashMap; import java.util.Map; public class AddActivity extends AppCompatActivity { private DBAdapter db; private Student student; private Button bt_cancel; private Button bt_ensure; private EditText et_cl; private EditText et_num; private EditText et_na; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); bt_cancel = findViewById(R.id.bt_cancel); bt_ensure = findViewById(R.id.bt_ensure); et_cl = findViewById(R.id.et_cl); et_num = findViewById(R.id.et_num); et_na = findViewById(R.id.et_na); //Intent intent = getIntent(); db = new DBAdapter(this); db.open(); bt_cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddActivity.this,MainActivity.class); startActivity(intent); finish(); } }); bt_ensure.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { String cl = et_cl.getText().toString(); String num = et_num.getText().toString(); String na = et_na.getText().toString(); student = new Student(cl,num,na); // Toast.makeText(AddActivity.this,cl+num+na,Toast.LENGTH_SHORT).show(); long colunm= db.insert(student); //db.close(); Intent intent = new Intent(AddActivity.this,MainActivity.class); startActivity(intent); db.close(); finish(); } }); } }
ADBadapter.java
package com.walker.exp6; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase.CursorFactory; public class DBAdapter { private static final String DB_NAME = "student.db"; private static final String DB_TABLE = "studentinfo"; private static final int DB_VERSION = 1; public static final String KEY_ID = "_id"; public static final String KEY_NAME = "name"; public static final String KEY_CLASS = "class"; public static final String KEY_NUMBER = "number"; private SQLiteDatabase db; private final Context context; private DBOpenHelper dbOpenHelper; public DBAdapter(Context _context) { context = _context; } /** Close the database */ public void close() { if (db != null){ db.close(); db = null; } } /** Open the database */ public void open() throws SQLiteException { dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION); try { db = dbOpenHelper.getWritableDatabase(); } catch (SQLiteException ex) { db = dbOpenHelper.getReadableDatabase(); } } public long insert(Student student) { ContentValues newValues = new ContentValues(); newValues.put(KEY_NAME, student.Name); newValues.put(KEY_CLASS, student.Clas); newValues.put(KEY_NUMBER, student.Number); return db.insert(DB_TABLE, null, newValues); } public Student[] queryAllData() { Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER}, null, null, null, null, null); return ConvertToStudent(results); } public Student[] queryOneData(long id) { Cursor results = db.query(DB_TABLE, new String[] { KEY_ID, KEY_NAME, KEY_CLASS, KEY_NUMBER}, KEY_ID + "=" + id, null, null, null, null); return ConvertToStudent(results); } private Student[] ConvertToStudent(Cursor cursor){ int resultCounts = cursor.getCount(); if (resultCounts == 0 || !cursor.moveToFirst()){ return null; } Student[] students = new Student[resultCounts]; for (int i = 0 ; i<resultCounts; i++){ students[i] = new Student(); students[i].ID = cursor.getInt(0); students[i].Name = cursor.getString(cursor.getColumnIndex(KEY_NAME)); students[i].Clas = cursor.getString(cursor.getColumnIndex(KEY_CLASS)); students[i].Number = cursor.getString(cursor.getColumnIndex(KEY_NUMBER)); cursor.moveToNext(); } return students; } public long deleteAllData() { return db.delete(DB_TABLE, null, null); } public long deleteOneData(int id) { return db.delete(DB_TABLE, KEY_ID + "=" + id, null); } public long updateOneData(long id , Student student){ ContentValues updateValues = new ContentValues(); updateValues.put(KEY_NAME, student.Name); updateValues.put(KEY_CLASS, student.Clas); updateValues.put(KEY_NUMBER, student.Number); return db.update(DB_TABLE, updateValues, KEY_ID + "=" + id, null); } private static class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } private static final String DB_CREATE = "create table " + DB_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_NAME+ " text not null, " + KEY_CLASS+ " text not null," + KEY_NUMBER + " text not null);"; @Override public void onCreate(SQLiteDatabase _db) { _db.execSQL(DB_CREATE); } @Override public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) { _db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE); onCreate(_db); } } }
student.java
package com.walker.exp6; public class Student { public int ID = -1; public String Name; public String Number; public String Clas; public Student(String Class, String Number, String Name) { this.Clas = Class; this.Number = Number; this.Name = Name; } public Student() { super(); } public String getClas() { return Clas; } public String getName() { return Name; } public String getNumber() { return Number; } public int getID() { return ID; } @Override public String toString() { String result = ""; result += this.ID + " "; result += this.Clas + " "; result += this.Number + " "; result += this.Name + " "; return result; } }
activity.xml
<?xml version="1.0" encoding="utf-8"?> <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:background="@color/layout" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="ID" android:textSize="20sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="班级" android:textSize="20sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="学号" android:textSize="20sp" /> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="姓名" android:textSize="20sp" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ListView android:id="@+id/listview" android:layout_width="match_parent" android:layout_height="wrap_content"></ListView> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btn_add" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@color/app_bk" android:text="@string/app_button" android:textSize="20sp" /> </RelativeLayout> </LinearLayout>
activity_add.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".AddActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#bdddc8"> <Button android:id="@+id/bt_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="取消" android:textSize="20sp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_centerVertical="true" android:gravity="center_vertical|center_horizontal" android:text="添加名单" android:textSize="20sp" /> <Button android:id="@+id/bt_ensure" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="确定" android:textSize="20sp"/> </RelativeLayout> <EditText android:id="@+id/et_num" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="学号" android:inputType="text" android:textSize="20sp" /> <EditText android:id="@+id/et_na" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="姓名" android:textSize="20sp" /> <EditText android:id="@+id/et_cl" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="班级" android:textSize="20sp" /> </LinearLayout>
item_view.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"> <TextView android:id="@+id/tv_id1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp"/> <TextView android:id="@+id/tv_class1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp"/> <TextView android:id="@+id/tv_number1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp"/> <TextView android:id="@+id/tv_name1" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="20sp"/> </LinearLayout>
文章来源: 实验六 sqlite 是数据库管理