安卓--数据存储和访问
实验目的:
分别使用sqlite3工具和Android代码的方式建立SQLite数据库。在完成建立数据库的工作后,编程实现基本的数据库操作功能,包括数据的添加、删除和更新。
实验要求:
- 创建一个学生管理的应用,基本信息包含学生姓名,班级,学号。采用数据库存储这些信息。
- 应用应该至少包含信息录入和删除功能。
- 数据显示考虑采用ListView。
(1) 使用sqlite3工具建库:
使用adb前,需要先把adb加入环境变量:C:\Users\Flyuz\AppData\Local\Android\Sdk\platform-tools
然后在cmd或android studio命令行中进入adb shell。
出现的问题:
Android 7无法获得root权限,不能进入data/data/com.example.flyuz.sqlite6文件夹,所以不能建库,
解决方法:1 在命令行中前后使用 adb root adb remount (我不管用)
2 使用Android 6的虚拟机即可获得root权限。
步骤:
进入adb shell
cd data/data/com.example.flyuz.sqlite6
建数据库文件夹 mkdir databases
建数据库 sqlite3 student.db
Create table studentinfo(num text PRIMARY KEY, name text not null, cla text not null);
添加数据 insert into studentinfo()
查看所有表 .tables
1 package com.example.flyuz.sqlite6; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.view.View; 6 import android.view.MenuItem; 7 import android.widget.Button; 8 import android.widget.ListView; 9 import android.widget.ArrayAdapter; 10 import android.widget.EditText; 11 import android.widget.PopupMenu; 12 import android.widget.AdapterView; 13 14 import java.util.List; 15 import java.util.ArrayList; 16 17 public class MainActivity extends AppCompatActivity { 18 private Button bt_add; 19 private ListView lv; 20 private DBAdapter dbAdapter; 21 22 @Override 23 protected void onCreate(Bundle savedInstanceState) { 24 super.onCreate(savedInstanceState); 25 setContentView(R.layout.activity_main); 26 bt_add = (Button) findViewById(R.id.bt_add); 27 lv = (ListView) findViewById(R.id.lv); 28 dbAdapter = new DBAdapter(this); 29 dbAdapter.open(); 30 init(); 31 } 32 33 private void init() { 34 Student[] students = dbAdapter.queryAllData(); 35 36 List<String> list = new ArrayList<String>(); 37 if (students != null) { 38 for (Student stu : students) { 39 list.add(stu.toString()); 40 } 41 } 42 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list); 43 lv.setAdapter(adapter); 44 45 //设置事件 46 bt_add.setOnClickListener(new View.OnClickListener() { 47 public void onClick(View v) { 48 EditText et_class = (EditText) findViewById(R.id.et_class); 49 EditText et_number = (EditText) findViewById(R.id.et_number); 50 EditText et_name = (EditText) findViewById(R.id.et_name); 51 52 String str_class = et_class.getText().toString(); 53 String str_number = et_number.getText().toString(); 54 String str_name = et_name.getText().toString(); 55 56 Student student = new Student(); 57 student.setNum(str_number); 58 student.setName(str_name); 59 student.setCla(str_class); 60 long colunm = dbAdapter.insert(student); 61 62 ArrayAdapter add_adp = (ArrayAdapter) lv.getAdapter(); 63 add_adp.add(student.toString()); 64 } 65 }); 66 lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { 67 @Override 68 public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { 69 PopupMenu popup = new PopupMenu(MainActivity.this, view); 70 popup.getMenuInflater().inflate(R.menu.menu, popup.getMenu()); 71 popup.show(); 72 popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { 73 @Override 74 public boolean onMenuItemClick(MenuItem item) { 75 switch (item.getItemId()) { 76 case R.id.menu_del: 77 ArrayAdapter temp_adp = (ArrayAdapter) lv.getAdapter(); 78 String delStu = (String) temp_adp.getItem(position); 79 String[] num = delStu.split("\\s+"); 80 String[] res = num[0].split(":"); 81 long colunm = dbAdapter.deleteOneData(Integer.parseInt(res[1])); 82 temp_adp.remove(temp_adp.getItem(position)); 83 return true; 84 default: 85 return false; 86 } 87 } 88 }); 89 return true; 90 } 91 }); 92 } 93 }
1 package com.example.flyuz.sqlite6; 2 3 import android.content.ContentValues; 4 import android.content.Context; 5 import android.database.Cursor; 6 import android.database.sqlite.SQLiteDatabase; 7 import android.database.sqlite.SQLiteException; 8 import android.database.sqlite.SQLiteOpenHelper; 9 import android.database.sqlite.SQLiteDatabase.CursorFactory; 10 11 /** 12 * Created by Administrator on 2018/10/29. 13 */ 14 15 public class DBAdapter { 16 private static final String DB_NAME = "student.db"; 17 private static final String DB_TABLE = "studentinfo"; 18 private static final int DB_VERSION = 1; 19 20 //public static final String KEY_ID = "id"; 21 public static final String KEY_NAME = "name"; 22 public static final String KEY_NUM = "num"; 23 public static final String KEY_CLA = "cla"; 24 25 private SQLiteDatabase db; 26 private final Context context; 27 28 public DBAdapter(Context _context) { 29 context = _context; 30 } 31 32 /** Close the database */ 33 public void close() { 34 if (db != null){ 35 db.close(); 36 db = null; 37 } 38 } 39 40 /** Open the database */ 41 public void open() throws SQLiteException { 42 DBOpenHelper dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION); 43 try { 44 db = dbOpenHelper.getWritableDatabase(); 45 } 46 catch (SQLiteException ex) { 47 db = dbOpenHelper.getReadableDatabase(); 48 } 49 } 50 51 private static class DBOpenHelper extends SQLiteOpenHelper { 52 53 public DBOpenHelper(Context context, String name, CursorFactory factory, int version) { 54 super(context, name, factory, version); 55 } 56 57 private static final String DB_CREATE = 58 "create table " + DB_TABLE 59 + "(" 60 + KEY_NUM + " text PRIMARY KEY," 61 + KEY_NAME + " text not null, " 62 + KEY_CLA + " text not null" +" );"; 63 64 @Override 65 public void onCreate(SQLiteDatabase _db) { 66 _db.execSQL(DB_CREATE); 67 } 68 69 @Override 70 public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) { 71 _db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE); 72 onCreate(_db); 73 } 74 } 75 76 public long insert(Student student) { 77 ContentValues newValues = new ContentValues(); 78 79 newValues.put(KEY_NUM, student.getNum()); 80 newValues.put(KEY_NAME, student.getName()); 81 newValues.put(KEY_CLA, student.getCla()); 82 83 return db.insert(DB_TABLE, null, newValues); 84 } 85 86 public Student[] queryAllData() { 87 Cursor results = db.query(DB_TABLE, new String[] { KEY_NUM, KEY_NAME, KEY_CLA}, 88 null, null, null, null, null); 89 return ConvertToStudent(results); 90 } 91 public Student[] queryOneData(long id) { 92 Cursor results = db.query(DB_TABLE, new String[] { KEY_NUM, KEY_NAME, KEY_CLA}, 93 KEY_NUM + "=" + id, null, null, null, null); 94 return ConvertToStudent(results); 95 } 96 97 private Student[] ConvertToStudent(Cursor cursor){ 98 int resultCounts = cursor.getCount(); 99 if (resultCounts == 0 || !cursor.moveToFirst()){ 100 return null; 101 } 102 103 Student[] students = new Student[resultCounts]; 104 for (int i = 0 ; i<resultCounts; i++){ 105 students[i] = new Student(); 106 107 students[i].setNum(cursor.getString(cursor.getColumnIndex(KEY_NUM))); 108 students[i].setName(cursor.getString(cursor.getColumnIndex(KEY_NAME))); 109 students[i].setCla( cursor.getString(cursor.getColumnIndex(KEY_CLA))); 110 111 cursor.moveToNext(); 112 } 113 return students; 114 } 115 116 117 public long deleteAllData() { 118 return db.delete(DB_TABLE, null, null); 119 } 120 121 public long deleteOneData(long id) { 122 return db.delete(DB_TABLE, KEY_NUM + "=" + id, null); 123 } 124 125 public long updateOneData(long id , Student student){ 126 ContentValues updateValues = new ContentValues(); 127 128 updateValues.put(KEY_NUM, student.getNum()); 129 updateValues.put(KEY_NAME, student.getName()); 130 updateValues.put(KEY_CLA, student.getCla()); 131 132 return db.update(DB_TABLE, updateValues, KEY_NUM+ "=" + id, null); 133 } 134 }
1 package com.example.flyuz.sqlite6; 2 3 /** 4 * Created by Administrator on 2018/10/29. 5 */ 6 7 public class Student { 8 private String Num; 9 private String Name; 10 private String Cla; 11 12 public String toString(){ 13 return "学号:" + Num + " 姓名:" + Name + " 班级:" + Cla; 14 } 15 16 public String getNum() { 17 return Num; 18 } 19 20 public String getName() { 21 return Name; 22 } 23 24 public String getCla() { 25 return Cla; 26 } 27 28 public void setNum(String num) { 29 Num = num; 30 } 31 32 public void setName(String name) { 33 Name = name; 34 } 35 36 public void setCla(String cla) { 37 Cla = cla; 38 } 39 }
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:orientation="vertical" 8 tools:context=".MainActivity"> 9 10 <LinearLayout 11 android:layout_width="match_parent" 12 android:layout_height="200dp" 13 android:gravity="center" 14 android:orientation="vertical"> 15 16 <LinearLayout 17 android:layout_width="match_parent" 18 android:layout_height="50dp" 19 android:gravity="center" 20 android:orientation="horizontal"> 21 22 <TextView 23 android:layout_width="50dp" 24 android:layout_height="40dp" 25 android:gravity="center" 26 android:text="学号:" /> 27 28 <EditText 29 android:id="@+id/et_number" 30 android:layout_width="150dp" 31 android:layout_height="40dp" /> 32 </LinearLayout> 33 34 <LinearLayout 35 android:layout_width="match_parent" 36 android:layout_height="50dp" 37 android:gravity="center" 38 android:orientation="horizontal"> 39 40 <TextView 41 android:layout_width="50dp" 42 android:layout_height="40dp" 43 android:gravity="center" 44 android:text="姓名:" /> 45 46 <EditText 47 android:id="@+id/et_name" 48 android:layout_width="150dp" 49 android:layout_height="40dp" /> 50 </LinearLayout> 51 52 <LinearLayout 53 android:layout_width="match_parent" 54 android:layout_height="50dp" 55 android:gravity="center" 56 android:orientation="horizontal"> 57 58 <TextView 59 android:layout_width="50dp" 60 android:layout_height="40dp" 61 android:gravity="center" 62 android:text="班级:" /> 63 64 <EditText 65 android:id="@+id/et_class" 66 android:layout_width="150dp" 67 android:layout_height="40dp" /> 68 </LinearLayout> 69 70 71 <Button 72 android:id="@+id/bt_add" 73 android:layout_width="180dp" 74 android:layout_height="40dp" 75 android:text="添加" /> 76 </LinearLayout> 77 78 <ListView 79 android:id="@+id/lv" 80 android:layout_width="match_parent" 81 android:layout_height="wrap_content" 82 android:longClickable="true" /> 83 84 </LinearLayout>
1 <?xml version="1.0" encoding="utf-8"?> 2 <menu xmlns:android="http://schemas.android.com/apk/res/android"> 3 <item 4 android:id="@+id/menu_del" 5 android:title="删除" /> 6 </menu>
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.flyuz.service5"> 4 5 <application 6 android:allowBackup="true" 7 android:icon="@mipmap/ic_launcher" 8 android:label="@string/app_name" 9 android:roundIcon="@mipmap/ic_launcher_round" 10 android:supportsRtl="true" 11 android:theme="@style/AppTheme"> 12 <activity android:name=".MainActivity"> 13 <intent-filter> 14 <action android:name="android.intent.action.MAIN" /> 15 16 <category android:name="android.intent.category.LAUNCHER" /> 17 </intent-filter> 18 </activity> 19 <service android:name=".chronometerService"/> 20 </application> 21 22 </manifest>
1 <?xml version="1.0" encoding="utf-8"?> 2 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="com.example.flyuz.sqlite6"> 4 5 <application 6 android:allowBackup="true" 7 android:icon="@mipmap/ic_launcher" 8 android:label="@string/app_name" 9 android:roundIcon="@mipmap/ic_launcher_round" 10 android:supportsRtl="true" 11 android:theme="@style/AppTheme"> 12 <activity android:name=".MainActivity"> 13 <intent-filter> 14 <action android:name="android.intent.action.MAIN" /> 15 16 <category android:name="android.intent.category.LAUNCHER" /> 17 </intent-filter> 18 </activity> 19 </application> 20 21 </manifest>