Android Studio下SQLite数据库的配置与使用(完)

一,AS开发app用,所用的数据库有限制,必须使用较小的SQLite(MySql和Sql Server想想就不显示)

  但是该数据库并不需要我们单独下载,安装的SDK中已经有了,在C:\AndroidSDK\platform-tools目录下

    最下面一个exe文件就是,双击可以打开dos界面进行编写

将上述讲的SQLite的目录(C:\AndroidSDK\platform-tools)添加到环境变量path下就可以完成配置

验证是否完成配置:打开dos界面,输入SQLite3,出现以下界面就表示成功了

《Android Studio下SQLite数据库的配置与使用(完)》

二,分享一款SQLite3的可视化操作界面

  黑框框虽然看起来逼格非常高,但是个人觉得太捞比了,主要是太麻烦了(个人很懒)

    一个可视化界面的exe文件:SQLiteStudio 百度云盘地址 http://pan.baidu.com/s/1dES3Zep

    不用安装,解压后直接使用

三,以下分享一个在百度上找了很久的很小的对于数据库增删改查操作的实践~~~

原文出处:http://www.jianshu.com/p/ee08f75b407c 

<一>界面部分

我个人看法,开发app,首先可以把各个界面设计出来,这样也就明确了自己想要实现什么功能,那么在后面的代码实现过程中,就相应的有了目的性,界面不够,我们再添加就好了~

首先上两张图,也就是这个小project中的两个界面,也就是我们要实现的几个功能

界面一:显示所有学生名字,然后点某个人,跳到界面二

《Android Studio下SQLite数据库的配置与使用(完)》

界面二:某个学生的具体信息,可以对这个学生进行删改,或者添加新同学~

《Android Studio下SQLite数据库的配置与使用(完)》

1,首先创建一个project,名字随意

 

2,实现第一个页面布局activity_main.xml(也就是页面一)

(我个人直接把学习网站的代码拔过来了,但是会有一些warning)

比如:android:text=”Add” 

  最好在strings.xml中配置一下 :

    添加一条 <string name=”add”>Add</string>

  然后改成android:text = “@string/add”

  并不是说第一种错了,而是第二种规范性更棒,日后管理更新等操作更加方便,只需要在strings中改一下就ok了

 

《Android Studio下SQLite数据库的配置与使用(完)》
《Android Studio下SQLite数据库的配置与使用(完)》

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingLeft="@dimen/activity_horizontal_margin"
 6     android:paddingRight="@dimen/activity_horizontal_margin"
 7     android:paddingTop="@dimen/activity_vertical_margin"
 8     android:paddingBottom="@dimen/activity_vertical_margin"
 9     tools:context=".MainActivity">
10 
11     <Button
12         android:layout_width="wrap_content"
13         android:layout_height="wrap_content"
14         android:text="@string/add"
15         android:id="@+id/btnAdd"
16         android:layout_alignParentBottom="true"
17         android:layout_alignParentLeft="true"
18         tools:ignore="RtlHardcoded" />
19     <ListView
20         android:id="@android:id/list"
21         android:layout_width="wrap_content"
22         android:layout_height="wrap_content"
23         android:layout_above="@+id/btnAdd"
24         />
25 
26     <Button
27         android:layout_width="wrap_content"
28         android:layout_height="wrap_content"
29         android:text="@string/ListAll"
30         android:id="@+id/btnGetAll"
31         tools:ignore="RtlHardcoded"
32         android:layout_alignParentBottom="true"
33         android:layout_toEndOf="@+id/btnAdd" />
34 </RelativeLayout>

activity_main

 

3,接下来,画出界面二

  我们可以直接创建一个新的activity,因为没个界面都要配合一个动作的嘛~,因此可以直接new一个新的activity,StudentDetail.java

  其布局为第二个页面activity_student_detail.xml

《Android Studio下SQLite数据库的配置与使用(完)》
《Android Studio下SQLite数据库的配置与使用(完)》

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     xmlns:tools="http://schemas.android.com/tools"
 4     android:id="@+id/activity_student_detail"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:paddingBottom="@dimen/activity_vertical_margin"
 8     android:paddingLeft="@dimen/activity_horizontal_margin"
 9     android:paddingRight="@dimen/activity_horizontal_margin"
10     android:paddingTop="@dimen/activity_vertical_margin"
11     tools:context="examples.ouc.com.sqlitedemo.StudentDetail">
12 
13     <TextView
14         android:layout_width="wrap_content"
15         android:layout_height="wrap_content"
16         android:text="@string/name"
17         android:id="@+id/tvName"
18         android:layout_alignParentTop="true"
19         android:layout_alignParentLeft="true"
20         android:layout_alignParentStart="true"
21         android:layout_marginTop="30dp" />
22 
23     <TextView
24         android:layout_width="wrap_content"
25         android:layout_height="wrap_content"
26         android:text="@string/email"
27         android:id="@+id/tvEmail"
28         android:layout_below="@id/tvName"
29         android:layout_alignParentLeft="true"
30         android:layout_alignParentStart="true"
31         android:layout_marginTop="30dp" />
32     <TextView
33         android:layout_width="wrap_content"
34         android:layout_height="wrap_content"
35         android:text="@string/age"
36         android:id="@+id/tvAge"
37         android:layout_below="@id/tvEmail"
38         android:layout_alignParentLeft="true"
39         android:layout_alignParentStart="true"
40         android:layout_marginTop="30dp" />
41 
42     <EditText
43         android:layout_width="wrap_content"
44         android:layout_height="wrap_content"
45         android:id="@+id/etName"
46         android:inputType="textPersonName"
47         android:ems="10"
48         android:layout_above="@id/tvEmail"
49         android:layout_toEndOf="@id/tvName"
50         android:layout_alignParentRight="true"
51         android:layout_alignParentEnd="true" />
52 
53 
54     <EditText
55         android:layout_width="match_parent"
56         android:layout_height="wrap_content"
57         android:id="@+id/etEmail"
58         android:layout_toEndOf="@id/tvEmail"
59         android:inputType="textEmailAddress"
60         android:ems="10"
61         android:layout_above="@id/tvAge"
62         android:layout_alignParentRight="true"
63         android:layout_alignParentEnd="true" />
64 
65     <Button
66         android:layout_width="wrap_content"
67         android:layout_height="wrap_content"
68         android:id="@+id/btnClose"
69         android:text="@string/close"
70         android:layout_alignParentBottom="true"
71         android:layout_alignParentRight="true"
72         />
73 
74     <Button
75         android:layout_width="wrap_content"
76         android:layout_height="wrap_content"
77         android:id="@+id/btnSave"
78         android:text="@string/save"
79         android:layout_alignParentBottom="true"
80         android:layout_toStartOf="@id/btnClose"/>
81 
82     <Button
83         android:layout_width="wrap_content"
84         android:layout_height="wrap_content"
85         android:id="@+id/btnDelete"
86         android:text="@string/delete"
87         android:layout_alignParentBottom="true"
88         android:layout_toStartOf="@id/btnSave"/>
89 
90     <EditText
91         android:layout_width="match_parent"
92         android:layout_height="wrap_content"
93         android:id="@+id/etAge"
94         android:inputType="number"
95         android:ems="10"
96         android:layout_alignBottom="@+id/tvAge"
97         android:layout_toEndOf="@+id/tvName" />
98 </RelativeLayout>

activity_student_detail

 

4(直接复制自网友,因为我没有很理解)

  当用户点击ListView的item时展示学生的详细信息的activity,所以我们需要一个特殊的id来检索学生的详细信息,并且这个id必须来自ListView,可以通过两个方法实现:

  • 最简单的方法,可以放id和name进listview的item中,展示给用户(不好的UI设计),当用户点击选中item时,将检索的记录传递到StudentDetail.java的activity。
  • 创建一个layout作为listview的item,通过item中包含学生的id(不过设置成隐藏)来检索学生的详细信息;

采用第二种方法,创建一个新的layout,view_student_entry.xml,代码如下:

《Android Studio下SQLite数据库的配置与使用(完)》
《Android Studio下SQLite数据库的配置与使用(完)》

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical" android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:weightSum="1">
 6 
 7     <TextView
 8         android:layout_width="wrap_content"
 9         android:layout_height="wrap_content"
10         android:id="@+id/student_Id"
11         android:visibility="gone"
12         android:layout_weight="0.00" />
13 
14     <TextView
15         android:id="@+id/student_Name"
16         android:layout_width="match_parent"
17         android:layout_height="wrap_content"
18         android:paddingLeft="6dip"
19         android:paddingTop="6dip"
20         android:textSize="22sp"
21         android:textStyle="bold"/>
22 </LinearLayout>

view_student_entry

 

<二>实现代码部分:

 1,为了创建表,需要使用到SQLiteDatabase类(实现CRUD操作)和SQLiteOpenHelper(用于数据库的创建和版本管理),

  下面先创建一个DBHelper类   

      CRUD:在MVC系统中,CRUD是什么意思?

      CRUD  的意思就是 Create(创建C)、Read(读取R)、Update(更新U)和Delete(删除D)的缩写。

    注意:每次我们调用数据库,都会自动打开并连接,所以注意代码实现过程中要close()数据库。

《Android Studio下SQLite数据库的配置与使用(完)》《Android Studio下SQLite数据库的配置与使用(完)》

 1 public class DBHelper extends SQLiteOpenHelper {
 2 
 3     //version number to upgrade database version
 4     //each time if you Add, Edit table, you need to change the
 5     //version number.
 6     //每次你对数据表进行编辑,添加时候,你都需要对数据库的版本进行提升
 7 
 8     //数据库版本
 9     private static final int DATABASE_VERSION=3;
10 
11     //数据库名称
12     private static final String DATABASE_NAME="sqlitestudy.db";
13 
14 
15     public DBHelper(Context context){
16         super(context,DATABASE_NAME,null,DATABASE_VERSION);
17     }
18 
19     @Override
20     public void onCreate(SQLiteDatabase db) {
21         //创建数据表
22         String CREATE_TABLE_STUDENT="CREATE TABLE "+ Student.TABLE+"("
23                 +Student.KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT ,"
24                 +Student.KEY_name+" TEXT, "
25                 +Student.KEY_age+" INTEGER, "
26                 +Student.KEY_email+" TEXT)";
27         db.execSQL(CREATE_TABLE_STUDENT);
28     }
29 
30     @Override
31     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
32         //如果旧表存在,删除,所以数据将会消失
33         db.execSQL("DROP TABLE IF EXISTS "+ Student.TABLE);
34 
35         //再次创建表
36         onCreate(db);
37     }
38 }

DBHelper

2,然后我们进入实体类创建 Student 

  包含有Student数据库表的列信息,也可以单独用于存储某个学生的信息,作为单个对象进行处理。

《Android Studio下SQLite数据库的配置与使用(完)》
《Android Studio下SQLite数据库的配置与使用(完)》

 1 package examples.ouc.com.sqlitedemo;
 2 
 3 /**
 4  * Created by Huskyboy on 2016/10/25.
 5  */
 6 
 7 public class Student {
 8     //表名
 9     public static final String TABLE="Student";
10 
11     //表的各个域名
12     public static final String KEY_ID="id";
13     public static final String KEY_name="name";
14     public static final String KEY_email="email";
15     public static final String KEY_age="age";
16 
17     //属性
18     public int student_ID;
19     public String name;
20     public String email;
21     public int age;
22 
23 }

Student

3,新建StudentRepo类,编写CRUD函数。

《Android Studio下SQLite数据库的配置与使用(完)》
《Android Studio下SQLite数据库的配置与使用(完)》

 1 public class StudentRepo {
 2     private DBHelper dbHelper;
 3 
 4     public StudentRepo(Context context){
 5         dbHelper=new DBHelper(context);
 6     }
 7 
 8     public int insert(Student student){
 9         //打开连接,写入数据
10         SQLiteDatabase db=dbHelper.getWritableDatabase();
11         ContentValues values=new ContentValues();
12         values.put(Student.KEY_age,student.age);
13         values.put(Student.KEY_email,student.email);
14         values.put(Student.KEY_name,student.name);
15         //
16         long student_Id=db.insert(Student.TABLE,null,values);
17         db.close();
18         return (int)student_Id;
19     }
20 
21     public void delete(int student_Id){
22         SQLiteDatabase db=dbHelper.getWritableDatabase();
23         db.delete(Student.TABLE,Student.KEY_ID+"=?", new String[]{String.valueOf(student_Id)});
24         db.close();
25     }
26     public void update(Student student){
27         SQLiteDatabase db=dbHelper.getWritableDatabase();
28         ContentValues values=new ContentValues();
29 
30         values.put(Student.KEY_age,student.age);
31         values.put(Student.KEY_email,student.email);
32         values.put(Student.KEY_name,student.name);
33 
34         db.update(Student.TABLE,values,Student.KEY_ID+"=?",new String[] { String.valueOf(student.student_ID) });
35         db.close();
36     }
37 
38     public ArrayList<HashMap<String, String>> getStudentList(){
39         SQLiteDatabase db=dbHelper.getReadableDatabase();
40         String selectQuery="SELECT "+
41                 Student.KEY_ID+","+
42                 Student.KEY_name+","+
43                 Student.KEY_email+","+
44                 Student.KEY_age+" FROM "+Student.TABLE;
45         ArrayList<HashMap<String,String>> studentList=new ArrayList<HashMap<String, String>>();
46         Cursor cursor=db.rawQuery(selectQuery,null);
47 
48         if(cursor.moveToFirst()){
49             do{
50                 HashMap<String,String> student=new HashMap<String,String>();
51                 student.put("id",cursor.getString(cursor.getColumnIndex(Student.KEY_ID)));
52                 student.put("name",cursor.getString(cursor.getColumnIndex(Student.KEY_name)));
53                 studentList.add(student);
54             }while(cursor.moveToNext());
55         }
56         cursor.close();
57         db.close();
58         return studentList;
59     }
60 
61     public Student getStudentById(int Id){
62         SQLiteDatabase db=dbHelper.getReadableDatabase();
63         String selectQuery="SELECT "+
64                 Student.KEY_ID + "," +
65                 Student.KEY_name + "," +
66                 Student.KEY_email + "," +
67                 Student.KEY_age +
68                 " FROM " + Student.TABLE
69                 + " WHERE " +
70                 Student.KEY_ID + "=?";
71         int iCount=0;
72         Student student=new Student();
73         Cursor cursor=db.rawQuery(selectQuery,new String[]{String.valueOf(Id)});
74         if(cursor.moveToFirst()){
75             do{
76                 student.student_ID =cursor.getInt(cursor.getColumnIndex(Student.KEY_ID));
77                 student.name =cursor.getString(cursor.getColumnIndex(Student.KEY_name));
78                 student.email  =cursor.getString(cursor.getColumnIndex(Student.KEY_email));
79                 student.age =cursor.getInt(cursor.getColumnIndex(Student.KEY_age));
80             }while(cursor.moveToNext());
81         }
82         cursor.close();
83         db.close();
84         return student;
85     }
86 }

实现CRUD

4,然后创建StudentDetail的Activity,我们用它来配合显示每个同学具体信息的界面

《Android Studio下SQLite数据库的配置与使用(完)》
《Android Studio下SQLite数据库的配置与使用(完)》

 1 public class StudentDetail extends AppCompatActivity implements View.OnClickListener {
 2 
 3     Button btnSava, btnDelete;
 4     Button btnClose;
 5     EditText editTextName;
 6     EditText editTextEmail;
 7     EditText editTextAge;
 8     private int _Student_ID=0;
 9     @Override
10     protected void onCreate(Bundle savedInstanceState) {
11         super.onCreate(savedInstanceState);
12         setContentView(R.layout.activity_student_detail);
13 
14         btnSava = (Button) findViewById(R.id.btnSave);
15         btnDelete = (Button) findViewById(R.id.btnDelete);
16         btnClose = (Button) findViewById(R.id.btnClose);
17 
18         btnSava.setOnClickListener(this);
19         btnDelete.setOnClickListener(this);
20         btnClose.setOnClickListener(this);
21 
22         _Student_ID = 0;
23         Intent intent = new Intent();
24         _Student_ID = intent.getIntExtra("student_Id",0);
25         StudentRepo repo = new StudentRepo(this);
26         Student student;
27         student = repo.getStudentById(_Student_ID);
28 
29         editTextAge.setText(String.valueOf(student.age));
30         editTextName.setText(student.name);
31         editTextEmail.setText(student.email);
32     }
33 
34 
35     @Override
36     public void onClick(View v) {
37         StudentRepo repo = new StudentRepo(this);
38         if (v == findViewById(R.id.btnSave)){
39             Student student = new Student();
40             student.age = Integer.parseInt(editTextAge.getText().toString());
41             student.email = editTextEmail.getText().toString();
42             student.name = editTextName.getText().toString();
43             student.student_ID = _Student_ID;
44 
45             if(_Student_ID==0){
46                 _Student_ID = repo.insert(student);
47 
48                 Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show();
49             }else{
50                 repo.update(student);
51                 Toast.makeText(this,"Student Record updated",Toast.LENGTH_SHORT).show();
52             }
53         }else if (v == findViewById(R.id.btnDelete)){
54             repo.delete(_Student_ID);
55             Toast.makeText(this,"Student Record deleted",Toast.LENGTH_SHORT).show();
56             finish();
57         }else if (v == findViewById(R.id.btnClose)){
58             finish();
59         }
60     }
61 }

StudentDetail

 5,最后对主界面MainActivity编写代码

    注意:这里MainActivity一定要技能ListActivity,否则ListView无法使用

《Android Studio下SQLite数据库的配置与使用(完)》
《Android Studio下SQLite数据库的配置与使用(完)》

 1 public class MainActivity extends ListActivity implements android.view.View.OnClickListener {
 2 
 3     private Button btnAdd,btnGetAll;
 4     private TextView student_Id;
 5     @Override
 6     protected void onCreate(Bundle savedInstanceState) {
 7         super.onCreate(savedInstanceState);
 8         setContentView(R.layout.activity_main);
 9         btnAdd = (Button) findViewById(R.id.btnAdd);
10         btnAdd.setOnClickListener(this);
11 
12         btnGetAll = (Button) findViewById(R.id.btnGetAll);
13         btnGetAll.setOnClickListener(this);
14     }
15 
16     @Override
17     public void onClick(View v) {
18         if (v== findViewById(R.id.btnAdd)){
19 
20             Intent intent = new Intent(MainActivity.this,StudentDetail.class);
21             intent.putExtra("student_Id",0);
22             startActivity(intent);
23 
24         }else {
25 
26             StudentRepo repo = new StudentRepo(this);
27             ArrayList<HashMap<String, String>> studentList =  repo.getStudentList();
28             if(studentList.size()!=0) {
29                 ListView lv = getListView();
30                 lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
31                     @Override
32                     public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
33                         student_Id = (TextView) view.findViewById(R.id.student_Id);
34                         String studentId = student_Id.getText().toString();
35                         Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class);
36                         objIndent.putExtra("student_Id", Integer.parseInt( studentId));
37                         startActivity(objIndent);
38                     }
39                 });
40                 ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList, R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_Name});
41                 setListAdapter(adapter);
42             }else{
43                 Toast.makeText(this, "No student!", Toast.LENGTH_SHORT).show();
44             }
45 
46         }
47     }
48 
49 }

MainActivity

 

6,最后附上一点我个人在编写过程中遇到得一点傻逼错误,希望自己和看官老爷(如果有幸的话)引以为戒

  

我们在学习Intent时候,它可以用来帮忙跳转界面,也可以用来帮助传递数据和参数。

例如下面这个例子(MainActivity中跳转到添加界面)

 if (v== findViewById(R.id.btnAdd)){

            Intent intent = new Intent(MainActivity.this,StudentDetail.class);
            intent.putExtra("student_Id",0);
            startActivity(intent);
        }

    我们利用intent.putExtra(“student_Id”,0); 将int型的0,放入了intent,“student_Id”类似于身份的id

在 StudentDetail 我们可以获取到我们传入的这个0

1 _Student_ID = 0;
2         Intent intent = new Intent();
3         //getIntExtra的第二个参数表示:
4         //如果没有获取到student_Id的值,那么我们就返回0
5         _Student_ID = intent.getIntExtra("student_Id",0);

 

而我犯的错是。。。。开始没有写第二个参数,因为getStringExtra是不用写第二个参数的,返回的应该是null?

再有就是,我前后的 student_Id  居然写的不一样,一直获取不到,导致app 一直各种闪退和崩溃

 

    原文作者:sqlite
    原文地址: https://www.cnblogs.com/icyhusky/p/5959535.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞